0% found this document useful (0 votes)
6 views70 pages

Session 1-2 SQL Revision 2024

The document outlines assessment measures for a course, detailing the weight of lab, mid-term, and final exams. It provides a comprehensive overview of SQL, including data definition and manipulation languages, commands, and examples of SQL queries. Additionally, it covers set operations, joins, and how to handle ambiguous attribute names in SQL queries.

Uploaded by

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

Session 1-2 SQL Revision 2024

The document outlines assessment measures for a course, detailing the weight of lab, mid-term, and final exams. It provides a comprehensive overview of SQL, including data definition and manipulation languages, commands, and examples of SQL queries. Additionally, it covers set operations, joins, and how to handle ambiguous attribute names in SQL queries.

Uploaded by

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

2024-2025

Assessment measures

Lab 20
Mid-term exam 35
Final exam 45

SQL Revision 2
Introduction to SQL
 SQL functions fit into two broad categories:
 Data definition language
 SQL includes commands to:
 Create database objects, such as tables, indexes, and views

 Define access rights to those database objects

 Data manipulation language


 Includes commands to insert, update, delete, and retrieve data
within database tables

SQL Revision 3
Data Definition Language (DDL)

▪ DDL is a descriptive language for defining the database


schema.

▪ Some of the main SQL-DDL commands are:

 CREATE TABLE

 ALTER TABLE

 DROP TABLE

SQL Revision 4
Data Definition Language (DDL)

SQL Revision 5
Data Manipulation Language (DML)
▪ DML is a language for retrieving and updating (insert, delete,
& modify) the data in the DB.

▪ The main SQL-DML commands are:


 SELECT

 INSERT INTO

 UPDATE

 DELETE FROM

SQL Revision 6
SQL Data Manipulation Commands

SQL Revision 7
SQL Data Manipulation Commands

SQL Revision 8
SQL SELECT Overview
SELECT
[DISTINCT | ALL] <column-list>
FROM <table-names>
[WHERE <condition>]
[ORDER BY <column-list>]
[GROUP BY <column-list>]
[HAVING <condition>]

Condition = | {expression {=|<|>|<=|>=|<>} expression


| expression BETWEEN expression AND expression
| expression {IS NULL |IS NOT NULL}
| expression {IN |NOT IN} listeConstantes
| expression {LIKE |NOT LIKE} patron}

AND is stronger than OR


Parentheses can be used to define the priority for resolving conditions

SQL Revision 11
Example

Customer (noCustomer, Lastname, Phone, SSN)


