Basics Of Structured Query Language
Agenda
What is Database
What is Database Management System
History of Database
Need for Database
SQL
Classification of SQL
Each Command Explained
December 17, 2013
What is Data Base
Data Base is a collection of organized data that is stored electronically
on a computer or other digital device.
Designed to enable efficient storage, retrieval and manipulation of
data, and to provide a structured way of organize and manage
information.
In database, data is organized into tables, which consists of rows and
columns.
Database is used in wide range of applications, from small-scale
personal projects to large-scale enterprise systems.
They are also used to store and manage data in areas such
as Business, Health Care, Education others.
December 17, 2013
What is Data Base Management System
(DBMS)
A Database Management System (DBMS) is software that is used to
create, manage, and maintain Database.
It provides set of tools and functions for storing and retrieving data, as
well as for managing the security and integrity of the data
What is Relational Data Base Management System
(RDBMS)
A Relational Database Management System (RDBMS) is a type of
database management system that is based on the relational model of
data.
It provides set of tools and functions for creating, maintaining, and
querying relational databases.
Examples of RDBMS include Oracle, MySQL, Microsoft SQL Server
and PostgreSQL.
December 17, 2013
History of Data Base
YEAR Technology
First Electronic database created for scientific and business
1960
applications based on Hierarchical or Network Models.
1970 Relational Database Management Systems (RDBMS).
1980's and 1990's IBM's DB2 and Microsoft's SQL Server were introduced.
Early 2000's NoSQL
Recent Year's Big Data (Hadoop and Spark)
December 17, 2013
Why do we need Database Management
• We need to manage data because of following problems
with data management:
1. Data Organization and Structure
2. Data Integrity and Consistency
3. Data Sharing and Collaboration
4. Data Security
5. Data Scalability and Performance
6. Data Persistance
7. Data Analytics and Decision
December 17, 2013
SQL
SQL stands for Structured Query Language.
Structured Query Language (SQL) is a standard computer language
for relational database management and data manipulation.
SQL is used to search, insert, update and modify data.
First developed in the early 1970s at IBM by Raymond Boyce and
Donald Chamberlin, SQL was commercially released by Relational
Software Inc. (now known as Oracle Corporation) in 1979.
Data:
Data is a collection of unprocessed raw facts which has no meaning.
Ex: Customer's Bank Account Related
Details,CustomerAccountNumber, Balance in the bank etc
December 17, 2013
Classification of SQL
December 17, 2013
DATA DEFINITION LANGUAGE (DDL)
Data Definition Language actually consists of the SQL commands that can be used
to define the database schema. It simply deals with descriptions of the database
schema and is used to create and modify the structure of database objects in the
database.
CREATE: This command is used to create the database or its objects like tables,
index, stored procedures etc.
DROP: This Command is used to delete objects from the database.
ALTER: This is used to alter the structure of the table.
TRUNCATE: This is used to remove all records from a table, including all spaces
allocated for the records are removed.
December 17, 2013
DATA MANIPULATION LANGAUGE (DML)
The SQL commands that deals with the manipulation of data present in
the database belong to DML or Data Manipulation Language and this
includes most of the SQL statements.
INSERT: It is used to insert data into a table.
UPDATE: It is used to update records within the existing table.
DELETE: It is used to delete records from a database table
December 17, 2013
DATA QUERY LANGUAGE (DQL)
DQL Commands are used for performing queries on the data within schema
Object. The purpose of the DQL commands is to get some schema relation
Based on the query passed to it. The SELECT statement command allows
Us getting the data out of the database to perform operations with it. When
A SELECT is fired against a table or tables the result is compiled into a further
Temporary table, which is deployed or perhaps received by the program.
SELECT: It is used to retrieve data from the database.
December 17, 2013
DATA CONTROL LANGAUGE (DCL)
Data control language includes commands such as GRANT and REVOKE
which mainly deals with the rights, permissions, and other controls of the
Database system.
GRANT: This command gives users access privileges to the database.
REVOKE: This command withdraws the user's access privileges given by using
the GRANT command.
December 17, 2013
TRANSACTIONAL CONTROL LANGUAGE (TCL)
Transactions group a set of tasks into a single execution unit. Each transaction
begins with a specific task and ends when all the tasks in the group successfully
complete. If any of the tasks fail, the transaction fails. Therefore, a transaction has
only two results: success or failure. The following commands are used to control
The execution of transaction.
COMMIT: Commits a Transaction. It saves the transaction permanently to the disk.
ROLLBACK: By using this command, used can rollback to different save points that
User already created while carrying a transaction.
SAVEPOINT: We can save different parts of the same transaction with different
Names. For example, we can save all alter related queries with some name.
SET TRANSACTION/BEGIN: Specifies the characteristics for the transaction.
December 17, 2013
SQL Data Types
• Character Data Types
• Numeric Data Types
• Date and Time Data Types
December 17, 2013
Character Data Types
Data Type Description
Char (Size) It is used to store character data within the predefined length. It can be stored
up to 2000 bytes.
NChar (Size) It is used to store national character data within the predefined length. It can be
stored up to 2000 bytes.
VARCHAR(SIZE) It is the same as VARCHAR2(size). You can also use VARCHAR(size), but it is
suggested to use VARCHAR2(size)
VARCHAR2(size) It is used to store variable string data within the predefined length. It can be
stored up to 4000 byte.
NVARCHAR2(size) It is used to store Unicode string data within the predefined length. We have to
must specify the size of NVARCHAR2 data type. It can be stored up to 4000
bytes.
December 17, 2013
Numeric Data Types
Data Types Description
INTEGER Equal to INT size
INT A medium integer. Signed range is from -2147483648 to 2147483647.
Unsigned range is from 0 to 4294967295. The size parameter specifies
the maximum display width (which is 255)
SMALL INT A small integer. Signed range is from -32768 to 32767. Unsigned range
is from 0 to 65535. The size parameter specifies the maximum display
width (which is 255).
DECIMAL / NUMERIC (P, S) The decimal or numeric data type is used for storing exact decimal
numbers with a fixed precision and scale. The precision represents the
total number of digits that can be stored, while scale represents the
number of decimal places.
December 17, 2013
Date and Time Data Types
Data Types Description
DATE It is used to store a valid date-time format with a fixed length. Its range varies from
January 1, 4712 BC to December 31, 9999 AD.
TIME A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to '838:59:59'
TIMESTAMP It is used to store the valid date in YYYY-MM-DD with time hh:mm:ss format.
DATETIME A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The supported range is
from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. Adding DEFAULT and ON
UPDATE in the column definition to get automatic initialization and updating to the
current date and time
December 17, 2013
DDL
CREATE COMMAND
• Create table is used to create a new table in the database.
• To create a table you have to name the table and define its columns
and datatype for each column.
Syntax
CREATE TABLE table_name
(
column1 datatype [ NULL | NOT NULL | UNIQUE | PRIMARY KEY],
column2 datatype [ NULL | NOT NULL ],
...
column3 datatype [ NULL | NOT NULL ]
)
December 17, 2013
DROP COMMAND
• DROP TABLE statement is used to remove or delete a table from the database.
Syntax:
DROP TABLE table_name;
TRUNCATE COMMAND
• TRUNCATE TABLE is used to remove all the records from a table.
• It works same as DELETE statement but without specifying WHERE clause.
• It is generally used when you don't want have to worry about rolling back.
Syntax:
TRUNCATE TABLE table_name;
December 17, 2013
RENAME COMMAND
• The 'RENAME' command is used to rename database objects such as tables, columns, indexes or views.
• 'RENAME' command can vary depending on the database management system you are using.
• Renaming a Table Name.
Syntax: RENAME old_table_name to new_table_name;
• Renaming a Column Name.
Syntax: ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name;
December 17, 2013
ALTER Command
The ALTER TABLE statement is used to add, delete, or modify columns in and existing table.
1. To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;
2. To Modify a column in a table, use the following syntax:
ALTER TABLE table_name
MODIFY column_name datatype;
3. To delete a column in a table, use the following syntax
ALTER TABLE table_name
DROP COLUMN column_name;
December 17, 2013
DML
INSERT COMMAND
• INSERT command is used to add a single record or multiple records into the table.
SYNTAX
INSERT INTO table_name VALUES (value1,value2,value3,...);
• The second form specifies both the column names and the values to be inserted.
SYNTAX
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
December 17, 2013
UPDATE COMMAND
• The UPDATE statement is used to update existing records in a table.
Syntax
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
• The UPDATE statement which is used to update every record in the column.
• Without using WHERE clause.
Syntax
UPDATE table_name
SET column1=value1,column2=value2,…;
December 17, 2013
DELETE COMMAND
• The DELETE command is used to delete existing records in a table.
Syntax
DELETE FROM table_name
WHERE some_column=some_value;
• The DELETE statement which is used to delete every record in the column.
• Without using WHERE clause.
Syntax
DELETE FROM table_name;
December 17, 2013
DQL
SELECT COMMAND
• The SELECT statement is used to select data from the table.
• SQL Query to select specific columns in the table.
SELECT column_name, column_name FROM table_name;
• SQL Query to select all columns in the table.
SELECT * FROM table_name;
• SQL Query to select the data based on certain condition.
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
December 17, 2013
OPERATORS IN SQL
Comparison Operators
• = (Equal)
• <> or != (Not Equal)
• < (Less than)
• > (Greater than)
• >= (Greater than or equal to )
• <= (Lesser than or equal to)
Arithmetic Operators
• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
• % (Modulo Division)
December 17, 2013
Logical Operators
AND
• The AND operator displays a record if both the first condition AND the second
condition are true.
SELECT * FROM table_name
WHERE condition AND condition;
OR
• The OR operator displays a record if first condition OR the second condition are
true.
SELECT * FROM table_name
WHERE condition OR condition;
December 17, 2013
Logical Operators
NOT
• The NOT operator displays a record if the condition is NOT TRUE.
SYNTAX
SELECT column1, column2...
FROM table_name
WHERE NOT condition;
December 17, 2013
Aggregate Operators
• SUM () = Calculates the sum of set of values.
• AVG () = Calculates the average of a set of values.
• COUNT () = Counts the number of rows or non-null values.
• MIN () = Finds the minimum value in a set of values.
• MAX () = Finds the maximum value in a set of values
Assignment Operators
• = : Assigns a value to a variable or column
December 17, 2013
Pattern Matching Operators
LIKE Operator & NOT LIKE Operator
• The LIKE Operator is used in a WHERE Clause to search for specified pattern in a column.
• There are two wildcards often used in conjunction with the LIKE operator
1. The Percent sign (%) represents Zero, one or multiple characters.
2. The Underscore sign (_) represents One, single character.
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
Z% = Find any values that start with Z.
%Z = Find any values that end with Z.
%ka% = Find any values that have ka in any position.
_r% = Find any values that have "r" in second position.
Z_% = Find any values that start with "Z" and are at least 2 characters in length.
December 17, 2013
IN Operator & NOT IN Operator
IN Operator
• The IN operator allows you to specify multiple values in a WHERE clause.
• The IN operator is a shorthand of multiple OR conditions.
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
Sub Query
SELECT * FROM Customers
WHERE City IN (SELECT statement);
December 17, 2013
BETWEEN Operator & NOT BETWEEN
Operator
BETWEEN Operator
• The BETWEEN operator select values within a given range. The values can
be numbers, text or dates.
• The BETWEEN operator is inclusive: begin and end values are included.
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Sub Query
SELECT * FROM Customers
WHERE City IN (SELECT statement);
December 17, 2013
CONSTRAINTS IN SQL
Constraints in SQL
NOT NULL - Indicates that a column cannot store NULL value
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL
);
UNIQUE - Ensures that each row for a column must have a unique value
CREATE TABLE Persons (
ID int NOT NULL UNIQUE
);
December 17, 2013
Constraints in SQL
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or combination
of two or more columns) have an unique identity which helps to find a particular record in a table
more easily and quickly.
CREATE TABLE Persons (
ID int NOT NULL,
PRIMARY KEY (ID)
);
FOREIGN KEY -It points to a primary key in another table ensure the referential integrity of the data
one table to match values in another table.
CREATE TABLE Orders (
OrderID int NOT NULL,
PRIMARY KEY (OrderID),
FOREIGN KEY (OrderID) REFERENCES Persons(ID)
); December 17, 2013
Constraints in SQL
CHECK - Ensures that the value in a column meets a specific condition
CREATE TABLE Persons (
Age int,
CHECK (Age>=18)
);
DEFAULT - Specifies a default value when specified none for this column.
CREATE TABLE Persons (
ID int NOT NULL,
City varchar(255) DEFAULT 'Sandnes'
);
December 17, 2013
ALTER Command on CONSTRAINTS
• The ALTER TABLE statement is used to add, delete, or modify CONSTRAINTS in and
existing table.
1. To add a CONSTRAINT to column in a table, use the following syntax:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name (column_name);
2. To Modify a CONSTRAINT in a table, use the following syntax:
a) DROP THE CONSTRAINT.
b) ADD THE CONSTRAINT.
3. To delete a CONSTRAINT of column in a table, use the following syntax
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
December 17, 2013
CLAUSES IN SQL
FROM
• The FROM clause is used to specify the columns to retrieve in a query.
• It determines the data that will be returned as the result of the query.
SYNTAX
select * from table_name;
WHERE
• The WHERE clause is used to filter rows based on specific conditions in a query.
• It allows you to specify criteria to select only the rows that meet the specified
conditions.
SYNTAX
select * from table_name where column_name operator value;
December 17, 2013
ORDER BY
• The ORDER BY keyword is used to sort the result-set by one or more columns.
• The ORDER BY keyword sorts the records in ascending order by default.
• To sort the records in a descending order, you can use the DESC keyword.
Syntax
SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;
Example
SELECT * FROM Customers
ORDER BY Country;
SELECT * FROM Customers
ORDER BY Country DESC;
December 17, 2013
GROUP BY
• The GROUP BY statement is often used with aggregate functions (COUNT,
MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
Syntax [ it is used to group rows from one or more columns] compulsory
used the aggregate functions
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
December 17, 2013
HAVING
• The HAVING statement is used to filter the results of a 'GROUP BY' query
based on conditions applied to the grouped data.
• It is similar to WHERE clause could not be used in aggregate function
• It is used for filter the Group By Result
Example
• Retrieve the total order amount for customers who have placed orders with a
total amount greater than $1000.
SELECT customer_id, SUM(order_total) as total_amount
FROM orders
GROUP BY customer_id
HAVING SUM(order_total) > 1000;
December 17, 2013
SQL JOINS
SQL Joins
1. An SQL JOIN clause is used to combine rows from two or more tables, based on
a common field between them.
INNER JOIN or NORMAL JOIN :
2. Combine the rows and return the matching values in both tables
3. The INNER JOIN keyword selects all rows from both tables as long as there is a
match between the columns in both tables.
Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
December 17, 2013
LEFT JOIN
• Return all rows from the left table, and the matched rows from the right table.
• The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows
in the right table (table2).
• No match exists return the null values from right table.
Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;
December 17, 2013
RIGHT JOIN
• Return all rows from the right table, and the matched rows from the left table.
• The RIGHT JOIN keyword returns all rows from the right table (table1), with the matching
rows in the left table (table2).
• The result is NULL in the right side when there is no match.
Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
or:
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
December 17, 2013
FULL OUTER JOIN
• Return all rows from both tables, if there is any match or not.
• The FULL OUTER JOIN keyword returns all rows from the right table (table1) and all the
rows from the left table (table 2).
Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
December 17, 2013
SELF JOIN
• It is a join in which a table is joined with itself, specially when the table has a
FOREIGN KEY which references its own PRIMARY KEY.
• To join a table itself means that each row of the table is combined with itself
and with every other row of the table.
• The self join can be viewed as a join of two copies of the same table.
Syntax
SELECT t1.column_name, t2. column_name
FROM table t1, table t2
where t1.column_name = t2.column_name
December 17, 2013
Join Three tables with different joins
SYNTAX
Select * from Table1
Select * from Table2
Select * from Table3
Select * from Table1
Inner join Table2
on Table1.Column Name = Table2.Column Name
Left Outer join Table3
on Table2.Column name = Table3.Column Name
December 17, 2013
Normalization
Normalization
• Normalization is the process of organizing data within a database to eliminate
data anomalies, such as redundancy.
• In simpler terms, it involves breaking down a large, complex table into smaller
and simpler tables while maintaining data relationships.
• Normalization is commonly used when dealing with large datasets.
Scenarios where normalization is ofter used:
• Data Integrity
• Efficiency querying
• Storage Optimizations
December 17, 2013
Normalization
Why is normalization in SQL important?
• Reduces Redundancy
• Improves query performance
• Minimize update anomalies
• Enhances data integrity
What causes the need of normalization?
• Insertion, Deletion, and update anomalies
• Difficulties in managing relationships
• Partial dependencies
• Transitive dependencies
December 17, 2013
Normalization
Different types of Database Normalization
December 17, 2013
Normalization
First Normal Form (1NF)
• This normalization level ensures that each column in your data contains only
atomic values.
• Atomic values in this context means that each entry in a column in indivisible.
• It is like saying that each cell in spreadsheet should hold just one piece of
information.
• 1NF ensures atomicity of data, with each column cell containing only a single
value and each column having unique names.
December 17, 2013
Normalization
Second Normal Form (2NF)
• Eliminating the partial dependencies by ensuring that non-key attributes
depends only on the primary key.
• There should be a direct relationship between each column and the primary
key, and not between other columns.
Third Normal Form (3NF)
• Removes transitive dependencies by ensuring tha non-key attributes depends
only on the primary key.
• This level of normalization builds on 2NF.
December 17, 2013
Normalization
Boyce-Codd Normal Form (BCNF)
• This is more strict verison of 3NF that address additional anomalies.
• At this normalization level, every determinant is a candidate key.
Fourth Normal Form (4NF)
• This is the level that builds on BCNF by dealing with multi-valued
dependencies.
December 17, 2013
Normalization
Fifth Normal Form (5NF)
• 5NF is the highest normalization level that address join dependencies.
• It is used in specific scenarios to further minimize redundancy by breaking a
table into smaller tables.
December 17, 2013
Thank You