Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views48 pages

Unit-2 Chapter-3 More SQL Updated

The document covers advanced SQL concepts including complex queries, assertions, triggers, and views, along with detailed explanations of various types of joins such as inner, outer, and cross joins. It provides examples of SQL queries demonstrating nested queries, aggregate functions, and the use of CASE statements for conditional logic. Additionally, it discusses the significance of NULL values in SQL and the enforcement of integrity constraints through assertions.

Uploaded by

SANDEEP PANDU
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views48 pages

Unit-2 Chapter-3 More SQL Updated

The document covers advanced SQL concepts including complex queries, assertions, triggers, and views, along with detailed explanations of various types of joins such as inner, outer, and cross joins. It provides examples of SQL queries demonstrating nested queries, aggregate functions, and the use of CASE statements for conditional logic. Additionally, it discusses the significance of NULL values in SQL and the enforcement of integrity constraints through assertions.

Uploaded by

SANDEEP PANDU
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

More SQL:

1) Complex Queries (Nested queries, joined tables, and outer joins (in the FROM clause),
aggregate functions, and grouping)

2) Assertions (Specifying Constraints)

3) Triggers (Actions)

4) Views (Virtual Tables)


COMPANY relational database schema
COMPANY relational database schema – continued
Comparisons Involving NULL

 Meanings of NULL
 Unknown value
 Unavailable or withheld value
 Not applicable attribute
 Each individual NULL value considered to be different from
every other NULL value
 NULL = NULL comparison is avoided
 SQL allows queries that check whether an attribute value is NULL
 IS or IS NOT NULL
 Nested queries
 Complete select-from-where blocks within WHERE clause of another
query
Nested queries, contd

Query1) List Essns of all employees who work the same (project,
hours) combination on some project that employee ‘John Smith’
(whose Ssn = ‘123456789’) works on.
Query2) List the names of employees whose salary is greater
than the salary of all the employees in department 5

ALL: value must exceed all values from nested


query
• Avoid potential errors and ambiguities
• Create tuple variables (aliases) for all tables referenced in SQL query

Query3) Retrieve the name of each employee who has a dependent


with the same first name and is the same Gender as the employee.

SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E
WHERE E.Ssn IN ( SELECT D.Essn
FROM DEPENDENT AS D
WHERE E.Fname = D.Dependent_name AND
E.Gender = D. Gender );
Correlated Nested Queries
 Queries that are nested using the = or IN comparison operator can
be collapsed into one single block:
 E.g., Query3 can be written as:
Query3 ) Retrieve the name of each employee who has a dependent
with the same first name and is the same Gender as the employee.

SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E, DEPENDENT AS D
WHERE E.Ssn = D.Essn AND
E.Gender = D.Gender AND
E.Fname = D.Dependent_name;
The EXISTS and UNIQUE Functions in SQL for correlating queries

 EXISTS and UNIQUE are Boolean functions that return TRUE or FALSE;
 hence, they can be used in a WHERE clause condition
 EXISTS
 Check whether the result of a correlated nested query is empty or not.
 The result of EXISTS is a Boolean value TRUE if the nested query result
contains at least one tuple, or FALSE if the nested query result contains no
tuples.
 UNIQUE
 Returns TRUE if there are no duplicate tuples in the result of query Q
• Query3 ) Retrieve the name of each employee who has a dependent with the
same first name and is the same Gender as the employee.

SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E
WHERE EXISTS ( SELECT *
FROM DEPENDENT AS D
WHERE E.Ssn = D.Essn AND
E.Gender = D.Gender AND
E.Fname = D.Dependent_name);
Query 4) List the names of managers who have at least one
dependent.

SELECT Fname, Lname


FROM Employee
WHERE EXISTS (SELECT *
FROM DEPENDENT
WHERE Ssn= Essn)

AND EXISTS (SELECT *


FROM Department
WHERE Ssn= Mgr_Ssn)
• NOT EXISTS returns TRUE if there are no tuples in the result of nested
query Q, and returns FALSE otherwise.

Query 5) Retrieve the names of employees who have no dependents.

SELECT Fname, Lname


FROM EMPLOYEE
WHERE NOT EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn );
Query 6) Retrieve the Social Security numbers of all employees who
work on project numbers 1, 2, or 3.

SELECT DISTINCT Essn


FROM WORKS_ON
WHERE Pno IN (1, 2, 3);
JOINS
• JOINS are used to retrieve data from multiple tables.
• A JOIN is performed whenever two or more tables are listed in a SQL
statement.
• JOIN typically combines rows with equal values for the specified columns.
• Usually, one table contains a primary key, which is a column or columns that
uniquely identify rows in the table.
• The other table has a column or columns that refer to the primary key columns
in the first table.
• Such columns are foreign keys.
• The JOIN condition is the equality between the primary key columns in one
table and columns referring to them in the other table.
Syntax of JOIN Example
SELECT columns SELECT *
FROM table1 JOIN table2 from class JOIN class_info
ON table1.column = table2.column; ON class.id = class_info.id;

