0% found this document useful (0 votes)
6 views

UNIT 04-P3 Database Programming Using SQL

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

UNIT 04-P3 Database Programming Using SQL

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Dr. Suleiman H. Mustafa Slide 5.

3 - 1
UNIT 04 Part-3

Database Programming
– Queries in SQL

Reviewed and Edited by Prof. Suleiman H. Mustafa

Dr. Suleiman H. Mustafa Slide 5.3 - 2


Outline

 Introduction
 SQL Basic Query Structure: Queries from
One Table
 Queries from Multiple Tables
 Join Queries

 Set Queries

 Arithmetic and Aggregate Functions in SQL

Dr. Suleiman H. Mustafa Slide 5.3 - 3


Introduction

Dr. Suleiman H. Mustafa Slide 5.3 - 4


COMPANY relational database schema (Fig. 5.7)

Dr. Suleiman H. Mustafa Slide 5.3 - 5


One possible database state for the COMPANY
relational database schema (Fig. 5.6)

Dr. Suleiman H. Mustafa Slide 5.3 - 6


One possible database state for the COMPANY
relational database schema – continued (Fig. 5.6)

Dr. Suleiman H. Mustafa Slide 5.3 - 7


SQL Basic Query
Structure

Dr. Suleiman H. Mustafa Slide 5.3 - 8


SELECT-FROM-WHERE Clause
 SELECT statement
 One basic statement for retrieving information
from a database
 Basic form of the SELECT statement:

Dr. Suleiman H. Mustafa Slide 5.3 - 9


SELECT-FROM-WHERE Clause

 Projection attributes
 Attributes whose values are to be retrieved
 Conditions
 Selection Condition: Boolean condition that must
be true for any retrieved tuple.
 Join Condition: Boolean condition on join
attributes when multiple relations are involved.
 Logical comparison operators
 =, <, <=, >, >=, and <>

Dr. Suleiman H. Mustafa Slide 5.3 - 10


Queries from One Table

Dr. Suleiman H. Mustafa Slide 5.3 - 11


Unspecified Attributes Using (*)

 Specify an asterisk (*)


 Retrieve all the attribute values of the selected
tuples

Dr. Suleiman H. Mustafa Slide 5.3 - 12


Unspecified WHERE Clause

 Missing WHERE clause


 Indicates no condition on tuple selection
 Effect is a CROSS PRODUCT
 Result is all possible tuple combinations

 Note:
 It is extremely important not to overlook specifying any
selection and join conditions in the WHERE-clause;
 otherwise, incorrect and very large relations may result

Dr. Suleiman H. Mustafa Slide 5.3 - 13


Missing WHERE clause: Example

Dr. Suleiman H. Mustafa Slide 5.3 - 14


Dr. Suleiman H. Mustafa Slide 5.3 - 15
ALL and DISTINCT Tuples in SQL

 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

 Duplicates must be accounted for in aggregate operations


Dr. Suleiman H. Mustafa Slide 5.3 - 16
NULLS IN SQL QUERIES

 SQL allows queries that check if a value is


NULL (i.e., missing or undefined or not
applicable)
 SQL uses IS or IS NOT to compare NULLs
because it considers each NULL value distinct
from other NULL values,
 so equality comparison is not appropriate.

 Query 14: Retrieve the names of all employees who do


not have supervisors.
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE SUPERSSN IS NOT NULL
Dr. Suleiman H. Mustafa Slide 5.3 - 17
Ordering of Query Results
 ORDER BY clause

 Keyword ASC to specify ascending order explicitly


 Keyword DESC to see result in a descending order
of values
 Typically placed at the end of the query

Dr. Suleiman H. Mustafa Slide 5.3 - 18


Ordering of Query Results : Examples

SELECT *
FROM EMPLOYEE
ORDER BY Lname ASC;

SELECT *
FROM EMPLOYEE
ORDER BY SALARY DESC;

