89
6. DML Statements of SQL INSERT, UPDATE, DELETE and SELECT Statements SELECT DISTINCT, ALL, Column Alias, Column Expressions WHERE Clause and Search Conditions Logical and Relational Operators NULL, LIKE, IN and BETWEEN Predicates ORDER BY Clause Aggregate Functions, GROUP BY and HAVING Clauses Sub-queries, Quantifiers, EXISTS and NOT EXISTS Predicates Joins, Cartesian Products and Cross Join, Inner and Outer Joins Set Operations

Database Systems - SQL - DDL Statements (Chapter 3/3)

Embed Size (px)

Citation preview

Page 1: Database Systems - SQL - DDL Statements (Chapter 3/3)

6. DML Statements of SQL

INSERT, UPDATE, DELETE and SELECT Statements

SELECT DISTINCT, ALL, Column Alias, Column Expressions

WHERE Clause and Search Conditions

Logical and Relational Operators

NULL, LIKE, IN and BETWEEN Predicates

ORDER BY Clause

Aggregate Functions, GROUP BY and HAVING Clauses

Sub-queries, Quantifiers, EXISTS and NOT EXISTS Predicates

Joins, Cartesian Products and Cross Join, Inner and Outer Joins

Set Operations

Page 2: Database Systems - SQL - DDL Statements (Chapter 3/3)

SQL DML Statements

There are 4 DML statements:

DML

Statements

SELECT

INSERT

UPDATE

DELETE

Page 3: Database Systems - SQL - DDL Statements (Chapter 3/3)

INSERT Statement

The INSERT statement adds a row to the specified table.

Syntax: INSERT INTO table-name [ ( column-list ) ] VALUES ( value-list )

column-list: Comma separated columns value-list: Comma separated values

Examples:

INSERT INTO books VALUES (10001, ’Harry Potter and The Chamber of Secrets’, ’J.K. Rowling’, ’Bloomsbury’); INSERT INTO books (book_id) VALUES (10002); INSERT INTO books (book_title, book_id) VALUES (’Android 4 Application Development’, 10005);

Page 4: Database Systems - SQL - DDL Statements (Chapter 3/3)

INSERT Statement Contents of table “books”

Page 5: Database Systems - SQL - DDL Statements (Chapter 3/3)

UPDATE Statement The UPDATE statement modifies values of specified columns of specified table of all rows or only those rows that satisfy given search condition.

Syntax: UPDATE table-name SET column-name = value [, column-name = value ] … [ WHERE search-condition ]

search-condition: An expression containing column names and/or literals with relational operators and logical operators yielding a boolean value.

Examples:

UPDATE books SET publisher = ’Bloomsbury’; UPDATE books SET book_title = ’Harry Potter and The Philosopher\’s Stone’ WHERE book_id = 10001;

Page 6: Database Systems - SQL - DDL Statements (Chapter 3/3)

UPDATE Example Results

Result of executing two update statements shown in the earlier slide:

Page 7: Database Systems - SQL - DDL Statements (Chapter 3/3)

DELETE Statement

The DELETE statement deletes all rows or only those rows that satisfy given search condition from the specified table. Syntax: DELETE FROM table-name [ WHERE search-condition ] search-condition: An expression containing column names and/or literals with relational operators and logical operators yielding a boolean value. Examples: DELETE FROM books WHERE book_id = 10005;

Page 8: Database Systems - SQL - DDL Statements (Chapter 3/3)

DELETE Statement Example Results

The slide shows contents of table books after executing the delete statement specified in the previous slide.

Page 9: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT Statement

The SELECT statement retrieves all rows or only those rows that satisfy given search condition from the list of specified tables.

SELECT statement syntax is complex of all SQL statements. A simple SELECT statement syntax is as follows:

Syntax:: SELECT [ DISTINCT | ALL ] { * | { column-expr [ AS column-alias ] } [ , column-expr [ AS column-alias ] ] … FROM table-name [ table-alias ] [, table-name [ table-alias ] ] … [ WHERE search-condition ] [ GROUP BY grp-column-list ] [ HAVING search-condition ] [ ORDER BY ord-column-list ]

column-expr: An expression whose value will form a column value in the result of the SELECT statement. search-condition: An expression to select only those rows satisfying the expression.

Page 10: Database Systems - SQL - DDL Statements (Chapter 3/3)

Tables for Demonstration

CREATE TABLE emp( eno INTEGER NOT NULL PRIMARY KEY, ename VARCHAR (50) NOT NULL, designation VARCHAR(50) NOT NULL, salary DECIMAL(10, 2), mno INTEGER NULL, dno INTEGER NOT NULL REFERENCES dept(dno) );

CREATE TABLE bldg( bno INTEGER NOT NULL PRIMARY KEY, bname VARCHAR (50) NOT NULL, city VARCHAR(50) NOT NULL );

CREATE TABLE dept( dno INTEGER NOT NULL PRIMARY KEY, dname VARCHAR (50) NOT NULL, mno INTEGER NULL, bno INTEGER NOT NULL REFERENCES bldg(bno) );

Tables with primary keys and foreign keys:

ALTER TABLE dept ADD FOREIGN KEY (mno) REFERENCES emp(eno);

Page 11: Database Systems - SQL - DDL Statements (Chapter 3/3)

Data for Building Table bldg

INSERT INTO bldg VALUES(1, ’UB Tower’, ’Bangalore’); INSERT INTO bldg VALUES(2, ’Cyber Tower’, ’Hyderabad’); INSERT INTO bldg VALUES(3, ’Discoverer, ITPL’, ’Bangalore’); INSERT INTO bldg VALUES(4, ’ Maker Towers’, ’Mumbai’);

Page 12: Database Systems - SQL - DDL Statements (Chapter 3/3)

Data for Department Table dept

INSERT INTO dept VALUES(11, ’Corporate’, NULL, 1); INSERT INTO dept VALUES(22, ’HR’, NULL, 1); INSERT INTO dept VALUES(33, ’ Accounts’, NULL, 1); INSERT INTO dept VALUES(44, ’Projects’, NULL, 2); INSERT INTO dept VALUES(55, ’Products’, NULL, 3);

Page 13: Database Systems - SQL - DDL Statements (Chapter 3/3)

Data for Employee Table emp

INSERT INTO emp VALUES(111, ’Akhil’, ’President & CEO’, 500000, 111, 11); INSERT INTO emp VALUES(112, ’Dinesh’, ’COO’, 300000, 111, 11); INSERT INTO emp VALUES(113, ’Bhaskar’, ’CTO’, 300000, 111, 11); INSERT INTO emp VALUES(114, ’Harish’, ’CFO’, 300000, 111, 11);

INSERT INTO emp VALUES(221, ’Rajesh’, ’HR Manager’, 75000, 112, 22); INSERT INTO emp VALUES(222, ’Mathew’, ’HR Executive’, 50000, 221, 22);

INSERT INTO emp VALUES(331, ’Bala’, ’Accounts Manager’, 75000, 114, 33); INSERT INTO emp VALUES(332, ’Venky’, ’Accounts Trainee’, 20000, 331, 33);

INSERT INTO emp VALUES(441, ’Suri’, ’Manager - Projects’, 75000, 113, 44); INSERT INTO emp VALUES(442, ’Vinny’, ’Engineer’, 25000, 441, 44); INSERT INTO emp VALUES(443, ’Bhargav’, ’Engineer’, 20000, 442, 44);

INSERT INTO emp VALUES(551, ’Jimson’, ’Manager - Products’, 75000, 113, 55); INSERT INTO emp VALUES(552, ’Niranjan’, ’Engineer’, 50000, 551, 55); INSERT INTO emp VALUES(553, ’Praveen’, ’Engineer’, 25000, 552, 55); INSERT INTO emp VALUES(554, ’Sugumar’, ’Engineer’, 20000, 552, 55);

Page 14: Database Systems - SQL - DDL Statements (Chapter 3/3)

Setting up Managers for Departments

The following statements setup managers for Corporate, Projects and Products departments: UPDATE dept SET mno = 111 WHERE dno = 11; UPDATE dept SET mno = 112 WHERE dno = 44; UPDATE dept SET mno = 113 WHERE dno = 55;

Page 15: Database Systems - SQL - DDL Statements (Chapter 3/3)

Select Examples Projecting All Columns of A Table

Project all columns from table emp: SELECT eno, ename, designation, salary, mno, dno FROM emp;

Page 16: Database Systems - SQL - DDL Statements (Chapter 3/3)

Select Examples Projecting A Few Columns of A Table

Project two columns from table emp: SELECT ename, salary FROM emp;

Page 17: Database Systems - SQL - DDL Statements (Chapter 3/3)

Select Examples Using Table Alias

Table alias e used for table emp: SELECT e.ename, e.salary FROM emp e;

Page 18: Database Systems - SQL - DDL Statements (Chapter 3/3)

Select Examples Projecting All Columns with *

Project all columns from table emp: SELECT * FROM emp;

Using a table alias: SELECT e.* FROM emp e

Page 19: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT Examples: DISTINCT Clause

SELECT designation FROM emp;

SELECT DISTINCT designation FROM emp

The DISTINCT clause gives only distinct rows as result set of SELECT statement.

Page 20: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT Examples: ALL Clause

SELECT designation FROM emp;

SELECT ALL designation FROM emp

The ALL specified before result set column expressions makes the SELECT to return all rows.

Page 21: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT Examples: Result Column Names using AS Clause

SELECT eno AS ’Employee Number’, ename AS ’Employee Name’ FROM emp

SELECT eno, ename FROM emp

Page 22: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT: Column Expressions

Salary raise by 10%: SELECT ename , salary + salary * 0.1 FROM emp

Salary raise by 10% with name for the column expression: SELECT ename , salary + salary * 0.1 AS ’New Salary’ FROM emp

Page 23: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT: Row Selection Using WHERE Clause

• The WHERE clause is used to specify a condition to select only those rows from the input tables that satisfy the condition.

• The condition is known as Search Condition. • The condition should evaluate to a BOOLEAN value: TRUE or FALSE • The SELECT statement evaluates search condition for each row of

the table specified in the FROM clause by substituting columns of the condition with values from the row. If the search condition evaluates to TRUE, the statement selects the row and outputs.

• Arithmetic and Logical operators can be used in the search condition.

• Search Condition can contain columns, literals and even other SELECT statements.

Page 24: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT: WHERE Clause Search Condition Operators

Logical Operators: AND, OR, NOT Relational Operators: =, !=, <>, >, <. >= , <= Quantifiers: ALL, ANY, SOME Specific Predicates: NULL, LIKE, CONTAINS, EXISTS, IN, BETWEEN

Page 25: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT: Row Selection Using WHERE Clause

Employees who work in Products department: SELECT ename , salary FROM emp WHERE dno = 55

Employees who work in Products department and whose salary is more than Rs 25000: SELECT ename , salary FROM emp WHERE dno = 55 AND salary > 25000

Page 26: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT : WHERE clause - LOGICAL operators AND & OR

Employees who work in department number 44 or 55: SELECT ename , salary, dno FROM emp WHERE dno = 44 OR dno = 55

Employees who work in department number 55 and get salary of more than Rs 50,000: SELECT ename , salary, dno FROM emp WHERE dno = 55 AND salary > 50000

Page 27: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT: WHERE clause - LOGICAL operator NOT Employees who do not work in department number 44 or 55: SELECT ename , salary, dno FROM emp WHERE NOT (dno = 44 OR dno = 55)

Page 28: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT: WHERE clause – Other Relational operators != and <>

You already saw usage of relational operators =, > and <. The behaviors of operators != and <> are equivalent. Here is an example: Employees who do not work in both departments 44 and 55: SELECT ename , salary, dno FROM emp WHERE dno != 44 AND dno <> 55;

Page 29: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT: WHERE clause – Other Relational operators >= and <=

Employees who earn salary Rs 25,000 or more but 50,000 or less: SELECT ename , salary FROM emp WHERE salary >= 25000 AND salary <= 50000

Page 30: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT : WHERE clause – IS NULL Operator in NULL Predicate

The NULL operator is used to check if a value of a column in a row is NULL.

Departments who do not have a manager:

SELECT * FROM dept WHERE mno IS NULL

Departments who have a manager:

SELECT * FROM dept WHERE mno IS NOT NULL

NULL predicate

NULL predicate

Page 31: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT: WHERE clause – Incorrect use of NULL in predicates

SELECT * FROM dept WHERE mno = NULL;

WRONG!

SELECT * FROM dept WHERE mno != NULL;

WRONG!

Page 32: Database Systems - SQL - DDL Statements (Chapter 3/3)

SELECT: WHERE clause – LIKE Operator & LIKE Predicate

The LIKE operator is used to do pattern matching with character columns. Employees whose names start with ’B’: SELECT ename FROM emp WHERE ename LIKE ’B%’

Employees whose names do NOT start with ‘B’: SELECT ename FROM emp WHERE ename NOT LIKE ’B%’

LIKE predicate

LIKE predicate

Page 33: Database Systems - SQL - DDL Statements (Chapter 3/3)

LIKE Operator: Pattern Matching Characters % and _

% matches with any zero or more characters whereas _ matches with any one character. Employees whose names have ’i’ in second position: SELECT ename FROM emp WHERE ename LIKE ’_i%’

Employees whose names have ’a’ and ‘k’ in that order: SELECT ename FROM emp WHERE ename LIKE ’%a%k%’

Page 34: Database Systems - SQL - DDL Statements (Chapter 3/3)

LIKE Operator with ESCAPE clause

The ESCAPE clause is needed if the column values contain the pattern matching characters % and _.

If a column, offer, values are ’50% discount’, ‘30 percent discount’, ‘no discount’, to select rows that contain the % character, the following LIKE with ESCAPE can be used: Items having % character in offer column:

SELECT item_name, offer FROM store WHERE offer LIKE ’%#%%’ ESCAPE ’#’ Using predefined escape character ’\’: SELECT item_name, offer FROM store WHERE offer LIKE ’%\%%’

Page 35: Database Systems - SQL - DDL Statements (Chapter 3/3)

IN Operator & IN Predicate

The IN operator is used to specify a list of values a column expression has to satisfy: Employees who work in departments 11, 44 or 55: SELECT ename FROM emp WHERE dno IN (11, 44, 55)

IN predicate or membership search condition

Equivalent statement without using the IN operator: SELECT ename FROM emp WHERE dno = 11 OR dno = 44 OR dno = 55

Page 36: Database Systems - SQL - DDL Statements (Chapter 3/3)

BETWEEN Operator & BETWEEN Predicate

The BETWEEN operator is used to specify a range of values a column expression has to satisfy. Employees whose salary range is 25000 to 75000: SELECT ename, salary FROM emp WHERE salary BETWEEN 25000 AND 75000

BETWEEN predicate or Range search condition

The result includes end points of the range. The end points are values 25000 and 75000 in the above example.

Page 37: Database Systems - SQL - DDL Statements (Chapter 3/3)

ORDER BY Clause for Sorting Results

The ORDER BY clause is used to sort results of SELECT statements.

Syntax: ORDER BY {{ column-name | column-number } [ ASC | DESC ] } [, …]

column-number: serial number of a column expression in SELECT clause • The ORDER BY clause should be the last clause of a SELECT

statement. • Column names should be in SELECT clause. But some RDBMSs allow

columns not in the SELECT clause. • ASC causes results in ascending order of the column. This is default. • DESC causes results in descending order of the column. • Column numbers start from 1.

Page 38: Database Systems - SQL - DDL Statements (Chapter 3/3)

ORDER BY Clause Examples with one column

Results in ascending order of values of one column: SELECT ename, salary, eno FROM emp ORDER BY ename

Results in descending order of values of one column: SELECT ename, salary, eno FROM emp ORDER BY ename DESC

Page 39: Database Systems - SQL - DDL Statements (Chapter 3/3)

ORDER BY Clause Examples with two columns

Results in ascending order of values of two columns: SELECT salary, ename, eno FROM emp ORDER BY salary, ename

Results in descending order of values of first column and ascending order of second column: SELECT salary, ename, eno FROM emp ORDER BY salary DESC, ename ASC

Page 40: Database Systems - SQL - DDL Statements (Chapter 3/3)

ORDER BY Clause Examples with Column Expression numbers

Ordering based on column numbers: SELECT salary, ename, eno FROM emp ORDER BY 1 DESC, 3 ASC

Ordering based on expressions: SELECT salary, salary * 0.2, ename, eno FROM emp ORDER BY 2 DESC, 1 ASC

Page 41: Database Systems - SQL - DDL Statements (Chapter 3/3)

SQL Aggregate Functions

COUNT

SUM

AVG

MAX

MIN

Page 42: Database Systems - SQL - DDL Statements (Chapter 3/3)

SQL Aggregate Functions

An aggregate function gives one value from multiple values of a column.

SQL standard defined aggregate functions are as follows:

SNO Aggregate

Function

Functionality

1 COUNT Returns number of values in a column or count of rows.

2 SUM Returns sum of the values of a numeric column.

3 AVG Returns average of values of a numeric column.

4 MIN Returns the smallest value in a column.

5 MAX Returns the largest value in a column.

Page 43: Database Systems - SQL - DDL Statements (Chapter 3/3)

SQL Aggregate Function Usage

SUM and AVG functions can be used on only numeric columns. Each function takes one argument which should be a column name. COUNT can be applied on all columns using COUNT(*) which will return number of rows in a table as qualified by WHERE clause. Except COUNT(*) all other aggregate functions ignore NULL values in a column. Aggregate functions can be used only in SELECT and HAVING clauses. If SELECT clause contains any aggregate function, the select list can contain only those columns used in GROUP BY clause in addition to aggregate functions. It can not contain any other column references.

Page 44: Database Systems - SQL - DDL Statements (Chapter 3/3)

SQL Aggregate Function Examples: COUNT with and without NULLs

The screen shot on the right side shows there are 6 employees in department 55 using a select statement without using aggregate functions..

SELECT COUNT(ename) FROM emp WHERE dno = 55 SELECT COUNT(salary) FROM emp WHERE dno = 55 SELECT COUNT(*) FROM emp WHERE dno = 55; Note that NULL values are considered in the counts..

Page 45: Database Systems - SQL - DDL Statements (Chapter 3/3)

SQL Aggregate Function Examples: MAX, MIN, SUM & AVG

The screen shot shows there are 6 employees in department number 55. SELECT MAX(salary), MIN(salary), SUM(salary), AVG(salary) FROM emp WHERE dno = 55; Note that NULL values are not considered in computing aggregate values. For example, we can find that AVG(salary) = SUM(salary)/4 where the sum is divided by the number of non-null values and not

number of all values in the column.

Page 46: Database Systems - SQL - DDL Statements (Chapter 3/3)

SQL Aggregate Function Examples: COUNT (DISTINCT…)

The screen shot shows there are 6 employees in department number 55. SELECT COUNT(DISTINCT designation), COUNT(DISTINCT salary), COUNT(DISTINCT mno) FROM emp WHERE dno = 55 Note that NULL values are not considered in the counts with DISTINCT.

Page 47: Database Systems - SQL - DDL Statements (Chapter 3/3)

Grouping Results Partitioning of Rows into Groups

GROUP BY Clause

Grouping Columns

Aggregate Functions

Page 48: Database Systems - SQL - DDL Statements (Chapter 3/3)

GROUP BY clause

The GROUP BY clause groups results of a SELECT statement based on grouping column list specified for the clause.

Syntax: GROUP BY grp_column_list

grp_column_list: List of comma separated column names.

Example: SELECT dno, COUNT(eno), MAX(salary) FROM emp GROUP BY dno This select statement outputs one row for each department containing the department number, count of employees in the department and maximum salary given in the department.

Grouping column list: dno

Page 49: Database Systems - SQL - DDL Statements (Chapter 3/3)

GROUP BY clause examples

The following statement groups employees by department number:

SELECT dno, COUNT(eno), MAX(salary) FROM emp GROUP BY dno

The following statement groups employees by department number and designation:

SELECT dno, designation, COUNT(eno), MAX(salary) FROM emp GROUP BY dno, designation

Page 50: Database Systems - SQL - DDL Statements (Chapter 3/3)

GROUP BY clause: Points to be noted

1. A query that contains GROUP BY clause is known as grouped query.

2. Columns named in the GROUP BY clause are known as grouping columns.

3. Each item (column or expression) in the SELECT clause must be single valued per group. Hence the item has to be a grouping column or an aggregate function. It is an error to use non-grouping columns in the SELECT clause.

4. Grouping is done only after applying WHERE clause if it exists in a SELECT statement.

Page 51: Database Systems - SQL - DDL Statements (Chapter 3/3)

Restricting Groups: HAVING clause

The HAVING clause is used to restrict resulting rows of the GROUP BY clause. Syntax: HAVING search-condition The search condition is similar WHERE clause search condition. Unlike WHERE clause search condition, the HAVING clause search condition can contain aggregate functions. If the search condition contains any predicate that does not contain grouping columns or aggregate functions, such predicate may be moved to WHERE clause.

Page 52: Database Systems - SQL - DDL Statements (Chapter 3/3)

HAVING clause example

The following statement restricts to groups having number of employees 4 or more.

SELECT dno, COUNT(eno), MAX(salary) FROM emp GROUP BY dno HAVING COUNT(eno) >= 4

Page 53: Database Systems - SQL - DDL Statements (Chapter 3/3)

Subqueries Subqueries: Scalar Subqueries, Row Subqueries,

Table Subqueries

Quantifiers : ANY, SOME and ALL

Predicate: IN, EXISTS and NOT EXISTS

Page 54: Database Systems - SQL - DDL Statements (Chapter 3/3)

Subqueries

Subquery is a query embedded in another query. Subquery is also referred to as inner select, subselect or nested query or nested statement. The query that contains the subquery is called outer query or outer statement. Subqueries can be used in WHERE clause, HAVING clause and SELECT clause of SELECT statements. Subqueries can also be used in INSERT, UPDATE and DELETE statements.

Page 55: Database Systems - SQL - DDL Statements (Chapter 3/3)

Types of Subqueries

Scalar subquery: Returns only one column and one row; essentially one value. The query can be used in predicates as an operand for relational operators =, !=, <, <=, > and >=. Row subquery: Returns multiple columns in one row. Table subquery: Returns multiple columns and multiple rows.

Page 56: Database Systems - SQL - DDL Statements (Chapter 3/3)

Example: Scalar Subquery in WHERE clause

The following statement uses a scalar subquery that returns department number of department “Products” to list all employees of the department.

SELECT ename, salary FROM emp WHERE dno = (SELECT dno FROM dept WHERE dname=’Products’)

Page 57: Database Systems - SQL - DDL Statements (Chapter 3/3)

Example: Scalar Sub-query with Aggregate function in WHERE clause

The following statement returns employees whose salary is more than average salary of all employees using a scalar subquery that returns average salary of all employees:

SELECT ename, salary FROM emp WHERE salary > (SELECT AVG(salary) FROM emp)

Page 58: Database Systems - SQL - DDL Statements (Chapter 3/3)

Example: Scalar Sub-query in SELECT clause

The following statement returns employee name and difference between salary and average salary of all those employees whose salary is more than average salary:

SELECT ename, salary - (SELECT AVG(salary) FROM emp) AS SalDiff FROM emp WHERE salary > (SELECT AVG(salary) FROM emp)

Page 59: Database Systems - SQL - DDL Statements (Chapter 3/3)

Example: Nested Subquery

The following statement returns number of employees whose buildings are situated in Bangalore.

SELECT COUNT(*) FROM emp WHERE dno IN (SELECT dno FROM dept WHERE bno IN (SELECT bno FROM bldg WHERE city =’Bangalore’))

Page 60: Database Systems - SQL - DDL Statements (Chapter 3/3)

Predicates with Quantifiers: ANY, SOME and ALL

Keywords ANY, SOME and ALL are called quantifiers used to modify meaning of relational operators in predicates that contain sub-queries. Syntax: opd rel-oper { ANY | SOME | ALL } sub-query opd is an operand which could be a literal, column or a scalar sub-query or an expression containing them. rel-oper is any relational operator >, >=, <, <=, =, != sub-query should project only one column but any number of rows. If ANY or SOME quantifier is used, the predicate value is TRUE if it is satisfied with any one value returned by the sub-query. Otherwise, it is false. If the sub-query does not return any row, the predicate value is FALSE. If ALL quantifier is used, the predicate value is TRUE if it is satisfied with all values returned by the sub-query. Otherwise, it is false. If the sub-query does not return any row, the predicate value is TRUE.

Page 61: Database Systems - SQL - DDL Statements (Chapter 3/3)

An Example using quantifier ANY

The following statement finds all employees who work in departments other than 55 and whose salary is greater than the salary of at least one employee of department 55: SELECT ename, dno, salary FROM emp WHERE dno != 55 AND salary > ANY (SELECT salary FROM emp WHERE dno = 55)

Page 62: Database Systems - SQL - DDL Statements (Chapter 3/3)

An Example using quantifier: ALL

The following statement finds all employees who work in departments other than 55

and whose salary is greater than the salary of all employees of department 55: SELECT ename, dno, salary FROM emp WHERE dno != 55 AND salary > ALL (SELECT salary FROM emp WHERE dno = 55)

Page 63: Database Systems - SQL - DDL Statements (Chapter 3/3)

Predicates EXISTS and NOT EXISTS

The predicates EXISTS and NOT EXISTS can be used only with sub-queries. Syntax: WHERE EXISTS sub-query WHERE NOT EXISTS sub-query The predicate EXISTS evaluates to true if the sub-query returns at least one row. Otherwise it evaluates to false. The predicate NOT EXISTS is true if the sub-query does not return any row, i.e., it returns empty result set. False otherwise. The behavior is opposite of EXISTS predicate. The sub-query can project one or more columns or expressions.

Page 64: Database Systems - SQL - DDL Statements (Chapter 3/3)

Examples of predicates EXISTS and NOT EXISTS

Find cities where company departments are located.

SELECT DISTINCT b.city FROM bldg b WHERE EXISTS (SELECT * FROM dept d WHERE d.bno = b.bno)

Find cities that do not yet have a company department:

SELECT DISTINCT b.city FROM bldg b WHERE NOT EXISTS (SELECT * FROM dept d WHERE d.bno = b.bno);

Page 65: Database Systems - SQL - DDL Statements (Chapter 3/3)

Sub-query Points to Remember

• Scalar subqueries need to be used with relational operators and in

all places in an SQL statement where only one value is expected.

• Quantifiers can be used only with relational operators.

• Subqueries used with Quantifiers as well as IN operator must be table subqueries with one result column.

• Subqueries used with EXISTS and NOT EXISTS predicates can be any kind of subqueries.

• ORDER BY clause may not be allowed inside sub-queries. Some RDBMSs allow the clause as it makes sense if TOP clause is used in the SELECT clause.

Page 66: Database Systems - SQL - DDL Statements (Chapter 3/3)

Multi-Table Queries (JOINS)

Table List & Table Alias

Equi-joins

Sorting and Grouping Result sets

Cartesian Product & Cross Join

Inner Joins

Outer Joins

Left Outer Join, Right Outer Join and Full Outer Join

Page 67: Database Systems - SQL - DDL Statements (Chapter 3/3)

Multi-Table Queries or JOINs

The multi-table queries involve more than one table in the FROM clause of SELECT statements which combine columns of the tables and output specified columns as per the select-list of the statements. The operation used for combing columns is called join operation. The join operation on two tables gives rows where each row consists of required columns of a row of a table and required columns of rows of another table such that specified predicates where each predicate containing columns of the two tables are satisfied.

Page 68: Database Systems - SQL - DDL Statements (Chapter 3/3)

Table List & Table Alias

Table List in the FROM clause is separated by comma. Each table can be optionally followed by an alias which can be used wherever table name is required. An alias can be used as a qualifier for column name in order to use the alias as shorthand for table name and/or to disambiguate column names which could be same in multiple tables. In order to use an alias for a column, prefix column name with the alias separated by a dot. Example: t1.c1

Page 69: Database Systems - SQL - DDL Statements (Chapter 3/3)

Two Table Join with equal-to predicate : Equi-Join

List names of employees and departments they work for: SELECT e.ename, d.dname FROM emp e, dept d WHERE e.dno = d.dno

Page 70: Database Systems - SQL - DDL Statements (Chapter 3/3)

Two Table Join – Sorting results

List names of employees and departments they work for in the

ascending order of department name and employee name in each department:

SELECT e.ename, d.dname FROM emp e, dept d WHERE e.dno = d.dno ORDER BY d.dname, e.ename

Page 71: Database Systems - SQL - DDL Statements (Chapter 3/3)

Two Table Join – Grouping results

Find number of employees in each department:

SELECT d.dname AS ’Department’, COUNT(*) AS ’Number of Employees’ FROM emp e, dept d WHERE e.dno = d.dno GROUP BY d.dname ORDER BY d.dname

Page 72: Database Systems - SQL - DDL Statements (Chapter 3/3)

Three Table Join

Find city and department for each employee: SELECT b.city AS ’City’, d.dname AS ’Department’, e.ename AS ’Employee’ FROM emp e, dept d, bldg b WHERE e.dno = d.dno AND d.bno = b.bno ORDER BY 1, 2, 3

Page 73: Database Systems - SQL - DDL Statements (Chapter 3/3)

Cartesian Product using CROSS JOIN

The Cartesian product of two tables is another table consisting of all possible pairs of rows from the two tables.

Syntax: table1 CROSS JOIN table2

The columns of the Cartesian product consist of all columns of the table1 followed by all columns of the table2.

If a join condition (in WHERE clause) is not specified for two tables in a two table join, the Cartesian product is produced.

Example: A B

a1 b1

a2 b2

a3 b3

C D E

c1 d1 e1

c2 d2 e2

A B C D E

a1 b1 c1 d1 e1

a1 b1 c2 d2 e2

a2 b2 c1 d1 e1

a2 b2 c2 d2 e2

a3 b3 c1 d1 e1

a3 b3 c2 d2 e2

CROSS JOIN = A, B, C, D and E are names of columns.

Page 74: Database Systems - SQL - DDL Statements (Chapter 3/3)

Cartesian Product – Example

Find Cartesian product of emp and dept tables.

SELECT * FROM emp CROSS JOIN dept;

=

Tables: emp and dept

Result set

Page 75: Database Systems - SQL - DDL Statements (Chapter 3/3)

INNER JOINS and OUTER JOINS

Inner Join: So far whatever joins we have talked about are essentially inner joins. An inner join outputs rows from two tables that match the join condition. Inner joins can be written using list of tables, INNER JOIN keyword or just JOIN keyword.

Outer Join: An outer join returns rows that not only match the join condition but also those that do not match the join condition. There are three types of outer joins: LEFT OUTER JOIN, RIGHT OUTER JOIN and FULL OUTER JOIN.

Page 76: Database Systems - SQL - DDL Statements (Chapter 3/3)

INNER JOIN with List of Tables

The simplest way to write an inner join query is to have a comma separated list of required tables in the FROM clause of a query. This syntax is already familiar to you. Example: SELECT ot1.*, ot2.* FROM ot1, ot2 WHERE ot1.b = ot2.b;

Note that row <a4, NULL> of table ot1 does not match with any row of table ot2 even though column b of table ot2 has NULL values in two rows because NULL values can not be compared; NULL is an unknown value.

Page 77: Database Systems - SQL - DDL Statements (Chapter 3/3)

Inner Join with key words INNER & JOIN

If you want to write an inner join query that explicitly shows that it is such a query, use the keywords INNER and JOIN as shown in the following example: SELECT ot1.*, ot2.* FROM ot1 INNER JOIN ot2 WHERE ot1.b = ot2.b; Or SELECT ot1.*, ot2.* FROM ot1 JOIN ot2 WHERE ot1.b = ot2.b; Use of keyword INNER is optional.

Page 78: Database Systems - SQL - DDL Statements (Chapter 3/3)

LEFT OUTER JOIN

A left outer join of two tables returns rows that match specified join condition between the two tables as well as non-matching rows from the left table of the join. Values for the columns of the right table of the join will receive NULL values for the non-matching rows of the left table of the join. Here is an example: SELECT t1.*, t2.* FROM t1 LEFT OUTER JOIN t2 ON t1.b = t2.b;

•Keyword OUTER is optional. •ON keyword is used to specify the outer join condition.

Only rows <a1,b1> and <a3,b3> of t1 have matching rows in t2 based on the join condition. As it is left outer join , remaining rows of t1 (<a2,b2> and <a4, NULL>) have NULL values for columns b and c of t2.

Page 79: Database Systems - SQL - DDL Statements (Chapter 3/3)

RIGHT OUTER JOIN

A right outer join of two tables returns rows that match specified join condition between the two tables as well as non-matching rows from the right table of the join. Values for the columns of the left table of the join will receive NULL values for the non-matching rows of the right table of the join. Here is an example: SELECT t1.*, t2.* FROM t1 RIGHT OUTER JOIN t2 ON t1.b = t2.b;

•Keyword OUTER is optional. •ON keyword is used to specify the outer join condition.

Only rows <b1,c1> and <b3,c3> of t2 have matching rows in t1 based on the join condition. As it is right outer join , remaining rows of t2 (<NULL,c2> , <NULL, c4> and <b5,c5>) have NULL values for columns a and b of t1.

Page 80: Database Systems - SQL - DDL Statements (Chapter 3/3)

FULL OUTER JOIN

A full outer join of two tables returns rows that match specified join condition between the two tables as well as non-matching rows from the both tables of the join. Values for the columns of the left table of the join will receive NULL values for the non-matching rows of the right table of the join and vice versa. Here is an example:

SELECT t1.*, t2.* FROM t1 FULL OUTER JOIN t2 ON t1.b = t2.b

In the result of the full outer join, •1st and 5th rows are the matching rows. •6th and 7th rows are non-matching rows from t1 and they have NULLs for columns of t2. •2nd,3rd and 4th rows are non-matching rows from t2 and they have NULLs for columns of t1. •Keyword OUTER is optional. •ON keyword is used to specify the outer join condition.

A B

a1 b1

a2 b2

a3 b3

a4 -

t1 t2

Result

B C

b1 c1

- c2

b3 c3

- c4

b5 c5

A B B C

a1 b1 b1 c1

- - - c2

- - - c4

- - b5 c5

a3 b3 b3 c3

a4 - - -

a2 b2 - -

Page 81: Database Systems - SQL - DDL Statements (Chapter 3/3)

Outer Join support

All database systems may not support all outer joins. MySQL does not support full outer join. Oracle database supports it. The full outer join can be simulated using left and right outer joins as following: SELECT * FROM t1 LEFT OUTER JOIN t2 ON t1.b = t2.b UNION SELECT * FROM t1 RIGHT OUTER JOIN t2 ON t1.b = t2.b

Page 82: Database Systems - SQL - DDL Statements (Chapter 3/3)

SET Operations

UNION

INTERSECT

EXCEPT (MINUS)

Page 83: Database Systems - SQL - DDL Statements (Chapter 3/3)

SET Operations

The set operations are used to combine results returned by other SELECT statements. These operations are UNION, INTERSECT and EXCEPT Each operation takes two table operands which are the result sets of SELECT statements. The two tables must be union-compatible, i.e., they should have the same data structure and hence the same number of columns and the same data types and lengths. Of course most RDBMSs relax above condition. For example, two corresponding columns of two operands need not have the same data type as long as they are compatible.

Page 84: Database Systems - SQL - DDL Statements (Chapter 3/3)

UNION Operation The UNION of two tables is a table containing all rows of both the tables. Set representation of UNION of table A and table B: A ∪ B

A

B Graphical representation: Example:

SELECT a, b FROM t1 UNION SELECT c, b FROM t2

Page 85: Database Systems - SQL - DDL Statements (Chapter 3/3)

UNION Operation: DISTINCT and ALL rows

By default the result table of UNION contains distinct rows as shown in the following example:

Example 1:

SELECT b FROM t1 UNION SELECT b FROM t2

To get all rows from both the tables including duplicates use keyword ALL after keyword UNION as shown in the example:

Example 2:

SELECT b FROM t1 UNION ALL SELECT b FROM t2

Page 86: Database Systems - SQL - DDL Statements (Chapter 3/3)

INTERSECT Operation The INTERSECT operation of two tables is a table containing all rows common to both the tables.

Set representation of INTERSECT of table T1 and table T2: T1 ∩ T2

T1 T2 Graphical representation

Example: SELECT B FROM T1 INTERSECT SELECT B FROM T2

B

b1

b3

-

A B

a1 b1

a2 b2

a3 b3

a4 -

B C

b1 c1

- c2

- c4

b5 c5

b3 c3

T1 T2 Result

Note:-The tables and result shown on the right side are from Oracle RDBMS. MySQL does not support INTERSECT set operation.

Page 87: Database Systems - SQL - DDL Statements (Chapter 3/3)

EXCEPT Operation The EXCEPT operation of two tables is a table containing all rows that are in the first table but are not in the second table. Keyword used for the operation in old SQL standard is MINUS.

Set representation of EXCEPT of table T1 and table T2: T1 − T2 This is essentially set difference.

T1

T2

Graphical representation Example:

SELECT B FROM T1 MINUS SELECT B FROM T2

A B

a1 b1

a2 b2

a3 b3

a4 -

B C

b1 c1

- c2

- c4

b5 c5

b3 c3

T1 T2 Result

Note:-The tables and result shown on the right side are from Oracle RDBMS. MySQL does not support EXCEPT set operation. Oracle does not recognize new keyword EXCEPT.

B

b2

Page 88: Database Systems - SQL - DDL Statements (Chapter 3/3)

What You Have Learnt!

How to add rows to a table using INSERT statements. How to modify rows using UPDATE statements. How to delete rows using DELETE statements. How to retrieve rows using SELECT statements. Retrieving DISTINCT rows and ALL rows. Retrieving rows satisfying a search condition of WHERE

clause. Logical operators AND, OR and NOT. Relational operators =, !=, <>, <, <=, > and >=. Predicates NULL, LIKE, IN and BETWEEN. Sorting result set rows using ORDER BY clause. Aggregate functions COUNT, SUM, AVG, MAX and MIN and

behavior of these functions in the presence of NULL values. Grouping results using GROUP BY clause. Restricting grouped results using HAVING Clause.

Page 89: Database Systems - SQL - DDL Statements (Chapter 3/3)

What You Have Learnt ! (contd…)

Subqueries – Scalar subqueries, row subqueries and table subqueries.

Usage of Quantifiers ALL, ANY and SOME in predicates containing subqueries.

Predicates EXISTS and NOT EXISTS. Multi-table Joins. Cartesian Product and Cross join. Inner joins and outer joins. Left outer joins, right outer joins and full outer joins. Set operators UNION, INTERSECT and EXCEPT (MINUS).