ID NAME ID Address
Class Class_info
ID NAME ID Address 1 abhi 1 DELHI
1 abhi 1 DELHI 2 adam 2 MUMBAI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
3 alex 3 CHENNAI
4 anu 7 NOIDA
5 ashish 8 PANIPAT
JOIN CONDITIONS
• The JOIN condition doesn't have to be an equality – it can be any condition
you want.
• JOIN doesn't interpret the JOIN condition, it only checks if the rows satisfy the
given condition.
• To refer to a column in the JOIN query, you have to use the full column name:
first the table name, then a dot (.) and the column name:
ON class.id = class_info.id
• You can omit the table name and use just the column name if the name of the
column is unique within all columns in the joined tables.
Types of Join

• Inner Join or Join


 Default type of join in a joined table
 Tuple is included in the result only if a matching tuple exists in the
other relation
• Natural Join
• Outer Join - Left Outer Join
– Right Outer Join
– Full Outer Join

• Cross Join
Natural Join
• If the tables have columns with the same name, you can use NATURAL JOIN
instead of JOIN.
• The common column appears only once in the result table.
Example: SELECT *
from class NATURAL JOIN class_info;
Class_info
Output: ID
Class
NAME ID Address
ID NAME Address
1 abhi 1 DELHI
1 abhi DELHI
2 adam 2 MUMBAI
2 adam MUMBAI 3 alex 3 CHENNAI
3 alex CHENNAI 4 anu 7 NOIDA
5 ashish 8 PANIPAT
OUTER JOIN
• Outer Join is based on both matched and unmatched data.
• Outer Joins subdivide further into,
 LEFT OUTER JOIN
 Every tuple in left table must appear in result

 If no matching tuple


Padded with NULL values for attributes of right table
 RIGHT OUTER JOIN
 Every tuple in right table must appear in result

 If no matching tuple


Padded with NULL values for attributes of left table

FULL OUTER JOIN – combines result if LEFT and RIGHT OUTER JOIN
Left Outer Join
• LEFT JOIN returns all rows from the left table with matching rows from the right
table. Rows without a match are filled with NULLs.
Example:
SELECT *
Class Class_info
FROM class LEFT OUTER JOIN class_info ID NAME ID Address

ON class.id = class_info.id; 1 abhi 1 DELHI


2 adam 2 MUMBAI
ID NAME ID Address 3 alex 3 CHENNAI
1 abhi 1 DELHI 4 anu 7 NOIDA
2 adam 2 MUMBAI 5 ashish 8 PANIPAT
3 alex 3 CHENNAI
4 anu NULL NULL
5 ashish NULL NULL
Right Outer Join
• RIGHT JOIN returns all rows from the right table with matching rows from the
left table. Rows without a match are filled with NULLs.
Example: SELECT *
FROM class RIGHT OUTER JOIN class_info
ON class.id = class_info.id;
Class Class_info
ID NAME ID Address ID NAME ID Address
1 abhi 1 DELHI 1 abhi 1 DELHI
2 adam 2 MUMBAI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
3 alex 3 CHENNAI
4 anu 7 NOIDA
NULL NULL 7 NOIDA 5 ashish 8 PANIPAT

NULL NULL 8 PANIPAT


FULL Outer Join
• FULL JOIN returns all rows from the left table and all rows from the right table.
It fills the non-matching rows with NULLs.
Example: SELECT *
FROM class FULL OUTER JOIN class_info
ON class.id = class_info.id; Class_info
Class
ID NAME ID Address ID NAME ID Address
1 abhi 1 DELHI 1 abhi 1 DELHI
2 adam 2 MUMBAI 2 adam 2 MUMBAI
3 alex 3 CHENNAI 3 alex 3 CHENNAI
4 anu NULL NULL 4 anu 7 NOIDA
5 ashish NULL NULL 5 ashish 8 PANIPAT
NULL NULL 7 NOIDA
NULL NULL 8 PANIPAT
CROSS Join
• CROSS JOIN returns all possible combinations of rows from the left and right
tables
Example: SELECT *
FROM class CROSS JOIN class_info;
ID NAME ID Address
1 abhi 1 DELHI
1 abhi 2 MUMBAI
1 abhi 3 CHENNAI
2 adam 1 DELHI
2 adam 2 MUMBAI
2 adam 3 CHENNAI
3 alex 1 DELHI
3 alex 2 MUMBAI
3 alex 3 CHENNAI
4 anu 1 DELHI
4 anu 2 MUMBAI
4 anu 3 CHENNAI
Summary of JOINS
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left
or right table
CROSS JOIN: Returns all possible combinations of rows from the left and
right tables
Examples on Joins
Query 1) SELECT Fname, Lname, Address
FROM (EMPLOYEE JOIN DEPARTMENT ON Dno = Dnumber)
WHERE Dname = ‘Research’;