Dr. Suleiman H. Mustafa Slide 5.3 - 19


Queries from Multiple
Tables and
Join Operations

Dr. Suleiman H. Mustafa Slide 5.3 - 20


Retrieval from Multiple Tables:
Example-1

Dr. Suleiman H. Mustafa Slide 5.3 - 21


Join Operation

Join Condition

Selection Condition

EMPLOYEE DEPARTMENT
SSN DNO Dnumber Name
Join 5 Research

Dr. Suleiman H. Mustafa Slide 5.3 - 22


Join Operation: Alternative Form

Dr. Suleiman H. Mustafa Slide 5.3 - 23


Queries from Multiple Tables

Dr. Suleiman H. Mustafa Slide 5.3 - 24


Example-2: Queries from Multiple Tables

Dr. Suleiman H. Mustafa Slide 5.3 - 25


Example-3: Queries from Multiple Tables

Join Conditions
Selection Condition

Dr. Suleiman H. Mustafa Slide 5.3 - 26


Join Operation

EMPLOYEE DEPARTMENT
SSN DNO Mgr_
Dnumber DName SSN
Join (2)

PROJECT Join (1)


Pnumber PName PLoc Dnum

Dr. Suleiman H. Mustafa Slide 5.3 - 27


Join-1

Join (1)

Result of Join (1)


Dnum DName Mgr_SSN PNumber PName PLocation
4 Administration 98764321 10 Computerization Stafford
4 Administration 98764321 30 Newbenefits Stafford

Dr. Suleiman H. Mustafa Slide 5.3 - 28


Join-2

Dnum DName Mgr_SSN PNumber PName PLocation


4 Administration 98764321 10 Computerization Stafford
4 Administration 98764321 30 Newbenefits Stafford

Join (2)

Dr. Suleiman H. Mustafa Slide 5.3 - 29


Result of Join-2

Dnum DName Mgr_SSN PNumber PName PLocation Fname


4 Administration 98764321 10 Computerization Stafford Jennifer
4 Administration 98764321 30 Newbenefits Stafford Jennifer

Minit Lname Bdate Address Sex Salary Super_ssn Dno


S Wallace 1941-06-20 291 Berry, Bellaire, TX F 43000 888665555 4
S Wallace 1941-06-20 291 Berry, Bellaire, TX F 43000 888665555 4

Dr. Suleiman H. Mustafa Slide 5.3 - 30


Result of Join-2

Dnum DName Mgr_SSN PNumber PName PLocation Fname


4 Administration 98764321 10 Computerization Stafford Jennifer
4 Administration 98764321 30 Newbenefits Stafford Jennifer

Minit Lname Bdate Address Sex Salary Super_ssn Dno


S Wallace 1941-06-20 291 Berry, Bellaire, TX F 43000 888665555 4
S Wallace 1941-06-20 291 Berry, Bellaire, TX F 43000 888665555 4

Results of Project

Dr. Suleiman H. Mustafa Slide 5.3 - 31


Join with Asterisk and Unspecified
WHERE Clause

 Query Q1D retrieves all the attributes of an EMPLOYEE and


the attributes of the DEPARTMENT in which he or she works
for every employee of the ‘Research’ department, and
 Q10A specifies the CROSS PRODUCT of the EMPLOYEE and
DEPARTMENT relations.
Dr. Suleiman H. Mustafa Slide 5.3 - 32
Join with Unspecified WHERE Clause

result

Dr. Suleiman H. Mustafa Slide 5.3 - 33


Ambiguous Attribute Names
 The same name can be used for two (or
more) attributes in different relations
 As long as the attributes are in different relations
 Must qualify the attribute name with the relation
name to prevent ambiguity

Dr. Suleiman H. Mustafa Slide 5.3 - 34


NESTING OF QUERIES

 Many of the previous queries can be specified


in an alternative form using nesting.
 Example:

Dr. Suleiman H. Mustafa Slide 5.3 - 35


