Module 4.0
Module 4.0
Module 4.0
SQL
Reference: Database management systems, , Ramakrishnan, and Gehrke, 3rd Edition, 2014,
McGraw Hill
1
OUTLINE
Advances in SQL
More complex SQL retrieval queries
Specifying constraints as assertions
Triggers, Views in SQL
Schema change statements in SQL.
2
MORE COMPLEX SQL RETRIEVAL
QUERIES
Comparisons Involving NULL and Three-Valued Logic
Unknown value. A person’s date of birth is not known,
so it is represented by NULL in the database. An example
of the other case of unknown would be NULL for a person’s
home phone because it is not known whether or not the
person has a home phone.
Unavailable or withheld value. A person has a home
phone but does not want it to be listed, so it is withheld
and represented as NULL in the database.
Not applicable attribute. An attribute
LastCollegeDegree would be NULL for a person who has
no college degrees because it does not apply to that person.
3
NESTED QUERIES
A Subquery or Inner query or a Nested query is a query
within another SQL query and embedded within the
WHERE clause.
A subquery is used to return data that will be used in the
main query as a condition to further restrict the data to be
retrieved.
Subqueries can be used with the SELECT, INSERT,
UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN, etc.
A subquery can return a single value, a single row, a single
column, or a table containing one or more rows of one or
more columns.
4
SUBQUERIES
5
NESTED QUERIES (SINGLE ROW SUBQUERY EXAMPLES)
Retrieve the customers who earn salary more than the
salary of Customer with ID 6??
18
NESTED QUERY/SUB QUERY
List all customers with their total number of orders
20
GROUP BY CLAUSE
The GROUP BY Clause is utilized in SQL with the
SELECT statement to organize similar data into groups.
It combines the multiple records in single or more
columns using some functions.
21
GROUP BY CLAUSE
22
GROUP BY CLAUSE
Return the AVERAGE salary of the respective department
SELECT Avg(Salary)
FROM EMPLOYEE
GROUP BY DEPT ID ;
24
SQL HAVING CLAUSE
List the number of customers in each country.
Only include countries with more than 10 customers.
28
CORRELATED NESTED QUERIES
Whenever a condition in the WHERE clause of a nested
query references some attribute of a relation declared in
the outer query, the two queries are said to be correlated
29
CORRELATED NESTED QUERIES
Retrieve the names and Ids of employees whOse salary is
greater than the average salary of their department
30
EXISTS / NOT EXISTS
Retrieve the names of employees who have dependents.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn );
Retrieve the names of employees who do not have dependents.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE NOT EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn );
31
EXISTS / NOT EXISTS
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 );
32
RENAME
Retrieve the last name of each employee and his or her
supervisor while renaming the resulting attribute names as
Employee_name and Supervisor_name
33
AGGREGATE FUNCTIONS
Find the sum of the salaries of all employees, the maximum
salary, the minimum salary, and the average salary.
SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary)
FROM EMP
37
JOIN CONDITIONS
Oracle OUTER JOIN
Right Outer Join
The Right Outer Join returns all rows from the right-hand
table specified in the ON condition and only those rows
from the other table where the join condition is met.
SELECT SUPPLIERS.SUPPLIER_ID,
SUPPLIERS.SUPPLIER_NAME,
ORDER1.ORDER_NUMBER
FROM SUPPLIERS
RIGHT OUTER JOIN ORDER1
ON SUPPLIERS.SUPPLIER_ID =
ORDER1.SUPPLIER_ID;
38
JOIN CONDITIONS
Full Outer Join
The Full Outer Join returns all rows from the left hand
table and right hand table. It places NULL where the join
condition is not met.
39
JOIN CONDITIONS
Oracle EQUI JOIN
Retrieve the names of the managers
SELECT ENAME
FROM EMPLOYEE, DEPARTMENT
WHERE MGR_NO=SSN;
OR
SELECT E.ENAME
FROM EMPLOYEE E, DEPARTMENT D
WHERE D.MGR_NO=E.SSN;
40
JOIN CONDITIONS
SELFJOIN
A self join is a join in which a table is joined with itself (which is also called Unary relationships),
especially when the table has a FOREIGN KEY which references its own PRIMARY KEY.
42
SPECIFYING GENERAL CONSTRAINTS AS
ASSERTIONS IN SQL
In SQL, users can specify general Constraints via declarative
assertions, using the CREATE ASSERTION statement of the
DDL. Each assertion is given a constraint name and is specified
via a condition similar to the WHERE clause of an SQL query.
For example, to specify the constraint that the salary of an
employee must not be greater than the salary of the manager of
the department that the employee works for in SQL, we can write
the following assertion:
Three parts:
Event (activates the trigger)
Condition (tests whether the triggers should run) [Optional]
Action (what happens if the trigger runs)
Events could be :
44
BEFORE|AFTER INSERT|UPDATE|DELETE ON <tableName>
Eg.,
CREATE TRIGGER minSalary BEFORE INSERT ON Professor
BEGIN
END;
TRIGGERS
CREATE TRIGGER min_Salary BEFORE INSERT ON
EMPLOYEE
BEGIN
END;
TRIGGERS
R1: CREATE TRIGGER Total_sal1
AFTER INSERT ON EMPLOYEE
FOR EACH ROW R3: CREATE TRIGGER Total_sal3
BEGIN AFTER UPDATE OF Dno ON
IF ( :NEW.Dno IS NOT NULL ) EMPLOYEE
FOR EACH ROW
Then
BEGIN
UPDATE DEPARTMENT
UPDATE DEPARTMENT
SET Total_sal = Total_sal + :NEW.Salary SET Total_sal = Total_sal + :NEW.Salary
WHERE Dno = :NEW.Dno; WHERE Dno = :NEW.Dno;
End if; end; UPDATE DEPARTMENT
SET Total_sal = Total_sal – :OLD.Salary
R2: CREATE TRIGGER Total_sal2 WHERE Dno = :OLD.Dno;
AFTER UPDATE OF Salary ON EMPLOYEE
END;
FOR EACH ROW
R4: CREATE TRIGGER Total_sal4
Begin AFTER DELETE ON EMPLOYEE
if ( :NEW.Dno IS NOT NULL ) FOR EACH ROW
UPDATE DEPARTMENT BEGIN
SET Total_sal = Total_sal + :NEW.Salary IF ( :OLD.Dno IS NOT NULL)
– :OLD.Salary UPDATE DEPARTMENT 47
WHERE Dno = :NEW.Dno; SET Total_sal = Total_sal – :OLD.Salary
End if; end; WHERE Dno = :OLD.Dno; end if; end;
VIEW
You can present logical subsets or combinations of data by creating views of
tables. A view is a logical table based on a table or another view. A view
contains no data of its own but is like a window through which data from
tables can be viewed or changed. The tables on which a view is based are
called base tables. The view is stored as a SELECT statement in the data
dictionary.
48
CREATING A VIEW
Create a view, EMPVU80, that contains details of
employees in department 80.
50
USES OF A VIEW :
A good database should contain views due to the given reasons:
Rename Columns –
Views can also be used to rename the columns without affecting the base tables
provided the number of columns in view must match the number of columns
specified in select statement. Thus, renaming helps to hide the names of the
columns of the base tables. 51
UPDATE EMPLOYEE
SET Salary =
CASE WHEN Dno = 5 THEN Salary + 2000
WHEN Dno = 4 THEN Salary + 1500
WHEN Dno = 1 THEN Salary + 3000
ELSE Salary + 0 ;
52
SCHEMA CHANGE STATEMENTS IN
SQL
ALTER COMMAND
DROP A CONSTRAINT
ADD A CONSTRAINT
ADD A COLUMN
DROP A COLUMN
53
STORED PROCEDURE
54
STORED PROCEDURES AND
FUNCTIONS
In our presentation of database programming techniques so far, there was an implicit
assumption that the database application program was running on a client
it is sometimes useful to create database program modules—procedures or functions
—that are stored and executed by the DBMS at the database server
The parameters and local declarations are optional, and are specified only if needed.
55
STORED PROCEDURES AND
FUNCTIONS
For declaring a function, a return type is necessary, so the declaration form is:
56
SIMPLE EXAMPLE :STORED PROCEDURE AND FUNCTION
CREATE OR REPLACE PROCEDURE PrintHello AS
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello, Oracle SQL!');
END;
/
-- Execute the stored procedure
EXEC PrintHello;;
57
-- Use the function in a SELECT statement
SELECT AddNumbers(5, 7) AS SumResult FROM DUAL;
;
GOOD EXAMPLE :STORED PROCEDURE
CREATE OR REPLACE PROCEDURE GetEmployeeInfo (p_employee_id IN NUMBER)
AS
v_employee_name employees.employee_name%TYPE;
v_job employees.job%TYPE;
v_salary employees.salary%TYPE;
BEGIN
-- Retrieve employee information based on the provided ID
SELECT employee_name, job, salary
INTO v_employee_name, v_job, v_salary
FROM employees
WHERE employee_id = p_employee_id;
In Oracle PL/SQL, cursors are used to process the result set of a query. There are two
types of cursors: implicit cursors and explicit cursors.
Implicit
Explicit
60
IMPLICIT CURSORS
Example
DECLARE
v_employee_name employees.employee_name%TYPE;
BEGIN
SELECT employee_name INTO v_employee_name FROM employees WHERE
employee_id = 101;
DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_employee_name);
END;
/
61
EXPLICIT CURSORS
Explicit cursors are declared explicitly by the programmer.
Explicit cursors are used in scenarios where you need more control over the cursor
operations, such as processing multiple rows, handling exceptions, or performing
complex data manipulations.
62
EXPLICIT CURSORS: EXAMPLE
DECLARE
E_ID EMPLOYEE.EMP_ID%type;
E_name EMPLOYEE.EMP_NAME%type;
E_SALARY EMPLOYEE.SALARY%type;
CURSOR EMPLOYEE_DETAILS is
SELECT EMP_ID, EMP_NAME, SALARY FROM EMPLOYEE;
BEGIN
OPEN EMPLOYEE_DETAILS;
LOOP
FETCH EMPLOYEE_DETAILS into E_ID, E_NAME, E_SALARY;
EXIT WHEN EMPLOYEE_DETAILS%notfound;
dbms_output.put_line(E_ID || ' ' || E_NAME|| ' ' ||E_SALARY);
END LOOP;
CLOSE EMPLOYEE_DETAILS;
END; 63
SUMMARY
Advances in SQL
More complex SQL retrieval queries
Specifying constraints as assertions
Triggers, Views in SQL
Stored Procedures, functions, and cursor in SQL
Schema change statements in SQL.
64