Query 2) SELECT Fname, Lname, Address


FROM (EMPLOYEE NATURAL JOIN (DEPARTMENT AS DEPT (Dname,
Dno, Mssn, Msdate)))
WHERE Dname = ‘Research’;
Examples on Joins
Query 3)
SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name
FROM (EMPLOYEE AS E LEFT OUTER JOIN EMPLOYEE AS S ON E.Super_ssn =
S.Ssn);

Multi Join
Query 4) SELECT Pnumber, Dnum, Lname, Address, Bdate
FROM ((PROJECT JOIN DEPARTMENT ON Dnum = Dnumber) JOIN EMPLOYEE
ON Mgr_ssn = Ssn)
WHERE Plocation = ‘Stafford’;
Query) Find the sum of the salaries of all employees, the maximum
salary, the minimum salary, and the average salary.
SQL> SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary)
FROM EMPLOYEE;

*use AS to rename the column names in the resulting single-row table


SQL> SELECT SUM (Salary) AS Total_Sal, MAX (Salary) AS Highest_Sal,
MIN (Salary) AS Lowest_Sal, AVG (Salary) AS Average_Sal
FROM EMPLOYEE;
Query) Find the sum of the salaries of all employees of the ‘Research’ department, as well as
the maximum salary, the minimum salary, and the average salary in this department.
SQL> SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary)
FROM (EMPLOYEE JOIN DEPARTMENT ON Dno = Dnumber)
WHERE Dname = ‘Research’;

Query) Retrieve the total number of employees in the company


SQL> SELECT COUNT (*)
FROM EMPLOYEE;

Query) Retrieve the number of employees in the ‘Research’ department


SQL> SELECT COUNT (*)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO = DNUMBER AND DNAME = ‘Research’;
Query) For each department, retrieve the department number, the
number of employees in the department, and their average salary.
SQL> SELECT Dno, COUNT (*), AVG (Salary)
FROM EMPLOYEE
GROUP BY Dno;

Query) For each project, retrieve the project number, the project name, and the
number of employees who work on that project.
SQL> SELECT Pnumber, Pname, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno
GROUP BY Pnumber, Pname;
Query) For each project on which more than two employees work, retrieve the project
number, the project name, and the number of employees who work on the project.
SQL> SELECT Pnumber, Pname, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno
GROUP BY Pnumber, Pname
HAVING COUNT (*) > 2;

Query) For each project, retrieve the project number, the project name, and the number of
employees from department 5 who work on the project.
SQL> SELECT Pnumber, Pname, COUNT (*)
FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE Pnumber = Pno AND Ssn = Essn AND Dno = 5
GROUP BY Pnumber, Pname;
Query) Count the total number of employees whose salaries exceed $40,000 in
each department, but only for departments where more than five employees
work.
SQL> SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000
GROUP BY Dno
HAVING COUNT (*) > 5;
Use of CASE

• Used when a value can be different based on certain conditions.


• Can be used in any part of an SQL query where a value is expected
• Applicable when querying, inserting or updating tuples.
Query) Suppose we want to give employees different raise amounts depending on
which department they work for; for example, employees in department 5 get a
$2,000 raise, those in department 4 get $1,500 and those in department 1 get
$3,000

SQL> UPDATE EMPLOYEE


SET Salary =
CASE WHEN Dno = 5 THEN Salary + 2000
WHEN Dno = 4 THEN Salary + 1500
WHEN Dno = 1 THEN Salary + 3000 ;
Assertions
• Assertions are used to specify integrity constraints which can not be specified
using constraints like Primary key, NOT NLL,UNIQUE,CHECK and DEFAULT etc.
• Assertions is an expression or constraint that should be always TRUE.
• DBMS enforces the assertion on the database and the constraints specified in
the assertion must not be violated.
• DBMS always checks the assertion whenever modifications are done in
corresponding table.
• DBMS Tests the assertion for its validity when it is created.
Syntax of Assertion
CREATE ASSERTION [ assertion_name ]
CHECK ( [ condition ] );

Query) The salary of an employee must not be greater than