NESTED QUERIES
(Comparison Operator IN)

 A complete SELECT query, called a nested query, can be


specified within the WHERE-clause of another query using
the comparison operator IN, called the outer query
 Example:
 Query: Retrieve the name (first and last) and address of all
employees who work for the 'Research' department.

SELECT FNAME, LNAME, ADDRESS


FROM EMPLOYEE
WHERE DNO IN
(SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME='Research' )
Dr. Suleiman H. Mustafa Slide 5.3 - 36
EXPLICIT SETS Using IN

 It is also possible to use an explicit (enumerated) set of


values in the WHERE-clause rather than a nested query

Query 13: Retrieve the social security numbers of all


employees who work on project number 1, 2, or 3.
Q13: SELECT DISTINCT ESSN
FROM WORKS_ON
WHERE PNO IN (1, 2, 3)

Dr. Suleiman H. Mustafa Slide 5.3 - 37


Set Operations in SQL

Dr. Suleiman H. Mustafa Slide 5.3 - 38


SET OPERATIONS

 SQL has directly incorporated some set


operations, including: UNION, INTERSECT, and
EXCEPT or MINUS (for set difference).
 The resulting relations of these operations are
sets of tuples with no duplicates.
 The set operations apply only to type compatible
relations;
 the two relations must
1. have the same attributes and
2. the attributes must appear in the same order

Dr. Suleiman H. Mustafa Slide 5.3 - 39


Set Operations: Example

UNION MINUS

INTERSECT

Dr. Suleiman H. Mustafa Slide 5.3 - 40


Dr. Suleiman H. Mustafa Slide 5.3 - 41
Example: (Results of Two Queries)

Null

1
2

Dr. Suleiman H. Mustafa Slide 5.3 - 42


Query 4-A

Dr. Suleiman H. Mustafa Slide 5.3 - 43


Query 4-B

Dr. Suleiman H. Mustafa Slide 5.3 - 44


Dr. Suleiman H. Mustafa Slide 5.3 - 45
Dr. Suleiman H. Mustafa Slide 5.3 - 46
Arithmetic and Aggregate
Functions in SQL

Dr. Suleiman H. Mustafa Slide 5.3 - 47


Standard Arithmetic Operations

 Standard arithmetic operators:


 Addition (+), subtraction (–), multiplication (*), and
division (/) may be included as a part of SELECT
 Query 13. Show the resulting salaries if every employee
working on the ‘ProductX’ project is given a 10 percent
raise.
SELECT E.Fname, E.Lname, 1.1 * E.Salary AS
Increased_sal
FROM EMPLOYEE AS E, WORKS_ON AS W,
PROJECT AS P
WHERE E.Ssn=W.Essn AND W.Pno=P.Pnumber AND
P.Pname=‘ProductX’;
Dr. Suleiman H. Mustafa Slide 5.3 - 48
BETWEEN Comparison Operator

 BETWEEN comparison operator

 Example:
SELECT Fname, Lname
FROM EMLOYEE
WHERE (Salary BETWEEN 30000 AND 40000);

Dr. Suleiman H. Mustafa Slide 5.3 - 49


AGGREGATE FUNCTIONS

 SQL provides the following mathematical aggregate


functions: COUNT, SUM, MAX, MIN, and AVG

 EXAMPLE: Find the maximum salary, the minimum salary,


and the average salary among all employees.

 Q15: SELECT MAX(SALARY), MIN(SALARY),


AVG(SALARY)
FROM EMPLOYEE;
 Some SQL implementations may not allow more than one
function in the SELECT-clause

Dr. Suleiman H. Mustafa Slide 5.3 - 50


AGGREGATE FUNCTIONS

Query 16: Find the salary sum, the maximum salary,


the minimum salary, and the average salary among
employees who work for the 'Research' department.

SELECT SUM (SALARY), MAX(SALARY),


MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='Research‘;

Dr. Suleiman H. Mustafa Slide 5.3 - 51


