Unit 3
Form of Basic SQL Query
Examples of Basic SQL Queries
Introduction to Nested Queries Correlated.
Nested Queries Set Comparison Operators
Aggregative Operators
NULL values
Comparison using Null values
Logical connectivity’s AND, OR and NOT
Impact on SQL Constructs
Outer Joins Disallowing NULL values
Complex Integrity Constraints in SQLTriggers and
Active Data bases.
Database Languages
DDL (Data Definition Language)
DML (Data Manipulation language)
DCL (Data control language)
DQL (Data Query Language)
DDL
•DDL stands for Data Definition Language.
•It is used to define database structure or pattern.
•It is used to create schema, tables, indexes, constraints,
etc. in the database.
•Using the DDL statements, you can create the skeleton of
the database.
•Data definition language is used to store the information of
metadata like the number of tables and schemas, their
names, indexes, columns in each table, constraints, etc.
Here are some tasks that come under DDL:
Create: It is used to create tables in the database.
Alter: It is used to alter the structure of the database.
Drop: It is used to delete objects from the database.
Truncate: It is used to remove all records from a table.
Rename: It is used to rename an table.
CREATE TABLE table-name (Fieldname1
data_type, Fieldname2 data_type , …. ….. ….)
CREATE TABLE Sailors (sid NUMBER(2), sname
VARCHAR2(20), rating NUMBER(2))
ALTER TABLE tablename ADD (fieldname
Field_datatype)
ALTER TABLE Sailors ADD (age NUMBER(2))
ALTER TABLE Sailors Modify (age NUMBER(2))
ALTER TABLE Sailors drop column age
ALTER TABLE Sailors rename sid to studentid
DROP command
Used to delete an existing table
Syntax: DROP TABLE tablename
Example: DROP TABLE Sailors
TRUNCATE command
TRUNCATE Removes all rows from a table without backup
Syntax: TRUNCATE table tablename
Example: TRUNCATE table Sailors
RENAME Command
Syntax: RENAME TABLE old_table_name to new_table_name;
Example: RENAME TABLE student to students_info;
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.
• Examples of DML:
• INSERT – is used to insert data into a table.
• UPDATE – is used to update existing data within a
table.
• DELETE – is used to delete records from a database
table.
INSERT command
Inserting record into a table
Syntax: INSERT INTO table-name VALUES (field1,field2,…)
Example:
INSERT INTO Sailors values (22,'Dustin',7,45.0)
Inserting records from another table
Syntax: INSERT INTO table_name1 SELECT * FROM table_name2
Example: INSERT INTO Sailors1 SELECT * FROM Sailors;
CREATE TABLE Sailors1 as Select * from Sailors;
UPDATE command
For modifying attribute values of (some) tuples in a table
Syntax: UPDATE tablename SET column1=value1,…,
columnn=valuen WHERE condition
Example: UPDATE Sailors SET age=34.5 WHERE sid=22
DELETE command
Removing specified rows from a table
Syntax: DELETE FROM tablename WHERE condition
Example: DELETE FROM Sailors WHERE sid=22
DROP command
Used to delete an existing table
Syntax: DROP TABLE tablename
Example: DROP TABLE Sailors
TRUNCATE command
TRUNCATE Removes all rows from a table without backup
Syntax: TRUNCATE table tablename
Example: TRUNCATE table Sailors
Removing all rows from a table
Syntax: DELETE FROM tablename
Example: DELETE FROM Sailors
SQL is the most widely used commercial relational
database language
THE FORM OF A BASIC SQL QUERY
SELECT [DISTINCT] field names
FROM table names
WHERE condition
SELECT clause contains fields to be displayed in the result
FROM clause contains table names
Optional WHERE clause contains conditions on the tables
mentioned in the FROM clause
Rename Operator
• The SQL allows renaming relations and
attributes using the as clause:
• old-name as new-name
• Find the name, and id of all sailors; rename the
column name id as sailornumber.
Select sname,id as sailornumber
from sailors ;
DCL
-GRANT
-REVOKE
GRANT Command
It is used to provide access rights or privileges on the
database objects to the users.
Syntax:
GRANT privilege_name
ON object_name
TO {user_name |PUBLIC}
13
privilege_name is the access right or privilege granted
to the user. Some of the access rights are ALL, and
SELECT
object_name is database object name like TABLE,
VIEW, STORED PROCEDURE
user_name is the name of the user to whom an access
right is being granted
--PUBLIC is used to grant access rights to all users
14
Example:
GRANT SELECT ON employee TO user1;
User1 will be able to select data from employee
database
SQL REVOKE Command:
The REVOKE command removes user access rights
or privileges to the database objects
15
Syntax:
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC}
Eample:
REVOKE SELECT ON employee FROM user1;
REVOKE a SELECT privilege on employee table from
user1
user1 will not be able to SELECT data from that table
16
TCL (Transaction Control Language)
COMMIT command
•COMMIT command is used to permanently save any transaction
into the database.
•When we use any DML command like INSERT, UPDATE or
DELETE, the changes made by these commands are not
permanent, until the current session is closed, the changes made
by these commands can be rolled back.
•To avoid that, we use the COMMIT command to mark the
changes as permanent.
•Following is commit command's syntax,
commit;
ROLLBACK command
•This command restores the database to last commited state.
•If we have used the UPDATE command to make some changes
into the database, and realise that those changes were not required,
then we can use the ROLLBACK command to rollback those
changes, if they were not commited using the COMMIT command.
AND, OR, NOT and IN Operators
Question: Find the names of sailors who have reserved boat number
103
Query: SELECT sname
FROM Sailors S, Reserves R
WHERE S.sid=R.sid AND R.bid=103
Output:
SNAME
Dustin
Lubber
Horatio
19
Question: Find the names of sailors who have reserved a red or green
boat
Query: SELECT sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid=R.sid AND R.bid=B.Bid
AND (B.color=‘red’ OR B.color=‘green’);
20
IN
Used to check whether an attribute value matches a value
contained within a set of listed values
Question: Find all sailors whose age is in the list of
values(15.0,33.2,45.7,63.5)
Query: SELECT *
FROM Sailors
WHERE age IN (15.0,33.2,45.7,63.5)
Output:
SID SNAME RATING AGE
95 Bob 3 63.5 21
NOT
Used to check whether an attribute value does not match
with a value contained in a set of listed values
Question: Find all sailors whose age is not present in the list of
values(15.0,33.2,45.7,63.5)
Query: SELECT *
FROM Sailors
WHERE age NOT IN (15.0,33.2,45.7,63.5)
22
STRING operators
“%” character is used to match any substring
“_” character is used to match any character
Expresses patterns by using the ‘like’ comparison operator
Example1
SELECT *
FROM Sailors
WHERE sname LIKE '_u%'
23
Output:
RATIN
SID SNAME AGE
G
22 Dustin 7 45
31 Lubber 8 55.5
Example2 58 Rusty 10 35
SELECT *
FROM Sailors
WHERE sname LIKE 'A_d_'
Output:
RATIN
SID SNAME AGE
G 24
SET operators
Operations such as union, intersect, minus and exists
operate on relations
Corresponding to relational-algebra operations U, ∩ and –
Relations participating in the operations must be
compatible; i.e., must have same set of attributes
<query 1> <set operator> <query 2>
25
Example (union)
SELECT *
FROM Sailors
UNION
SELECT *
FROM Sailors1
26
Example (intersect)
SELECT *
FROM Sailors
INTERSECT
SELECT *
FROM Sailors1
27
Example (minus)
SELECT *
FROM Sailors
MINUS
SELECT *
FROM Sailors1
28
Nested Queries
A nested query is a query that has another query embedded
within it
The embedded query is called a subquery
Example:
Find the names of sailors who have reserved boat 103
SELECT S.sname
FROM Sailors S
WHERE S.sid IN
(SELECT R.sid FROM Reserves R WHERE R.bid=103)
Find the names of sailors who have reserved a blue boat
SELECT S.sname
FROM Sailors S
WHERE S.sid IN
(SELECT R.sid FROM Reserves R
WHERE R.bid IN
(SELECT B.bid FROM Boats B WHERE
B.color='blue'))
Correlated Nested Queries
In Correlated Nested Queries, inner subquery could depend on
the row that is currently being examined in the outer query
Find the names of sailors who have reserved boat 103
Query:
SELECT S.sname
FROM Sailors S
WHERE EXISTS
(SELECT * FROM Reserves R WHERE
R.bid = 103 AND R.sid = S.sid)
The EXISTS operator is another set comparison operator,
such as IN
It allows us to test whether a set is nonempty.
Thus, for each Sailor row S, we test whether the set of
Reserves rows R such that R.bid = 103 AND S.sid = R.sid
is nonempty. If so, sailor S has reserved boat 103, and we
retrieve the name
The occurrence of S in the subquery (in the form of the
literal S.sid) is called a correlation, and such queries are
called correlated queries
32
COMPARISION OPERATORS
These operators can be used in ‘WHERE’ clause and
‘HAVING’ clause
SYMBOL MEANING
= Equal to
< Less than
<= Less than or equal to
> Grater than
>= Greater than or equal to
<> or != or ^= Not equal to
33
SET-COMPARISION OPERATORS
EXISTS, IN along with their negated versions
SQL also suports op ANY and op ALL
Where op is one of the arithmetic comparison operators
(<,<=,>,>=,<>,=)
34
Example
Find sailors whose rating is better than some sailor called
Horatio
SELECT S1.sname, S1.rating
FROM Sailors S1
WHERE S1.rating > ANY (SELECT S2.rating FROM
Sailors S2 WHERE S2.sname='Horatio' )
SNAME RATING
Rusty 10
Zorba 10
Horatio 9
Lubber 8
Andy 8 35
Find sailors whose rating is better than every sailor called
Horatio
SELECT S1.sname, S1.rating
FROM Sailors S1
WHERE S1.rating > ALL ( SELECT S2.rating FROM
Sailors S2 WHERE S2.sname='Horatio' )
SNAME RATING
Rusty 10
Zorba 10
36
AGGREGATE OPERATORS
In addition to simply retrieving data, we often want to
perform some computation or summarization
SQL supports the following aggregate operators which can
be applied on any column, say A, of a relation(table):
1.COUNT ([DISTINCT] A): The number of (unique)
values in the A column
2.SUM ([DISTINCT] A): The sum of all (unique) values
in the A column
3.AVG ([DISTINCT] A): The average of all (unique)
values in the A column 37
4. MAX (A): The maximum value in the A column
5. MIN (A): The minimum value in the A column
Note: not specify DISTINCT in conjunction with MIN or
MAX
Examples:
Question: Find the average age of all sailors
Query:
SELECT AVG (age)
FROM Sailors
Output:
AVG(AGE)
36.9
38
Question: Find the name and age of the oldest sailor
Query:
SELECT S1.sname, S1.age
FROM Sailors S1
WHERE S1.age = ( SELECT MAX (S2.age) FROM Sailors
S2 )
Output:
SNAME AGE
Bob 63.5
Question: Count the number of sailors
Query:
SELECT COUNT (*)
FROM Sailors
Output: COUNT(*)
10 39
The GROUP BY and HAVING Clauses
GROUP BY used to apply aggregate operators to each
number of groups of rows in a relation
HAVING is used to place a condition, which is applied on
the groups of rows
general form:
SELECT [DISTINCT] fieldname
FROM table names
GROUP BY fieldname
HAVING group-condition
40
Examples
Question: Find the number of sailors belongs to each rating
level
Query:
SELECT rating, COUNT(rating)
FROM Sailors
GROUP BY rating RATING COUNT(RATING)
Output: 1 1
3 2
7 2
8 2
9 1
10 2 41
Question: Find the age of the youngest sailor for each rating
level
Query:
SELECT rating, MIN (age)
FROM Sailors
GROUP BY rating
Output:
RATING MIN(AGE)
1 33
3 25.5
7 35
8 25.5
9 35
10 16 42
Question: Find the age of the youngest sailor for each rating
level, which is greater than 7
Query:
SELECT rating, MIN(age)
FROM Sailors
GROUP BY rating
HAVING rating>7
Output:
RATING MIN(AGE)
8 25.5
9 35
10 16
43
ORDER BY
The order by clause is used to sort the tuples in a query
result based on the values of some attributes
Example
Question: display the sailors table in the ascending order
of sname
Query:
SELECT *
FROM Sailors
ORDER BY sname
44
Output:
RATIN
SID SNAME AGE
G
32 Andy 8 25.5
85 Art 3 25.5
95 Bob 3 63.5
29 Brutus 1 33
22 Dustin 7 45
64 Horatio 7 35
74 Horatio 9 35
31 Lubber 8 55.5
58 Rusty 10 35 45
Question: display the sailors table in the descending order of
sname
Query:
SELECT *
FROM Sailors
ORDER BY sname DESC
46
Output:
RATIN
SID SNAME AGE
G
71 Zorba 10 16
58 Rusty 10 35
31 Lubber 8 55.5
64 Horatio 7 35
74 Horatio 9 35
22 Dustin 7 45
29 Brutus 1 33
95 Bob 3 63.5
85 Art 3 25.5 47
Null Values
Column values in a row are sometimes
unknown (e.g., a rating has not been assigned)
or
inapplicable (e.g., no spouse’s name)
SQL provides a special value null for such situations.
The result of any arithmetic expression involving null is null
Example: 5 + null returns null.
Aggregate functions simply ignore nulls.
But count(*) includes NULL values also
Example
Insert the row (98,john,null,39) to represent john into
sailors table
Query: INSERT INTO Sailors VALUES(98,‘john',null,39)
Query: SELECT *
FROM Sailors
Output:
RATIN
SID SNAME AGE
G
22 Dustin 7 45
29 Brutus 1 33
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35
64 Horatio 7 35
71 Zorba 10 16
74 Horatio 9 35
85 Art 3 25.5
95 Bob 3 63.5 50
Comparisons using NULL values and AND,OR,NOT
connectives:
Any comparison with null returns unknown
Example: 5 < null or 6 + null or null = null
Three-valued logic using the truth value unknown:
OR: (unknown or true) = true, If both arguments are
(unknown or false) = unknown False OR is false
(unknown or unknown) = unknown
AND: (true and unknown) = unknown, If both arguments are
(false and unknown) = false, True AND is true
(unknown and unknown) = unknown
NOT: (not unknown) = unknown
SQL also provides a special comparison operator
IS NULL to test whether a column value is null
IS NULL
IS NOT NULL
52
Example
Query:
SELECT *
FROM sailors
WHERE rating IS NULL
Output:
RATIN
SID SNAME AGE
G
98 Dan 39
53
Impact on SQL Constructs
The arithmetic operations +, - ,* , / and = all return null
if one of their arguments is null
Example
Query:
SELECT sid, rating, sid+rating
FROM Sailors
54
Output: SID RATING SID + RATING
22 7 29
29 1 30
31 8 39
32 8 40
58 10 68
64 7 71
71 10 81
74 9 83
85 3 88
95 3 98
98 - -
55
COUNT(*) handles null values just like other values,
that is, they get counted
Example
Query:
SELECT COUNT(*)
FROM Sailors
Output:
COUNT(*)
11
56
Disallowing Null Values
We can disallow null values by specifying NOT NULL as
part of the field definition, for example,
sname VARCHAR2(20) NOT NULL
57