the salary of the manager of the department that the employee works for.
SQL> CREATE ASSERTION SALARY_CONSTRAINT
CHECK ( NOT EXISTS ( SELECT *
FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D
WHERE E.Salary > M.Salary AND E.Dno = D.Dnumber
AND D.Mgr_ssn = M.Ssn ) );

NOT EXISTS: Indicates that result of this query must be empty.


Assertion is violated whenever the result of query inside NOT EXISTS clause is not empty.
Triggers
• Triggers are the SQL statements/stored programs that are automatically
executed when there is any change in the database.
• The triggers are executed in response to certain events(INSERT, UPDATE or
DELETE) in a particular table.
• These triggers help in maintaining the integrity of the data by changing the
data of the database in a systematic fashion.
• Triggers can be defined on the table, view, schema, or database with which the
event is associated.
• Database Trigger has 3 parts: 1) Trigger Event
2) Condition
3) Trigger Action
Types of Triggers:

1. DML Trigger – INSERT, DELETE, UPDATE


2. DDL Trigger – ALTER, DROP, TRUNCATE, GRANT, REVOKE, RENAME
3. System Trigger –LOGON, LOGOFF, START UP, SHUTDOWN
4. Instead of Trigger – Trigger on views
5. Compound Trigger – combines DML trigger in single block
Purpose of triggers?
• Auditing
• Enforcing complex referential integrity
• Logging
• Enforcing security transactions
• Prevent invalid data
• Data replicating to multiple tables
Syntax of Trigger:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
<Trigger action >;
Explanation of Trigger Syntax:
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − specifies when the trigger will be executed. The
INSTEAD OF clause is used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE} − specifies the DML operation.
• [OF col_name] − specifies the column name that will be updated.
• [ON table_name] − specifies the name of the table associated with the trigger.
• [REFERENCING OLD AS o NEW AS n] − allows you to refer new and old values for
various DML statements, such as INSERT, UPDATE, and DELETE.
• [FOR EACH ROW] − specifies a row-level trigger, i.e., the trigger will be executed for
each row being affected. Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
• WHEN (condition) − provides a condition for rows for which the trigger would fire.
This clause is valid only for row-level triggers.
Query) Suppose we want to check whenever an employee’s salary is greater than the salary
of his or her direct supervisor in the COMPANY database.
Note: Several events can trigger this rule: inserting a new employee record, changing an
employee’s salary, or changing an employee’s supervisor.

SQL> CREATE TRIGGER SALARY_VIOLATION


BEFORE INSERT OR UPDATE OF SALARY, SUPERVISOR_SSN
ON EMPLOYEE
FOR EACH ROW
WHEN ( NEW.SALARY > ( SELECT SALARY
FROM EMPLOYEE
WHERE SSN = NEW.SUPERVISOR_SSN ) )
INFORM_SUPERVISOR(NEW.Supervisor_ssn, NEW.Ssn );
Example 2): Student(Student_id, Name, Address,Marks)

create a trigger that will add 100 marks to each new row of the Marks column
whenever a new student is inserted to the table.
CREATE TRIGGER Add_marks
BEFORE INSERT
ON Student
FOR EACH ROW
SET new.Marks = new.Marks + 100;
• After creating the trigger, write the query for inserting a new student in the
database.
INSERT INTO Student(Student_id, Name, Address, Marks) VALUES (4, ‘Ram',
'Maldives', 110);
Sql> SELECT * FROM Student;
Views (Virtual Tables) in SQL
• Views in SQL are kind of virtual tables.
• A view also has rows and columns as they are in a real table in the database.
• We can create a view by selecting fields from one or more tables present in
the database.
• A View can either have all the rows of a table or specific rows based on certain
condition.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
Customers Table
Id Name Age Address Salary
1 Sachin 32 Mumbai 5000
2 Khilan 25 Delhi 1000
3 Chaitali 23 Bhopal 2000
4 Hardik 27 Indore 3000
5 Komal 22 Kolkata 4000
6 Muffy 24 Delhi 2500
7 Akbar 21 Indore 3500

Query) Create a view which contain name and age of all customers.
SQL > CREATE VIEW CUSTOMERS_VIEW AS Name Age
Sachin 32
SELECT name, age Khilan 25
Chaitali 23
FROM CUSTOMERS; Hardik 27
SQL> SELECT * FROM CUSTOMERS_VIEW; Komal 22
Muffy 24
Akbar 21
Query) Create a view which contain name and age of customers
whose age > 23
SQL > CREATE VIEW CUSTOMERS_AGE AS Name Age
Sachin 32
SELECT name, age
Khilan 25
FROM CUSTOMERS Hardik 27
WHERE age > 23; Muffy 24

SQL> SELECT * FROM CUSTOMERS_AGE;

You might also like