Structured Query Language
Structured Query Language
SQL Fundamentals
• Structure Query Language (SQL) is a database query language used for storing
and managing data in Relational DBMS.
• Various parts of SQL are -
• Data Definition Language(DDL): It consists of a set of commands for defining
relation schema, deleting relations, and modifying relation schemas.
• Data Manipulation Language(DML): It consists of set of SQL commands for
inserting tuples into relational schema, deleting tuples from or modifying tuples in
databases.
• Integrity: The SQL DDL includes commands for specifying integrity
constraints. These constraints must be satisfied by the databases.
• View definition: The SQL DDL contains the commands for defining views for
database.
• Transaction control: The SQL also includes the set of commands that indicate
beginning and ending of the transactions.
• Embedded SQL and Dynamic SQL: There is a facility of including SQL
commands in the programming languages like C,C++, COBOL or Java.
• Authorization: The SQL DDL includes the commands for specifying access
rights to relations and views.
Data Abstraction
The Basic data types used in SQL are -
(1) char(n): For representing the fixed length character string this data type is
used. For instance to represent name, designation, coursename, we use this data
type. Instead of char we can also use character. The n is specified by the user.
(2) varchar(n): The varchar means character varying. That means - for denoting
the variable length character strings this data type is used. The n is user specified
maximum character length.
(3) int: For representing the numeric values without precision, the int data type is
used.
(4) numeric: For representing, a fixed point number with user-specified precision
this data type is used. The number consists of m digits plus sign k digits are to the
right of precision. For instance the numeric(3,2) allows 333.11 but it does not
allow 3333.11
(5) smallint: It is used to store small integer value. It allows machine dependent
subset of integer type.
(6) real: It allows the floating point, double precision numbers.
(7) float(n): For representing the floating point number with precision of at least n
digits this data type is used.
1. Creation
Syntax
CREATE DATABASE database_name;
Example
CREATE DATABASE Person _DB
Step 2: The table can be created inside the database as follows -
CREATE TABLE table name (
Col1_name datatype,
col2 _name datatype,
……
coln_name datatype
);
Example
CREATE TABLE person_details{
AdharNo int,
FirstName VARCHAR(20),
MiddleName VARCHAR(20),
LastName VARCHAR(20),
Address VARCHAR(30),
City VARCHAR(10)
}
The blank table will be created with following structure
Person_details
2. Insertion
We can insert data into the table using INSERT statement.
Syntax
INSERT INTO table_name (col1, col2,...,coln)
VALUES (value1,value,...., valuen)
Example
INSERT INTO person_details (AdharNo, FirstName, MiddleName, LastName,
Address, City)
VALUES (111, 'AAA','BBB','CCC','M.G. Road', 'Pune')
The above query will result into –
3. Select
• The Select statement is used to fetch the data from the database table.
• The result returns the data in the form of table. These result tables are called
resultsets.
• We can use the keyword DISTINCT. It is an optional keyword indicating that the
answer should not contain duplicates. Normally if we write the SQL without
DISTINCT operator then it does not eliminate the duplicates.
Syntax
SELECT col1, col2, ...,coln FROM table_name;
Example
SELECT AdharNo, FirstName, Address, City from person_details
The result of above query will be
• If we want to select all the records present in the table we make use of *
character.
Syntax
SELECT FROM table_name;
Example
SELECT * FROM person_details;
The above query will result into
4. Where Clause
The WHERE command is used to specify some condition. Based on this condition
the data present in the table can be displayed or can be updated or deleted.
Syntax
SELECT col1,col2, ...,coln
FROM table_name
WHERE condition;
Example
Consider following table-
5. Update
• For modifying the existing record of a table, update query is used.
Syntax
UPDATE table name
SET col1-value1, col2-value2,...
WHERE condition;
Example
Consider following table
Person_details table
If we execute following query
UPDATE rerson_details
SET city 'Chennai'
WHERE AdharNo=333
The result will be
6. Deletion
We can delete one or more records based on some condition. The syntax is as
follows -
Syntax
DELETE FROM table_name WHERE condition;
Example
DELETE FROM person_details
WHERE AdharNo=333
The result will be –
We can delete all the records from table. But in this deletion, all the records get
deleted without deleting table. For that purpose the SQL statement will be
DELETE FROM person_details;
7. Logical Operators
• Using WHERE clause we can use the operators such as AND, OR and NOT.
• AND operator displays the records if all the conditions that are separated using
AND operator are true.
• OR operator displays the records if any one of the condition separated using OR
operator is true.
• NOT operator displays a record if the condition is NOT TRUE.
Consider following table
Syntax of AND
SELECT col1, col2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3...;
Example of AND
If we execute following query-
SELECT AdharNo, FirstName, City
FROM person_details
WHERE AdharNo=222 AND City= 'Pune';
The result will be –
Syntax of OR
SELECT col1, col2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
Example of OR
SELECT AdharNo, FirstName, City
FROM person_details
WHERE City='Pune' OR City='Mumbai';
The result will be –
Syntax of NOT
SELECT col1, col2, ...
FROM table_name
WHERE NOT condition;
Example of NOT
SELECT AdharNo, FirstName, City
FROM person_details
WHERE NOT City='Pune';
The result will be
8. Order By Clause
• Many times we need the records in the table to be in sorted order.
• If the records are arranged in increasing order of some column then it is called
ascending order.
• If the records are arranged in decreasing order of some column then it is called
descending order.
• For getting the sorted records in the table we use ORDER BY command.
• The ORDER BY keyword sorts the records in ascending order by default.
Syntax
SELECT col1, col2,...,coln
FROM table_name
ORDER BY col1,col2.... ASC | DESC
Here ASC is for ascending order display and DESC is for descending order
display.
Example
Consider following table
SELECT *
FROM person_details
ORDER BY AdharNo DESC;
The above query will result in
9. Alteration
There are SQL command for alteration of table. That means we can add new
column or delete some column from the table using these alteration commands.z
Syntax for Adding columns
ALTER TABLE table_name
ADD column_name datatype;
Example
Consider following table
Dept Table:
• Notice that the "EmpID" column in the "Dept" table points to the "EmpID"
column in the "Employee" table.
• The "EmpID" column in the "Employee" table is the PRIMARY KEY in the
"Employee" table.
• The "EmpID" column in the "Dept" table is a FOREIGN KEY in the "Dept"
table.
• The FOREIGN KEY constraint is used to prevent actions that would destroy
links between tables.
• The FOREIGN KEY constraint also prevents invalid data from being inserted
into the foreign key column, because it has to be one of the values contained in the
table it points to.
• The purpose of the foreign key constraint is to enforce referential integrity but
there are also performance benefits to be had by including them in your database
design.
The table Dept can be created as follows with foreign key constraint.
CREATE TABLE DEPT (
DeptID int
DeptName VARCHAR(20),
EmpID int,
PRIMARY KEY(DeptID),
FOREIGN KEY (EmpID)
REFERENCES EMPLOYEE(EmpID)
);
(3) Unique
Unique constraint is used to prevent same values in a column. In the EMPLOYEE
table, for example, you might want to prevent two or more employees from having
an identical designation. Then in that case we must use unique constraint.
We can set the constraint as unique at the time of creation of table, or if the table is
already created and we want to add the unique constraint then we can use ALTER
command.
For example -
CREATE TABLE EMPLOYEE(
EmpID INT NOT NULL,
Name VARCHAR (20) NOT NULL,
Designation VARCHAR(20) NOT NULL UNIQUE,
Salary DECIMAL (12, 2),
PRIMARY KEY (EmpID)
);
If table is already created then also we can add the unique constraint as follows -
ALTER TABLE EMPLOYEE
MODIFY Designation VARCHAR(20) NOT NULL UNIQUE;
(4) NOT NULL
• By default the column can have NULL values.
• NULL means unknown values.
• We can set the column values as non NULL by using the constraint NOT NULL.
• For example
CREATE TABLE EMPLOYEE(
EmpID INT NOT NULL,
Name VARCHAR (20) NOT NULL,
Designation VARCHAR(20) NOT NULL,
Salary DECIMAL (12, 2) NOT NULL,
PRIMARY KEY (EmpID)
);
(5) CHECK
The CHECK constraint is used to limit the value range that can be placed in a
column.
For example
CREATE TABLE parts (
Part_no int PRIMARY KEY,
Description VARCHAR(40),
Price DECIMAL(10, 2) NOT NULL CHECK(cost > 0)
);
(6) IN operator
The IN operator is just similar to OR operator.
It allows to specify multiple values in WHERE clause.
Syntax
SELECT col1,col2,....
FROM table_name
WHERE column-name IN (value1, value2,...);
Example
Consider following table
Employee
Query: Find the names of students who have reserved the books with book isbn
Select Student.sname,Reserve.isbn
From Student, Reserve
Where Student.sid=Reserve.sid
Use of SQL Join
The SQL Joins clause is used to combine records from two or more tables in a
database. A JOIN is a means for combining fields from two tables by using values
common to each.
Example: Consider two tables for using the joins in SQL. Note that cid is common
column in following tables.
1) Inner Join:
• The most important and frequently used of the joins is the INNER JOIN. They
are also known as an EQUIJOIN.
• The INNER JOIN creates a new result table by combining column values of two
alqutul no tables (Table1 and Table2) based upon the join-predicate.
• The query compares each row of tablel with each row of Table2 to find all pairs
of rows which satisfy the join-predicate.
• When the join-predicate is satisfied, column values for each matched pair of rows
of A and B are combined into a result row. It can be represented as:
2) Left Join:
• The SQL LEFT JOIN returns all rows from the left table, even if there are no
matches in the right table. This means that if the ON clause matches 0 (zero)
records in the right table; the join will still return a row in the result, but with
NULL in each column from the right table.
• This means that a left join returns all the values from the left table, plus matched
values from the right table or NULL in case of no matching join predicate.
• It can be represented as –
Select S.sname,R.isbn
From Student as S, Reserve as R
Where S.sid=R.sid
In above case we could shorten the names of tables Student and Reserve as S and
R respectively.
Another reason to rename a relation is a case where we wish to compare tuples in
the same relation. We then need to take the Cartesian product of a relation with
itself. For example-
If the query is - Find the names of students who reserve the book of isbn005. Then
the SQL statement will be -
Select S.sname, R.isbn
From Student as S, Reserve as R
Where S.sid-R.sid and S.isbn=005
2) Attribute Specification in Select clause: The symbol * is used in select clause
to denote all attributes. For example - To select all the records from Student table
we can write
Select* from Student
3) Ordering the display of tuples: For displaying the records in particular order
we use order by clause.
The general syntax with ORDER BY is
SELECT column_name(s)
FROM table_name
WHERE condition
ORDER BY column_name(s)
• Example: Consider the Student table as follows-
Syntax of AND
SELECT column1, column2, ....
FROM table name
WHERE condition1 AND condition2 AND condition3 ...;
Example: Find the student having name "AAA" and lives in city "Pune"
SELECT
FROM Students
Where sname='AAA' AND city= 'Pune'
Output
Syntax OR
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
Example: Find the student having name "AAA" OR lives in city "Pune"
SELECT *
FROM Students
Where sname='AAA' OR city='Pune'
Output
Syntax NOT
SELECT column1, column2, ..
FROM table name
WHERE NOT condition
Example: Find the student who do not have city "Pune"
SELECT *
FROM Students
Where NOT city='Pune'
Output
String Operations
• For string comparisons, we can use the comparison operators =, <, >,<,>=> with
the ordering of strings determined alphabetically as usual.
• SQL also permits a variety of functions on character strings such as concatenation
suing operator, extracting substrings, finding length of string, converting strings to
upper case(using function upper(s)) and lowercase(using function lower(s)),
removing spaces at the end of string(using function(trim(s)) and so on.
• Pattern matching can also be performed on strings using two types of special
characters -
• Percent(%): It matches zero, one or multiple characters
• Underscore(_): The _ character matches any single character.
• The percentage and underscore can be used in combinations.
• Patterns are case sensitive. That means upper case characters do not match
lowercase characters or vice versa.
• For instance:
• 'Data%' matches any string beginning with "Data", For instance it could be
with a blen "Database", "DataMining","DataStructure"
• ' _ _ _' matches any string of exactly three characters.
• ' _ _ _'%'matches any string of at least length 3 characters.
• The LIKE clause can be used in WHERE clause to search for specific patterns.
• For example - Consider following Employee Database
(1) Find all the employee with EmpName starting with "s"
SQL Statement:
SELECT FROM Employee
WHERE EmpName LIKE 's%'
Output
(2) Find the names of employee whose name begin with S and end with a
SQL Statement:
SELECT EmpName FROM Employee
WHERE EmpName LIKE 'S%a'
Output
(3) Find the names of employee whose name begin with S and followed by exactly
four characters
SELECT EmpName FROM Employee
WHERE EmpName LIKE 'S_ _ _’
Output
Set Operations
1) UNION: To use this UNION clause, each SELECT statement must have
i) The same number of columns selected
ii) The same number of column expressions
iii) The same data type and
iv) Have them in the same order
This clause is used to combine two tables using UNION operator. It replaces the
OR operator in the query. The union operator eliminates duplicate while the union
all query will retain the duplicates.
Syntax
The basic syntax of a UNION clause is as follows -
SELECT column1 [, column2]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ].
[WHERE condition]
Here, the given condition could be any given expression based on your
requirement.
Consider Following relations –
Example: Find the names of the students who have reserved the 'DBMS' book or
'OS' Book
The query can then be written by considering the Student, Reserve and Book table
as
SELECT S.sname
FROM Student S, Reserve R, Book B
WHERE S.sid-R.sid AND R.isbn=B.isbn AND B.bname='DBMS'
UNION
SELECT S.sname
FROM Student S, Reserve R, Book B
WHERE S.sid-R.sid AND R.isbn=B.isbn AND B.bname='OS'
2) INTERSECT: The common entries between the two tables can be represented
with the help of Intersect operator. It replaces the AND operator in the query.
Syntax
The basic syntax of a INTERSECT clause is as follows --
SELECT column1 [, column2]
FROM table1 [, table2 ]
[WHERE condition]
INTERSECT
SELECT column1 [, column2]
FROM table1 [, table2 ]
[WHERE condition]
Example: Find the students who have reserved both the 'DBMS' book and 'OS'
Book
The query can then be written by considering the Student, Reserve and Book table
as
SELECT S.sid, S.sname
FROM Student S, Reserve R, Book B
WHERE S.sid-R.sid AND R.isbn=B.isbn AND B.bname='DBMS'
INTERSECT
SELECT S.sname
FROM Student S, Reserve R, Book B
WHERE S.sid-R.sid AND R.isbn=B.isbn AND B.bname='OS'
3) EXCEPT: The EXCEPT clause is used to represent the set-difference in the
query. This query is used to represent the entries that are present in one table and
not in other.
Syntax:
The basic syntax of a EXCEPT clause is as follows -
SELECT column1 [, column2 |
FROM table1 [, table2 ]
[WHERE condition]
EXCEPT
SELECT column1 [, column2]
FROM table1 [, table2]
[WHERE condition]
Example: Find the students who have reserved both the 'DBMS' book but not
reserved 'OS' Book
The query can then be written by considering the Student, Reserve and Book table
as
SELECT S.sid, S.sname
FROM Student S, Reserve R, Book B
WHERE S.sid=R.sid AND R.isbn=B.isbn AND B.bname='DBMS'
EXCEPT
SELECT S.sname
FROM Student S, Reserve R, Book B
WHERE S.sid=R.sid AND R.isbn=B.isbn AND
B.bname='OS'
Aggregate Functions
• An aggregate function allows you to perform a calculation on a set of values to
return a single scalar value.
• SQL offers five built-in aggregate functions:
1. Average: avg
2. Minimum: min
3. Maximum : max
4. Total: sum
5. Count:
1. Basic Aggregation
The aggregate functions that accept an expression parameter can be modified by
the keywords DISTINCT or ALL. If neither is specified, the result is the same as if
ALL were specified.
Syntax of all the Aggregate Functions
AVG([ DISTINCT | ALL ] expression)
COUNT(*)
COUNT([ DISTINCT | ALL | expression)
MAX( | DISTINCT | ALL ] expression)
MIN([ DISTINCT | ALL ] expression)
SUM([DISTINCT | ALL ] expression)
• The avg function is used to compute average value. For example - To compute
average marks of the students we can use t
SQL Statement
SELECT AVG(marks)
FROM Students
• The Count function is used to count the total number of values in the specified
field. It works on both numeric and non-numeric data type. COUNT (*) is a special
implementation of the COUNT function that returns the count of all the rows in a
specified table. COUNT (*) also considers Nulls and duplicates. For example
Consider following table
SQL Statement
SELECT COUNT(*)
FROM Test
Output
4
SELECT COUNT(ALL id)
FROM Test
Output
3
• The min function is used to get the minimum value from the specified column.
For example - Consider the above created Test table
SQL Statement
SELECT Min(value)
FROM Test
Output
100
• The max function is used to get the maximum value from the specified column.
For example - - Consider the above created Test table
SQL Statement
SELECT Max(value)
FROM Test
Output
400
• The sum function is used to get total sum value from the specified column. For
example - Consider the above created Test table
SOL Statement
SELECT sum(value)
FROM Test
Output
1000
(ii) Having:
• HAVING filters records that work on summarized GROUP BY results.
• HAVING applies to summarized group records, whereas WHERE applies to been
individual records.
• Only the groups that meet the HAVING criteria will be returned.
• HAVING requires that a GROUP BY clause is present.
• WHERE and HAVING can be in the same query.
• Syntax:
SELECT column-names
FROM table-name
WHERE condition
GROUP BY column-names
HAVING condition
Example: Consider the Student table as follows –
Query: Find the total marks of each student in the city named 'Pune' and 'Mumbai'
only
SELECT SUM(marks), city
FROM Student
GROUP BY city
HAVING city IN('Pune', 'Mumbai')
Output
• The result will be as follows-
Nested Queries
In nested queries, a query is written inside a query. The result of inner query is
used in execution of outer query.
There are two types of nested queries:
i) Independent Query:
• In independent nested queries, query execution starts from innermost query to
outermost queries.
• The execution of inner query is independent of outer query, but the result of inner
query is used in execution of outer query.
• Various operators like IN, NOT IN, ANY, ALL etc are used in writing
independent nested queries.
• For example - Consider three tables namely Student, City and Student_City as
follows-
• Example 1 - If we want to find out sid who live in city 'Pune' or 'Chennai'. We
can then write independent nested query using IN operator. Here we can use the IN
operator allows you to specify multiple values in a WHERE clause. The IN
operator is a shorthand for multiple OR conditions.
Step 1: Find cid for cname='Pune' or 'Chennai'. The query will be
SELECT cid
FROM City
WHERE cname='Pune' or 'Chennai'
Step 2: Using cid obtained in step 1 we can find the sid. The query will be
SELECT sid
FROM Student_City
WHERE cid IN
(SELECT cid FROM City WHERE cname='Pune' or cname='Chennai')
The inner query will return a set with members 101 and 103 and outer query will
return those sid for which cid is equal to any member of set (101 and 103 in this
case). So, it will return 1, 2 and 4.
Example 2: If we want to find out sname who live in city 'Pune' or 'Chennai'.
SELECT sname FROM Student WHERE sid IN
(SELECT sid FROM Student City WHERE cid IN
(SELECT cid FROM City WHERE cname='Pune' or cname='Chennai'))
ii) Co-related Query:
In co-related nested queries, the output of inner query depends on the row which is
being currently executed in outer query. For example
If we want to find out sname of Student who live in city with cid as 101, it can be
done with the help of co-related nested query as:
SELECT sname FROM Student S WHERE EXISTS
(SELECT * FROM Student_City SC WHERE S.sid=SC.sid and SC.cid=101)
Here For each row of Student S, it will find the rows from Student_City where
S.sid SC.sid and SC.cid=101.
If for a sid from Student S, atleast a row exists in Student City SC with cid=101,
then inner query will return true and corresponding sid will be returned as output.
Modification of Databases
The modification of database is an operation for making changes in the existing
databases. Various operations of modification of database are insertion, deletion
and updation of databases.
1. Deletion: The delete command is used to delete the existing record.
Syntax
delete from table_name
where condition;
Example
delete from student
where RollNo=10
2. Insertion: The insert command is used to insert data into the table. There are
two syntaxes of inserting data into SQL
Syntax
(i) Insert into table_name (column1, column2, column3, ...)
values (value1, value2, value3, ...);
(ii) insert into table_name
values (value1, value2, value3, ...);
Example
(i) insert into Student (RollNo,Name, Makrs) values (101, 'AAA',56.45)
(ii) insert into Student values(101,'AAA',56.45)
3. Update: The update statement is used to modify the existing records in the
table.
update table_name
set column1-value1, column2=value2,...
where condition;
Example :
Delete student
Set Name='WWW'
where Roll No=101
Review Questions
1. Explain aggregate functions in SQL with example. AU: May-18, Marks 13
2. Write DDL, DML, DCL commands for the students database. AU: Dec.-17,
Marks 7
3. Explain about SQL fundamentals. AU: May-16, Marks 8
4. Explain about Data Definition Language. AU: May-16, Marks 8
5. Explain the six clauses in the syntax of SQL query and show what type of
constructs can be specified in each of the six clauses. Which of the six clauses are
required and which are optional? AU: Dec.-15, Marks 16
6. Explain- DDL and DML. AU: Dec.-14, Marks 8