AGGREGATE FUNCTIONS

Q17: Retrieve the total number of employees in the


company

Q17: SELECT COUNT (*)


FROM EMPLOYEE;

Q18: Retrieve the number of employees in the 'Research'


department

Q18: SELECT COUNT (*)


FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='Research’;
Dr. Suleiman H. Mustafa Slide 5.3 - 52
GROUPING

• In many cases, we want to apply the aggregate


functions to subgroups of tuples in a relation

• Each subgroup of tuples consists of the set of


tuples that have the same value for the grouping
attribute(s)
• The function is applied to each subgroup
independently

• SQL has a GROUP BY-clause for specifying the


grouping attributes, which must also appear in
the SELECT-clause.
Dr. Suleiman H. Mustafa Slide 5.3 - 53
GROUPING (contd.)

 Query 20: For each department, retrieve the


department number, the number of employees in
the department, and their average salary.
SELECT DNO, COUNT (*), AVG (SALARY)
FROM EMPLOYEE
GROUP BY DNO;
Grouping Attribute

Dr. Suleiman H. Mustafa Slide 5.3 - 54


GROUPING (contd.)

 In Q20, the EMPLOYEE tuples are divided into


groups-
 Each group having the same value for the
grouping attribute DNO
 The COUNT and AVG functions are applied to
each such group of tuples separately
 The SELECT-clause includes only the grouping
attribute and the functions to be applied on each
group of tuples
 A join condition can be used in conjunction with
grouping

Dr. Suleiman H. Mustafa Slide 5.3 - 55


GROUPING (contd.)

Query 21: For each project, retrieve the project number,


project name, and the number of employees who work on
that project.

SELECT PNUMBER, PNAME, COUNT (*)


FROM PROJECT, WORKS_ON
WHERE PNUMBER = PNO
GROUP BY PNUMBER, PNAME;

 In this case, the grouping and functions are applied after


the joining of the two relations

Dr. Suleiman H. Mustafa Slide 5.3 - 56


HAVING Clause

 Sometimes we want to retrieve the values of


these functions for only those groups that satisfy
certain conditions
 The HAVING-clause is used for specifying a
selection condition on groups (rather than on
individual tuples)

 Example

Dr. Suleiman H. Mustafa Slide 5.3 - 57


HAVING Clause

 Query 22: For each project on which more than two


employees work, retrieve the project number, project
name, and the number of employees who work on that
project.
Q22: SELECT PNUMBER, PNAME, COUNT(*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
HAVING COUNT (*) > 2;

Dr. Suleiman H. Mustafa Slide 5.3 - 58


Query 22

Result

Dr. Suleiman H. Mustafa Slide 5.3 - 59


Recap of SQL Queries

A query in SQL can consist of up to six clauses, but only the


first two, SELECT and FROM, are mandatory. The clauses
are specified in the following order:

SELECT <attribute list>


FROM <table list>
[WHERE <condition>]
[GROUP BY <grouping attribute(s)>]
[HAVING <group condition>]
[ORDER BY <attribute list>]

There are three SQL commands to modify the database:


INSERT, DELETE, and UPDATE
Dr. Suleiman H. Mustafa Slide 8- 60
Slide 5.3 - 60
END

Dr. Suleiman H. Mustafa Slide 5.3 - 61


Review Questions

Consider the following relations for a database that keeps track of student
enrollment in courses and the books adopted for each course:

R1: STUDENT (SSN, Name, Major, BDate)


R2: COURSE (CourseNo, CName, Dept)
R3: ENROLL (SSN, CourseNo, Quarter, Grade)
R4: BOOK_ADOPTION (CourseNo, Quarter, ISBN)
R5: TEXTBOOK (ISBN, Title, Author, Publisher)

1. Draw the ER diagram for these relations


2. Write the SQL statements to create these relations.
Dr. Suleiman H. Mustafa Slide 5.3 - 62

You might also like