Slides by: Ms. Shree Jaswal
Overview of SQL, Data Definition Commands, Set operations, aggregate function, null values, Data Manipulation commands, Data Control commands, Views in SQL, Complex Retrieval Queries using Group By, Recursive Queries, nested Queries ; Referential integrity in SQL. Event Condition Action (ECA) model (Triggers) in SQL; Database Programming with JDBC, Security and authorization in SQL Functions and Procedures in SQL and cursors. Module 4 Slides by: Shree Jaswal 2
Chapter 4: SQL: Data definition, constraints, and basic queries and updates, Elmasri and Navathe, Fundamentals of Database Systems, 6th Edition, PEARSON Education Chapter 5: SQL: Advanced queries, assertions, triggers and views, Elmasri and Navathe, Fundamentals of Database Systems, 6th Edition, PEARSON Education Chapter 3: Introduction to SQL, Raghu Ramkrishnan and Johannes Gehrke, Database Management Systems,TMH Chapter 4: Intermediate SQL, Raghu Ramkrishnan and Johannes Gehrke, Database Management Systems,TMH Chapter 5: Advanced SQL, Raghu Ramkrishnan and Johannes Gehrke, Database Management Systems,TMH Module 4 Slides by: Shree Jaswal 3
SQL language Considered one of the major reasons for the commercial success of relational databases SQL Structured Query Language Statements for data definitions, queries, and updates (both DDL and DML) Core specification Plus specialized extensions Module 4 Slides by: Shree Jaswal 4
Terminology: Table, row, and column used for relational model terms relation, tuple, and attribute CREATE statement Main SQL command for data definition Module 4 Slides by: Shree Jaswal 5
SQL schema Identified by a schema name Includes an authorization identifier and descriptors for each element Schema elements include Tables, constraints, views, domains, and other constructs Each statement in SQL ends with a semicolon Module 4 Slides by: Shree Jaswal 6
CREATE SCHEMA statement CREATE SCHEMA COMPANY AUTHORIZATION Jsmith ; Catalog Named collection of schemas in an SQL environment SQL environment Installation of an SQL-compliant RDBMS on a computer system Module 4 Slides by: Shree Jaswal 7
Specify a new relation Provide name Specify attributes and initial constraints Can optionally specify schema: CREATE TABLE COMPANY.EMPLOYEE... or CREATE TABLE EMPLOYEE... Module 4 Slides by: Shree Jaswal 8
Base tables (base relations) Relation and its tuples are actually created and stored as a file by the DBMS Virtual relations Created through the CREATE VIEW statement Module 4 Slides by: Shree Jaswal 9
Module 4 Slides by: Shree Jaswal 10
Module 4 Slides by: Shree Jaswal 11
Some foreign keys may cause errors Specified either via: Circular references Or because they refer to a table that has not yet been created Module 4 Slides by: Shree Jaswal 12
Basic data types Numeric data types Integer numbers: INTEGER, INT, and SMALLINT Floating-point (real) numbers: FLOAT or REAL, and DOUBLE PRECISION Character-string data types Fixed length: CHAR(n), CHARACTER(n) Varying length: VARCHAR(n), CHAR VARYING(n), CHARACTER VARYING(n) Module 4 Slides by: Shree Jaswal 13
Bit-string data types Fixed length: BIT(n) Varying length: BIT VARYING(n) Boolean data type Values of TRUE or FALSE or NULL DATE data type Ten positions Components are YEAR, MONTH, and DAY in the form YYYY-MM-DD Module 4 Slides by: Shree Jaswal 14
Additional data types Timestamp data type (TIMESTAMP) Includes the DATE and TIME fields Plus a minimum of six positions for decimal fractions of seconds Optional WITH TIME ZONE qualifier INTERVAL data type Specifies a relative value that can be used to increment or decrement an absolute value of a date, time, or timestamp Module 4 Slides by: Shree Jaswal 15
Basic constraints: Key and referential integrity constraints Restrictions on attribute domains and NULLs Constraints on individual tuples within a relation Module 4 Slides by: Shree Jaswal 16
NOT NULL NULL is not permitted for a particular attribute Default value DEFAULT <value> CHECK clause Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21); Module 4 Slides by: Shree Jaswal 17
Module 4 Slides by: Shree Jaswal 18
PRIMARY KEY clause Specifies one or more attributes that make up the primary key of a relation Dnumber INT PRIMARY KEY; UNIQUE clause Specifies alternate (secondary) keys Dname VARCHAR(15) UNIQUE; Module 4 Slides by: Shree Jaswal 19
FOREIGN KEY clause Default operation: reject update on violation Attach referential triggered action clause Options include SET NULL, CASCADE, and SET DEFAULT Action taken by the DBMS for SET NULL or SET DEFAULT is the same for both ON DELETE and ON UPDATE CASCADE option suitable for relationship relations Module 4 Slides by: Shree Jaswal 20
CHECK clauses at the end of a CREATE TABLE statement Apply to each tuple individually CHECK (Dept_create_date <= Mgr_start_date); Module 4 Slides by: Shree Jaswal 22
SELECT statement One basic statement for retrieving information from a database SQL allows a table to have two or more tuples that are identical in all their attribute values Unlike relational model Multiset or bag behavior Module 4 Slides by: Shree Jaswal 23
Basic form of the SELECT statement: Module 4 Slides by: Shree Jaswal 24
Logical comparison operators =, <, <=, >, >=, and <> Projection attributes Attributes whose values are to be retrieved Selection condition Boolean condition that must be true for any retrieved tuple Module 4 Slides by: Shree Jaswal 25
Module 4 Slides by: Shree Jaswal 26
Module 4 Slides by: Shree Jaswal 27
Module 4 Slides by: Shree Jaswal 28
Module 4 Slides by: Shree Jaswal 29
Module 4 Slides by: Shree Jaswal 30
Module 4 Slides by: Shree Jaswal 31
Module 4 Slides by: Shree Jaswal 32
Module 4 Slides by: Shree Jaswal 33
Same name can be used for two (or more) attributes As long as the attributes are in different relations Must qualify the attribute name with the relation name to prevent ambiguity Module 4 Slides by: Shree Jaswal 34
Aliases or tuple variables Declare alternative relation names E and S EMPLOYEE AS E(Fn, Mi, Ln, Ssn, Bd, Addr, Sex, Sal, Sssn, Dno) Module 4 Slides by: Shree Jaswal 35
Module 4 Slides by: Shree Jaswal 36
Missing WHERE clause Indicates no condition on tuple selection CROSS PRODUCT All possible tuple combinations Module 4 Slides by: Shree Jaswal 37
Specify an asterisk (*) Retrieve all the attribute values of the selected tuples Module 4 Slides by: Shree Jaswal 38
SQL does not automatically eliminate duplicate tuples in query results Use the keyword DISTINCT in the SELECT clause Only distinct tuples should remain in the result Module 4 Slides by: Shree Jaswal 39
Set operations UNION, EXCEPT (difference), INTERSECT Corresponding multiset operations: UNION ALL, EXCEPT ALL, INTERSECT ALL) Module 4 Slides by: Shree Jaswal 40
LIKE comparison operator Used for string pattern matching % replaces an arbitrary number of zero or more characters underscore (_) replaces a single character Standard arithmetic operators: Addition (+), subtraction ( ), multiplication (*), and division (/) BETWEEN comparison operator Module 4 Slides by: Shree Jaswal 41
Module 4 Slides by: Shree Jaswal 42
Module 4 Slides by: Shree Jaswal 43
Use ORDER BY clause Keyword DESC to see result in a descending order of values Default order is in ascending order of values Keyword ASC to specify ascending order explicitly ORDER BY D.Dname DESC, E.Lname ASC, E.Fname ASC Module 4 Slides by: Shree Jaswal 44
Module 4 Slides by: Shree Jaswal 45
Module 4 Slides by: Shree Jaswal 46
Three commands used to modify the database: INSERT, DELETE, and UPDATE Module 4 Slides by: Shree Jaswal 47
Specify the relation name and a list of values for the tuple Module 4 Slides by: Shree Jaswal 48
Removes tuples from a relation Includes a WHERE clause to select the tuples to be deleted Module 4 Slides by: Shree Jaswal 49
Modify attribute values of one or more selected tuples Additional SET clause in the UPDATE command Specifies attributes to be modified and new values Module 4 Slides by: Shree Jaswal 50
Techniques for specifying complex retrieval queries Writing programs in various programming languages that include SQL statements Set of commands for specifying physical database design parameters, file structures for relations, and access paths Transaction control commands Module 4 Slides by: Shree Jaswal 51
Specifying the granting and revoking of privileges to users Constructs for creating triggers Enhanced relational systems known as objectrelational New technologies such as XML and OLAP Module 4 Slides by: Shree Jaswal 52
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 SQL uses a three-valued logic: TRUE, FALSE, and UNKNOWN Module 4 Slides by: Shree Jaswal 53
Module 4 Slides by: Shree Jaswal 54
SQL allows queries that check whether an attribute value is NULL IS or IS NOT NULL Module 4 Slides by: Shree Jaswal 55
Nested queries Complete select-from-where blocks within WHERE clause of another query Outer query Comparison operator IN Compares value v with a set (or multiset) of values V Evaluates to TRUE if v is one of the elements in V Module 4 Slides by: Shree Jaswal 56
Module 4 Slides by: Shree Jaswal 57
Module 4 Slides by: Shree Jaswal 58
Use tuples of values in comparisons Place them within parentheses This query will select the Essns of all employees who work the same (project, hours) combination on some project that employee John Smith (whose Ssn = 123456789 ) works on. Module 4 Slides by: Shree Jaswal 59
Use other comparison operators to compare a single value v = ANY (or = SOME) operator Returns TRUE if the value v is equal to some value in the set V and is hence equivalent to IN Other operators that can be combined with ANY (or SOME): >, >=, <, <=, and <> An example is the following query, which returns the names of employees whose salary is greater than the salary of all the employees in department 5: Module 4 Slides by: Shree Jaswal 60
Avoid potential errors and ambiguities Create tuple variables (aliases) for all tables referenced in SQL query Module 4 Slides by: Shree Jaswal 61
A query written with nested select-from-where blocks and using the = or IN comparison operators can always be expressed as a single block query. For example, Q16 may be written as in Q16A: Q16A: SELECT E.Fname, E.Lname FROM EMPLOYEE AS E, DEPENDENT AS D WHERE E.Ssn=D.Essn AND E.Sex=D.Sex AND E.Fname=D.Dependent_name; Module 4 Slides by: Shree Jaswal 62
Correlated nested query Evaluated once for each tuple in the outer query Q16A: SELECT E.Fname, E.Lname FROM EMPLOYEE AS E, DEPENDENT AS D WHERE E.Ssn=D.Essn AND E.Sex=D.Sex AND E.Fname=D.Dependent_name; Module 4 Slides by: Shree Jaswal 63
EXISTS function Check whether the result of a correlated nested query is empty or not In general, EXISTS(Q) returns TRUE if there is at least one tuple in the result of the nested query Q, and it returns FALSE otherwise. NOT EXISTS Typically used in conjunction with a correlated nested query returns TRUE if there are no tuples in the result of nested query Q, and it returns FALSE otherwise. SQL function UNIQUE(Q) Returns TRUE if there are no duplicate tuples in the result of query Q Module 4 Slides by: Shree Jaswal 64
Q16B: SELECT E.Fname, E.Lname FROM EMPLOYEE AS E WHERE EXISTS ( SELECT * FROM DEPENDENT AS D WHERE E.Ssn=D.Essn AND E.Sex=D.Sex AND E.Fname=D.Dependent_name); Module 4 Slides by: Shree Jaswal 65
Query 6. Retrieve the names of employees who have no dependents. Q6: SELECT Fname, Lname FROM EMPLOYEE WHERE NOT EXISTS ( SELECT * FROM DEPENDENT WHERE Ssn=Essn); Module 4 Slides by: Shree Jaswal 66
Can use explicit set of values in WHERE clause Use qualifier AS followed by desired new name Rename any attribute that appears in the result of a query Query 17. Retrieve the Social Security numbers of all employees who work on project numbers 1, 2, or 3. Q17: SELECT DISTINCT Essn FROM WORKS_ON WHERE Pno IN (1, 2, 3); For each employee, retrieve the employee s first and last name and the first and last name of his or her immediate supervisor. Module 4 Slides by: Shree Jaswal 67
Joined table Permits users to specify a table resulting from a join operation in the FROM clause of a query The FROM clause in Q1A Contains a single joined table Query 1. Retrieve the name and address of all employees who work for the Research department. Module 4 Slides by: Shree Jaswal 68
Specify different types of join NATURAL JOIN Various types of OUTER JOIN NATURAL JOIN on two relations R and S No join condition specified Implicit EQUIJOIN condition for each pair of attributes with same name from R and S Q1B: SELECT Fname, Lname, Address FROM (EMPLOYEE NATURAL JOIN (DEPARTMENT AS DEPT (Dname, Dno, Mssn, Msdate))) WHERE Dname= Research ; Module 4 Slides by: Shree Jaswal 69
Inner 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 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 Q8B: 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); All employees who have a supervisor are included in the result along with those who do have supervisor value as NULL Module 4 Slides by: Shree Jaswal 70
RIGHT OUTER JOIN Every tuple in right table must appear in result If no matching tuple Padded with NULL values for the attributes of left table FULL OUTER JOIN Can nest join specifications Q2A: For every project located in Stafford, list the project number, the controlling department number, and the department manager s last name, address, and birth date. Q2A: SELECT Pnumber, Dnum, Lname, Address, Bdate FROM ((PROJECT JOIN DEPARTMENT ON Dnum=Dnumber) JOIN EMPLOYEE ON Mgr_ssn=Ssn) WHERE Plocation= Stafford ; Module 4 Slides by: Shree Jaswal 71
Used to summarize information from multiple tuples into a single-tuple summary Grouping Create subgroups of tuples before summarizing Built-in aggregate functions COUNT, SUM, MAX, MIN, and AVG Functions can be used in the SELECT clause or in a HAVING clause Query 19. Find the sum of the salaries of all employees, the maximum salary, the minimum salary, and the average salary. Q19: SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary) FROM EMPLOYEE; Module 4 Slides by: Shree Jaswal 72
NULL values discarded when aggregate functions are applied to a particular column Module 4 Slides by: Shree Jaswal 73
Query 23. Count the number of distinct salary values in the database. Q23: SELECT COUNT (DISTINCT Salary) FROM EMPLOYEE; Module 4 Slides by: Shree Jaswal 74
Partition relation into subsets of tuples Based on grouping attribute(s) Apply function to each such group independently GROUP BY clause Specifies grouping attributes If NULLs exist in grouping attribute Separate group created for all tuples with a NULL value in grouping attribute Module 4 Slides by: Shree Jaswal 75
Query 24. For each department, retrieve the department number, the number of employees in the department, and their average salary. Q24: SELECT Dno, COUNT (*), AVG (Salary) FROM EMPLOYEE GROUP BY Dno; Query 25. For each project, retrieve the project number, the project name, and the number of employees who work on that project. Q25: SELECT Pnumber, Pname, COUNT (*) FROM PROJECT, WORKS_ON WHERE Pnumber=Pno GROUP BY Pnumber, Pname; Module 4 Slides by: Shree Jaswal 76
HAVING clause Provides a condition on the summary information Module 4 Slides by: Shree Jaswal 77
Module 4 Slides by: Shree Jaswal 78
CREATE ASSERTION Specify additional types of constraints outside scope of built-in relational model constraints CREATE TRIGGER Specify automatic actions that database system will perform when certain events and conditions occur Module 4 Slides by: Shree Jaswal 79
CREATE ASSERTION Specify a query that selects any tuples that violate the desired condition Use only in cases where it is not possible to use CHECK on attributes and domains In the following example, the query selects all employees whose salaries are greater than the salary of the manager of their department. If the result of the query is not empty, the assertion is violated. Module 4 Slides by: Shree Jaswal 80
CREATE TRIGGER statement Used to monitor the database Typical trigger has three components: Event(s):These are usually database update operations that are explicitly applied to the database. Condition: Determines whether the rule action should be executed: Once the triggering event has occurred, an optional condition may be evaluated. Action: The action is usually a sequence of SQL statements, but it could also be a database transaction or an external program that will be automatically executed Module 4 Slides by: Shree Jaswal 81
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 Suppose that the action to take would be to call an external stored procedure SALARY_VIOLATION,5 which will notify the supervisor. The trigger could then be written as in R5 below. R5: 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 ); Module 4 Slides by: Shree Jaswal 82
Event(s): In this example the events are: inserting a new employee record, changing an employee s salary, or changing an employee s supervisor. These events are specified after the keyword BEFORE in our example. An alternative is to use the keyword AFTER Condition: The condition is specified in the WHEN clause of the trigger. Action: In this example, the action is to execute the stored procedure INFORM_SUPERVISOR. Module 4 Slides by: Shree Jaswal 83
Concept of a view in SQL Single table derived from other tables Considered to be a virtual table Module 4 Slides by: Shree Jaswal 84
CREATE VIEW command Give table name, list of attribute names, and a query to specify the contents of the view Module 4 Slides by: Shree Jaswal 85
Module 4 Slides by: Shree Jaswal 86
Specify SQL queries on a view View always up-to-date Responsibility of the DBMS and not the user DROP VIEW command Dispose of a view Module 4 Slides by: Shree Jaswal 87
Complex problem of efficiently implementing a view for querying Query modification approach Modify view query into a query on underlying base tables Disadvantage: inefficient for views defined via complex queries that are time-consuming to execute Module 4 Slides by: Shree Jaswal 88
View materialization approach Physically create a temporary view table when the view is first queried Keep that table on the assumption that other queries on the view will follow Requires efficient strategy for automatically updating the view table when the base tables are updated Module 4 Slides by: Shree Jaswal 89
Incremental update strategies DBMS determines what new tuples must be inserted, deleted, or modified in a materialized view table Module 4 Slides by: Shree Jaswal 90
Update on a view defined on a single table without any aggregate functions Can be mapped to an update on underlying base table View involving joins Often not possible for DBMS to determine which of the updates is intended Module 4 Slides by: Shree Jaswal 91
Clause WITH CHECK OPTION Must be added at the end of the view definition if a view is to be updated In-line view Defined in the FROM clause of an SQL query Module 4 Slides by: Shree Jaswal 92
DROP command Used to drop named schema elements, such as tables, domains, or constraint Drop behavior options: CASCADE and RESTRICT Example: DROP TABLE DEPENDENT CASCADE; Module 4 Slides by: Shree Jaswal 93
Alter table actions include: Adding or dropping a column (attribute) Changing a column definition Adding or dropping table constraints Example: ALTER TABLE COMPANY.EMPLOYEE ADD COLUMN Job VARCHAR(12); To drop a column Choose either CASCADE or RESTRICT Module 4 Slides by: Shree Jaswal 94
Change constraints specified on a table Add or drop a named constraint Module 4 Slides by: Shree Jaswal 95
96 Module 4 Slides by: Shree Jaswal