Items (NumItem, Description, UP, Quantity)
Order (NumOrder, Date, #Nocustomer, #SSN_Employee)
OrderDetail(#NumOrder, #NumItem, QTy)
Employee (SSN, name_Employee, Salary)
Delivery (NumDelivery, Date)
DeliveryDetails (#NumDeliv, #Numorder, #NumItem, Qty)

SQL Revision 12
Simple SQL queries
 View all Orders

SELECT *
FROM Order

SQL Revision 13
Simple SQL queries
 Show the NoCustomer and date of all Orders

SELECT nocustomer, date


FROM Order
nocustomer date
10 01/06/2000
20 02/06/2000
10 02/06/2000
10 05/07/2000
30 09/07/2000
20 09/07/2000
40 15/07/2000
40 15/07/2000
SQL Revision 14
Simple SQL queries
 Projection of a table without duplicates
 Show the NoCustomer and date of all Orders

SELECT Distinct nocustomer, date


FROM Order

nocustomer date
10 01/06/2000
20 02/06/2000
10 02/06/2000
10 05/07/2000
30 09/07/2000
20 09/07/2000
40 15/07/2000
SQL Revision 15
Simple SQL queries
 Show Items with number greater than 30 whose
price is less than 20 Euros

SELECT *
FROM Items
WHERE UP <20 and numitem > 30

NumItem description UP Quantity


60 Erable argenté 15.99 10
70 Herbe à puce 10.99 10
95 Génévrier 15.99 10

SQL Revision 16
Simple SQL queries
 Show Items whose number is greater than 30 and the
price is less than 20 Euros, or the number is less than 20
and the price is greater than 30.

SELECT *
FROM Items
WHERE ( UP <20 and numitem > 30 )
OR ( UP > 30 and numitem <20 )

SELECT *
FROM Items
WHERE UP <20 and numitem > 30
OR UP > 30 and numitem <20

SQL Revision 17
Simple SQL queries
 View Orders for the month of June of the year 2000

SELECT *
FROM Order
WHERE date between 01/06/2000 and 30/06/2000

SELECT *
FROM Order
WHERE date >= 01/06/2000 and date <= 30/06/2000

NumOrder Date NoCustomer SSN_Employee


1 01/06/2000 10 123
2 02/06/2000 20 456
3 02/06/2000 10 123

SQL Revision 18
Simple SQL queries
 View Orders for Customers number 10 or 40 or 80
SELECT *
FROM Order
WHERE nocustomer IN ( 10; 40 ; 80 )

SELECT *
FROM Order
WHERE nocustomer = 10 or nocustomer = 40 or nocustomer = 80

SQL Revision 19
Simple SQL queries
 Show Customers whose lastName starts with D

SELECT *
FROM Customer
WHERE lastname Like “D*”

Nocustomer Lastname Phone SSN

20 Dollard Cash (888)888- 456


8888
80 Dollard Cash (333)333- 123
3333

SQL Revision 20
Simple SQL queries
 Show Customers whose lastName contains the word
"Dol"

SELECT *
FROM Customer
WHERE lastname Like “*Dol*”

nocustomer Lastname Phone SSN


20 Dollard Cash (888)888-8888 456
80 Dollard Cash (333)333-3333 123

SQL Revision 21
Simple SQL queries
 Show Customers whose 3rd letter of the lastName is L
and last letter is a h

SELECT *
FROM Customer
WHERE lastname Like “??L*h”

nocustomer Lastname Phone SSN


20 Dollard Cash (888)888-8888 456
80 Dollard Cash (333)333-3333 123

SQL Revision 22
Simple SQL queries
 View the Customers whose phone has been entered
SELECT *
FROM Customer
WHERE phone is not null

nocustomer Lastname Phone SSN


10 Hugh Paycheck (999)999-9999 123
20 Dollard Cash (888)888-8888 456
30 Ye San Le Sou (777)777-7777 123
40 Le Comte Hasek (666)666-6666 456
50 Hafedh Lajoie (555)555-5555 789
60 Comtesse Hasek (666)666-6666 789
70 Coco McPoulet (444)444-4419 789
80 Dollard Cash (333)333-3333 123
SQL Revision 23
Simple SQL queries
 Show the noCustomer and date of Orders entered
after 05/07/2000
SELECT nocustomer, date
FROM Order
WHERE date > 05/07/2000

noCustomer date
30 09/07/2000
20 09/07/2000
40 15/07/2000
40 15/07/2000
24
Ordering of Query Results
 Use ORDER BY clause
 Keyword DESC to see result in a descending order of
values
 Keyword ASC to specify ascending order explicitly
 ORDER BY D.Dname DESC, E.Lname ASC

Ordering is ascending, unless you specify the DESC keyword.

SQL Revision 25
Simple SQL queries
 Display the name and phone of Customers whose
number is different from 30 in alphabetical order
SELECT lastname, phone
FROM Customer
WHERE nocustomer <> 30
ORDER BY lastname ASC, phone ASC

lastname phone lastname phone


Coco McPoulet (444)444-4419 Coco McPoulet (444)444-4419
Comtesse Hasek (666)666-6666 Comtesse Hasek (666)666-6666
Dollard Cash (888)888-8888 Dollard Cash (333)333-3333
Dollard Cash (333)333-3333 Dollard Cash (888)888-8888
Hafedh Lajoie (555)555-5555 Hafedh Lajoie (555)555-5555
Hugh Paycheck (999)999-9999 Hugh Paycheck (999)999-9999
Le Comte Hasek (666)666-6666 Le Comte Hasek (666)666-6666
SQL Revision 26
SELECT Example Using Alias
Alias is an alternative column or table name
SELECT lastname as name, phone
FROM Customer
WHERE nocustomer <> 30

SELECT cust.lastname as name, cust.phone


FROM Customer as cust
WHERE cust.nocustomer <> 30

SQL Revision 27
Simple SQL queries
 View the social security number and phone of all
Customers
SELECT lastname, phone, ssn as [ social security number]
FROM Customer

lastname phone social security number


Hugh Paycheck (999)999-9999 951
Dollard Cash (888)888-8888 753
Ye San Le Sou (777)777-7777 486
Le Comte Hasek (666)666-6666 197
Hafedh Lajoie (555)555-5555 123
Comtesse Hasek (666)666-6666 164
Coco McPoulet (444)444-4419 188
Dollard Cash (333)333-3333 133
SQL Revision 28
Alias
 Display the details of Customers who have placed
orders
SELECT customer.nocustomer, lastname, phone, numorder, date
FROM Customer, order
WHERE customer.nocustomer = order.nocustomer

SELECT cl.nocustomer, lastname, phone, numorder, date


FROM Customer as cl, order as ori
WHERE cl.nocustomer = ori.nocustomer

SELECT cl.*, ori.numorder, ori.date


FROM Customer as cl, order as ori
WHERE cl.nocustomer = ori.nocustomer

SQL Revision 29
SET OPERATIONS
 SQL has directly incorporated some set operations

 a union operation (UNION)


 intersection ( Intersect )
 Set difference ( Except )

SQL Revision 30
SET OPERATIONS
 View the SSN and the names of all customers and
employees
(SELECT ssn as numssn, lastname
FROM Customer )
Union all numssn lastname
(SELECT ssn, name 951 Hugh Paycheck
FROM employee ) 753 Dollard Cash
486 Ye San Le Sou
197 Le Comte Hasek
123 M. Barth
164 Comtesse Hasek
188 Coco McPoulet
133 Dollard Cash
456 M. Chbeir
789 Mme Kacimi
123 M. Barth
SQL Revision 31
SET OPERATIONS
 View the SSN and the names of all customers and
employees
(SELECT ssn as numssn, lastname
FROM Customer )
Union
numssn lastname
(SELECT ssn, name
951 Hugh Paycheck
FROM employee )
753 Dollard Cash
486 Ye San Le Sou
197 Le Comte Hasek
123 M. Barth
164 Comtesse Hasek
188 Coco McPoulet
133 Dollard Cash
456 M. Chbeir
789 Mme Kacimi

SQL Revision 32
SET OPERATIONS
 View the SSN and the names of all customers who
are also employed
(SELECT ssn as numssn, lastname
FROM Customer )
Intersect
(SELECT ssn, name
FROM employee )

Numssn lastname
123 M. Barth

SQL Revision 33
Ambiguous Attribute Names
 In SQL, we can use the same name for two (or more) attributes as
long as the attributes are in different relations

 A query that refers to two or more attributes with the same name
must qualify the attribute name with the relation name by
prefixing the relation name to the attribute name

Table_name . Column_name

 Example:
EMPLOYEE.NAME, DEPARTMENT.NAME

SQL Revision 34
JOINs
 JOINs can be used to
combine tables
 There are many types of
JOIN
 CROSS JOIN
 INNER JOIN
 NATURAL JOIN

SQL Revision 35
CROSS JOIN or CARTESIAN PRODUCT
If more than one relation is SELECT * FROM
specified in the FROM-clause and Student CROSS JOIN
there is no join condition, then the
CARTESIAN PRODUCT of tuples is Enrolment
selected
ID Name ID Code
123 John 123 DBS
Student 124 Mary 123 DBS
Enrolment 125 Mark 123 DBS
ID Name ID Code 126 Jane 123 DBS
123 John 124 PRG
123 John 123 DBS 124 Mary 124 PRG
124 Mary 124 PRG 125 Mark 124 PRG
125 Mark 124 DBS 126 Jane 124 PRG
126 Jane 126 PRG 123 John 124 DBS
124 Mary 124 DBS

SQL Revision 36
NATURAL JOIN
Student SELECT * FROM
ID Name Student NATURAL JOIN
123 John
Enrolment
124 Mary
125 Mark
126 Jane ID Name Code

Enrolment 123 John DBS


124 Mary PRG
ID Code 124 Mary DBS
123 DBS 126 Jane PRG
124 PRG
124 DBS
126 PRG

SQL Revision 37
NATURAL JOIN
 View the names of Customers who placed Orders
on 01/07/2002
SELECT lastname
FROM Customer, order
WHERE customer.nocustomer = order.nocustomer and date=01/07/2002

SELECT lastname
FROM Customer natural join order
WHERE date=01/07/2002

SELECT lastname
FROM Customer
WHERE nocustomer in
( select nocustomer
from order
Where date= 01/07/2002)
SQL Revision 38
Natural join of multiple tables
 View the names of Customers who ordered at least
one Printer item
SELECT lastname
FROM Customer, order, orderdetail, item
WHERE description=‘Printer’ and
customer.nocustomer = order.nocustomer and
order.numorder = orderdetail.numorder and
orderdetail.numitem = item.numitem

SQL Revision 39
Natural join of multiple tables
 View the names of Customers who ordered at least
one Printer item
SELECT lastname
FROM Customer
WHERE nocustomer in
select nocustomer
from order
where numorder in

select numorder
from orderdetail
where numitem in

select numitem
from item
where description = ‘Printer’
SQL Revision 40
INNER JOIN
 INNER JOINs specify a  Can also use
condition which the pairs SELECT * FROM
of rows satisfy A INNER JOIN B
USING
SELECT * FROM (col1, col2,…)
A INNER JOIN B  Chooses rows where the
ON <condition> given columns are equal

SQL Revision 41
INNER JOIN
Student SELECT * FROM
ID Name Student INNER JOIN
123 John
Enrolment USING (ID)
124 Mary
125 Mark ID Name ID Code
126 Jane 123 John 123 DBS
Enrolment 124 Mary 124 PRG
124 Mary 124 DBS
ID Code 126 Jane 126 PRG
123 DBS
124 PRG
124 DBS
126 PRG

SQL Revision 42
INNER JOIN
Buyer SELECT * FROM
Name Budget Buyer INNER JOIN
Property ON
Smith 100,000
Jones 150,000 Price <= Budget
Green 80,000

Property Name Budget Address Price

Address Price Smith 100,000 15 High St 85,000


Jones 150,000 15 High St 85,000
15 High St 85,000 Jones 150,000 12 Queen St 125,000
12 Queen St 125,000
87 Oak Row 175,000

SQL Revision 43
INNER JOIN
SELECT * FROM SELECT * FROM
A INNER JOIN B A INNER JOIN B
ON <condition> USING(col1, col2,...)
is the same as is the same as
SELECT * FROM A, B SELECT * FROM A, B
WHERE <condition> WHERE A.col1 = B.col1
AND A.col2 = B.col2
AND ...

SQL Revision 44
Auto-Join
 Show Customers who have the same phone
number

SELECT customer.nocustomer, customer.lastname, cust2.nocustomer,


cust2.lastname
FROM Customer , customer cust2
WHERE customer.phone = cust2.phone and
customer.nocustomer <> cust2.nocustomer

SELECT customer.nocustomer, customer.lastname, cust2.nocustomer,


cust2.lastname
FROM Customer join customer as cust2
on customer.phone = cust2.phone

SQL Revision 45
General expressions on columns
 Display the list of items with the current unit price and the
taxed price (increased by 15%)

SELECT numitem, UP, UP*1.15 as TaxedPrice


FROM items
numitem UP TaxedPrice
10 10.99 12.64
20 12.99 14.94
40 25.99 29.89
50 22.99 26.44
60 15.99 18.39
70 10.99 12.64
80 26.99 31.04
81 25.99 29.89
90 25.99 29.89
95 15.99 18.39

SQL Revision 46
General expressions on columns
 Show the details of each item ordered including the total
price before and after the 15% tax

SELECT od.numitem, Quantity, UP, UP*Quantity as total,


UP*Quantity*1.15 as TotalPlusTax
FROM OrderDetail od, items as I
WHERE od.numitem = I.numitem

SQL Revision 47
General expressions on columns
 Show Items with 15% Increased Unit price still less than
16
SELECT numitem , UP
FROM Item
WHERE UP*1.15 < 16

SQL Revision 48
Functions
 In SQL, you can use several types of functions
 Dependent functions of the DBMS

 Generic functions
 Arithmetic functions
 Aggregate functions

SQL Revision 49
Dependent functions of the DBMS
 View Orders of today

SELECT *
FROM Order
Where date = sysdate()

SQL Revision 50
Arithmetic and Aggregate Functions
 ARITHMETIC FUNCTIONS
 +, *, /, -

 Aggregate functions
 COUNT: The number of rows
 SUM: The sum of the entries in a column
 AVG: The average entry in a column
 MIN, MAX: The minimum and maximum entries in a column

SQL Revision 51
Aggregate functions
 COUNT(*)
 COUNT(*) counts all rows in a table or result in a
selection (without eliminating duplicates)

 COUNT(DISTINCT attribute) counts the number of


attributes without duplicates
 COUNT(DISTINCT *) is invalid

SQL Revision 52
Aggregate functions
 Displays the average salary of employees

SELECT avg(salary)
FROM Employee

 View employees who earn more than the average


salary
SELECT name
FROM Employee
Where salary >= (select avg(salary) from employee)

SQL Revision 53
Aggregate functions
 View the number of employees who have a fixed salary

SELECT count(*)
FROM Employee
Where salary is not null

 View the number of employees who do not earn the


same salary
SELECT count( Distinct salary)
FROM Employee

SQL Revision 54
Partition of a table with GROUP BY
 Display the number of Orders of each Customer (who has
placed at least one Order)
SELECT nocustomer, count(*) as nborders
FROM Order
Group by nocustomer

Table Order
numorder date nocustomer
1 01/06/2000 10
3 02/06/2000 10 nocustomer nborders
4 05/07/2000 10 10 3
2 02/06/2000 20
6 09/07/2000 20
20 2
5 09/07/2000 30 30 1
7 15/07/2000 40 40 2
8 15/07/2000 40
SQL Revision 55
Partition of a table with GROUP BY
For each of the delivery details (for which at least one has been
delivered), display the order number and item number, the total
quantity delivered, and the number of deliveries made.

SELECT numorder, numitem, sum(Qty) as totaldeliv , count(*) as


nbdeliveries
FROM DeliveryDetails
Group by numorder, numitem

Table Deliverydetails
Numdeliv Numorder Numitem Qty
Numorder Numitem Totaldeliv nbdeliveries
100 1 10 7
101 1 10 3 1 10 10 2
100 1 70 5 1 70 5 1
102 2 40 2 1 90 1 1
102 2 95 1 2 40 2 1
100 3 20 1 2 95 1 1
103 1 90 1 3 20 1 1
104 4 40 1 4 40 1 1
105 5 70 2 5 70 2 1
SQL Revision 56
Clause HAVING
 View the number of Orders for each Customer who has
placed two or more Orders
SELECT nocustomer, count(*) as nborders
FROM Order
Group by nocustomer
Having count(*) >=2

SQL Revision 57
Clause HAVING
 Display the number of Orders from each Customer placed
after 02/06/2000
SELECT nocustomer, count(*) as nborders
FROM Order
Where date > 02/06/2000
Group by nocustomer

SQL Revision 58
Clause HAVING
 Example
 View the number of Orders of each Customer who has placed two
or more Orders after 02/06/2000
SELECT nocustomer, count(*) as nborders
FROM Order
Where date > 02/06/2000
Group by nocustomer
Having count(*) >=2

SQL Revision 59
Nested SELECT
 View all information about Customers who have placed
at least one Order
SELECT nocustomer, lastname, phone
FROM customer
Where nocustomer in
(select nocustomer
from Order)

SELECT customer.nocustomer, lastname, phone


FROM Customer, order
WHERE customer.nocustomer = order.nocustomer

SQL Revision 60
Nested SELECT
 View Gemayel's Orders

SELECT *
FROM Order
Where nocustomer =
(select nocustomer
from customer
where lastname = ‘Gemayel’ )

SELECT customer.nocustomer, lastname, phone


FROM Customer, order
WHERE customer.nocustomer = order.nocustomer and lastname =
‘Gemayel’

SQL Revision 61
ALL condition
 View employees who earn more than any other
supplier (the highest)

SELECT *
FROM Employee
Where salary >= ALL
(select salary
from supplier)

SQL Revision 62
ANY Condition (SOME)
 View employees who earn more than one salary of a
supplier whose name begins with c

SELECT *
FROM Employee
Where salary >= ANY
(select salary
from supplier
where name like “c*”)

SQL Revision 63
EXISTS FUNCTION
 Show Customers who are not employees at the same
time
SELECT *
FROM Customer e
Where not EXISTS
(select *
from employee
where ssn =e.ssn)

SELECT *
FROM Customer
Where ssn not in
(select ssn
from employee
)

SQL Revision 64
UNIQUE
 View customers with the same name

SELECT lastname
FROM Customer e
Where not unique
(select lastname
from customer
where nocustomer=e.nocustomer)

SELECT lastname
FROM Customer , customer cust2
WHERE customer.lastname = cust2.lastname and
customer.nocustomer <> cust2.nocustomer

SQL Revision 65
VIEW
A view is a partial or particular view of data from one or
more tables in the database.

The definition of a view is given by a SELECT which


indicates the data of the base which will be seen

Only the view definition is saved in the database, not the


view data.

SQL Revision 66
Command to create and delete a view

CREATE VIEW givenname (col1, col2...) AS


SELECT ...

 To delete a view, just run the following command

DROP VIEW givenname


SQL Revision 67
Example
 Creating a view of the Article table
CREATE VIEW article_v AS (SELECT noArticle, description, Quantity
FROM article )

Article Article_v
noArticle description price Quantity noArticle description Quantity
60 Erable argenté 15.99 10 60 Erable argenté 10
70 Herbe à puce 10.99 10 70 Herbe à puce 10
95 Génévrier 15.99 10 95 Génévrier 10

SQL Revision 68
Example
 Creating a view of the Article table
CREATE VIEW article_v (v1, v2) AS (SELECT noArticle, description
FROM article )

Article Article_v
noArticle description price Quantity v1 v2
60 Erable argenté 15.99 10 60 Erable argenté
70 Herbe à puce 10.99 10 70 Herbe à puce
95 Génévrier 15.99 10 95 Génévrier

SQL Revision 69
Example (limited rights)
 CREATE VIEW article_v AS (SELECT noArticle,
description, Quantity FROM article )

 GRANT select ON article_v TO user

SQL Revision 70
Update a view
 Under certain conditions, it is possible to perform DELETE,
INSERT and UPDATE through views.

 The following conditions must be met:


 To perform a DELETE, the select that defines the view must
not have a join, group by, distinct, group function;
 For an UPDATE, in addition to the previous conditions, the
modified columns must be actual columns of the underlying
table;
 For an INSERT, in addition to the previous conditions, any
"not null" column of the underlying table must be present in
the view.

SQL Revision 71
Update a view
 A view can create data that it can not visualize

CREATE TABLE t1 (a INT);


CREATE VIEW v1 AS SELECT * FROM t1 WHERE a < 2

Insert into v1 values (3)

 If you want to avoid this, you must add WITH CHECK


OPTION in the creation order of the view after the
query defining the view

CREATE VIEW v1 AS SELECT * FROM t1 WHERE a < 2


WITH CHECK OPTION
SQL Revision 72

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy