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

Week7 Chapter 8 - moreSQLexamples

The document discusses advanced SQL concepts like joins, subqueries, and using WHERE, HAVING, GROUP BY clauses. It provides examples of SQL queries on a sample Persons table to demonstrate concepts like selecting columns, using DISTINCT, and inserting, updating, and deleting rows. The document is intended as a reference for an database systems course.

Uploaded by

yeolengkeong
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)
15 views

Week7 Chapter 8 - moreSQLexamples

The document discusses advanced SQL concepts like joins, subqueries, and using WHERE, HAVING, GROUP BY clauses. It provides examples of SQL queries on a sample Persons table to demonstrate concepts like selecting columns, using DISTINCT, and inserting, updating, and deleting rows. The document is intended as a reference for an database systems course.

Uploaded by

yeolengkeong
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/ 50

EE4791: Database Systems

Chapter 8 Advanced SQL & More Examples

Assoc Prof Chen Lihui

College of Engineering
School of Electrical and Electronic Engineering
Chapter 8: Adv. SQL & More SQL Examples 0
SQL multi-Table Queries
(Chapter 7/8 )

• Where clause & Having clause


• Create Table Tablename or Create View Viewname
• Select … From… Where … Group by… Having
• Insert Into Tablename Values (… ) InnerJoin : focuses on the
• Update Tablename SET col=v1 Where … commonality between two Ts
• Delete From Tablename Where … OuterJoin : finds and returns
• Drop Table Tablename matching data and some
dissimilar data from Ts
• ALTER TABLE Tablename
InnerJoin vs Natural J:
• JOINS : IJ: needs to specify j.column
o NaturalJoin ~ InnerJoin but …
o OuterJoin: LeftOuterJoin; RightOuterJoin; UnionJoin

• SubQueries : NonCorrelated vs Correlated


Chapter 8: Adv. SQL & More SQL Examples 1
SQL Database Table

Persons table
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

Chapter 8: Adv. SQL & More SQL Examples 2


SQL Queries
Persons
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

SELECT LastName
FROM Persons;

Result:

LastName
Hansen
Svendson
Pettersen

Chapter 8: Adv. SQL & More SQL Examples 3


SELECT LastName, FirstName
FROM Persons;

Query Result

LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari

Chapter 8: Adv. SQL & More SQL Examples 4


Select All Columns

To select all columns from the "Persons" table, use a *


symbol instead of column names, like this:
SELECT *
FROM Persons;

Query Results

LastName FirstName Address City


Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

Chapter 8: Adv. SQL & More SQL Examples 5


Semicolon after SQL Statements?

Semicolon is the standard way to separate each SQL statement in


database systems that allow more than one SQL statement to be
executed in the same call to the server.
Some SQL tutorials end each SQL statement with a semicolon. Is
this necessary? We are using MS Access and SQL Server 2000
and we do not have to put a semicolon after each SQL statement,
but some database programs force you to use it.

Chapter 8: Adv. SQL & More SQL Examples 6


DISTINCT
SELECT Company
FROM Orders;

Orders
Company
Sega
Company OrderNumber
W3Schools
Sega 3412
Trio
W3Schools 2312
W3Schools
Trio 4678
W3Schools 6798

Chapter 8: Adv. SQL & More SQL Examples 7


Note that "W3Schools" is listed twice in the result-set.
To show only DIFFERENT values from the column named
"Company" we use a SELECT DISTINCT statement like this:
SELECT DISTINCT Company
FROM Orders;
Orders
Company
Sega
Company OrderNumber
W3Schools
Sega 3412
Trio
W3Schools 2312
Trio 4678
W3Schools 6798

Chapter 8: Adv. SQL & More SQL Examples 8


Using the WHERE Clause
To select only the persons living in the city "Sandnes", we add a
WHERE clause to the SELECT statement:
SELECT *
FROM Persons
WHERE City='Sandnes' ;
Persons table
LastName FirstName Address City Year
Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980
Pettersen Kari Storgt 20 Stavanger 1960

Query Results
Address
LastName FirstName City Year
Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980
Chapter 8: Adv. SQL & More SQL Examples 9
Insert a New Row

Persons table
LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger

INSERT INTO Persons


VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes');

Persons table
LastName FirstName Address City

Pettersen Kari Storgt 20 Stavanger

Hetland Camilla Hagabakka 24 Sandnes


Chapter 8: Adv. SQL & More SQL Examples 10
Insert Data in Specified
Columns
LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes

INSERT INTO Persons (LastName, Address)


VALUES ('Rasmussen', 'Storgt 67');

LastName FirstName Address City


Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes
Rasmussen Storgt 67

Chapter 8: Adv. SQL & More SQL Examples 11


Update one Column in a Row
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67

We want to add a first name “Nina” to the person with a last


name of "Rasmussen":
UPDATE Person SET FirstName = 'Nina'
WHERE LastName = 'Rasmussen'

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Storgt 67
Chapter 8: Adv. SQL & More SQL Examples 12
Update several Columns in a Row

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Storgt 67

We want to change the address and add the name of the city:
UPDATE Person
SET Address = 'Stien 12', City = 'Stavanger'
WHERE LastName = 'Rasmussen' ;

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger
Chapter 8: Adv. SQL & More SQL Examples 13
Updates

Example: a specific date, all price 50% off?


Product (name, price, category, manufacturer)
Purchase(id, product, buyer, date)

UPDATE PRODUCT
SET price = price/2
WHERE Product.name IN
(SELECT Distinct product
FROM Purchase
WHERE Date =‘Oct. 25, 1999’);

Chapter 8: Adv. SQL & More SQL Examples 14


Delete a Row

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger

Everyone with last name “Rasmussen“ will be deleted:


DELETE FROM Person
WHERE LastName = 'Rasmussen‘;

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger

Chapter 8: Adv. SQL & More SQL Examples 15


Keys and Foreign Keys
Company
CName StockPrice Country
GizmoWorks 25 USA
Key
Canon 65 Japan
Hitachi 15 Japan

Product
PName Price Category Manufacturer
Foreign
Gizmo $19.99 Gadgets GizmoWorks
key
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi

Chapter 8: Adv. SQL & More SQL Examples 16


Syntax for Inner Join:
SELECT columnI, columnJ Joins SELECT columnI, columnJ
FROM TableA INNER JOIN TableB
FROM TableA, TableB ON TableA.columnX = TableB.columnY
WHERE TableA.columnX = TableB.columnY WHERE other conditions;
AND other conditions;

Product (pname, price, category, manufacturer)

Company (cname, stockPrice, country)

Find all products under $200 manufactured in Japan;


return their names and prices. Join
between Product
SELECT PName, Price and Company
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200;

Chapter 8: Adv. SQL & More SQL Examples 17


Joins

Product Company
PName Price Category Manufacturer Cname StockPrice Country
Gizmo $19.99 Gadgets GizmoWorks GizmoWorks 25 USA
Powergizmo $29.99 Gadgets GizmoWorks Canon 65 Japan
SingleTouch $149.99 Photography Canon Hitachi 15 Japan
MultiTouch $203.99 Household Hitachi

SELECT PName, Price


FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200; PName Price
SingleTouch $149.99

Chapter 8: Adv. SQL & More SQL Examples 18


Subqueries SELECT city
FROM Company, Product, Purchase
WHERE name= maker
Company(name, city) AND pname = product
Product(pname, maker) AND buyer = ‘Joe Blow’;

Purchase(id, product, buyer, price)


Return cities where one can find companies that manufacture
products bought by Joe Blow

SELECT city
FROM Company
WHERE name IN
(SELECT maker
FROM Purchase, Product
WHERE pname=product
AND buyer = ‘Joe Blow‘);
Chapter 8: Adv. SQL & More SQL Examples 19
Subqueries

Is it equivalent to this ?

SELECT city
FROM Company, Product, Purchase
WHERE name= maker
AND pname = product
AND buyer = ‘Joe Blow’;

Beware of duplicates !

Chapter 8: Adv. SQL & More SQL Examples 20


Removing Duplicates

SELECT DISTINCT city


FROM Company
WHERE name IN
(SELECT maker
FROM Purchase, Product
WHERE pname=product
AND buyer = ‘Joe Blow‘);

SELECT DISTINCT city Now


FROM Company, Product, Purchase they are
WHERE name= maker equivalent
AND pname = product
AND buyer = ‘Joe Blow’;
Chapter 8: Adv. SQL & More SQL Examples 21
Subqueries Operators : ALL, ANY, EXISTS

Product (name, price, category, maker)


Find products that are more expensive than all those produced
By “Gizmo-Works”: (every value in the set)
SELECT name
FROM Product
WHERE price > ALL (SELECT price
FROM Product
WHERE maker=‘Gizmo-Works’);

Find products that have a higher price than any product in the
“Électronics” category: (at least one value in the set)

SELECT *
FROM Product
WHERE price > ANY (SELECT price FROM Product
WHERE category = 'Electronics');
Chapter 8: Adv. SQL & More SQL Examples 22
Operators : ALL, ANY, EXISTS

Product (name, price, category, maker)

Find Product where the maker is ‘ABC Inc’.

The subquery inside EXISTS checks if there is at least one row in the Product table where the maker is 'ABC Inc.'. If
such a row exists, the condition is true, and the product details are included in the result set.

SELECT name, price, category, maker


FROM Product P
WHERE EXISTS
( SELECT 1
FROM Product
WHERE maker = 'ABC Inc.'
);

Or SELECT * FROM Product WHERE maker = 'ABC Inc.';

SELECT 1 = at least one row exists – but no need to retrieve the row

Chapter 8: Adv. SQL & More SQL Examples 23


Correlated Queries
Movie (title, year, director, length)
Find movies whose title appears more than once (in different years).
SELECT DISTINCT title correlation
FROM Movie AS x
WHERE year <> ANY
(SELECT year
FROM Movie
WHERE title = x.title);

Title Year Director Length(min)


Avata 2009 JamesCameron 162
Avata 2022 JamesCameron 192
Life Of Pi 2012 AngLee 127
Another Woman 1988 Woody Allen 77
The WHERE clause checks if the year is not equal to any year associated with the same movie title in the subquery.
Café Society
Chapter 2016
8: Adv. SQL & More SQL Examples Woody Allen 96 24
Without Correlated Queries

Movie (title, year, director, length)


Find movies whose title appears more than once (in different years).

SELECT title, count (*)


FROM Movie
GROUP BY title
HAVING count (*) > 1 ;

Title Year Director Length(min)


Avata 2009 JamesCameron 162
Avata 2022 JamesCameron 192
Life Of Pi 2012 AngLee 127
Another Woman 1988 Woody Allen 77

Café Society 2016 Woody Allen 96

Chapter 8: Adv. SQL & More SQL Examples 25


Correlated Query

Product ( pname, price, category, maker, year)


• Find products (and their manufacturers) that are more
expensive than all products made by the same
manufacturer before 1972.

SELECT DISTINCT pname, maker


FROM Product AS x
WHERE price > ALL (SELECT price
FROM Product
WHERE maker = x.maker AND year < 1972);

Chapter 8: Adv. SQL & More SQL Examples 26


Aggregation

SELECT avg(price) SELECT count(*)


FROM Product FROM Product
WHERE maker=“Toyota”; WHERE year > 1995;

SQL supports several aggregation operations:

sum, count, min, max, avg

Except count, all aggregations apply to a single attribute

Chapter 8: Adv. SQL & More SQL Examples 27


Aggregation: Count
COUNT (columnA): counts the number of non-NULL values in the columnA.
COUNT applies to duplicates, unless otherwise stated:

SELECT Count(category) same as Count(*)


FROM Product
WHERE year > 1995;

But if you want to get the total number of categories, you should do:

SELECT Count(DISTINCT category)


FROM Product
WHERE year > 1995;

Chapter 8: Adv. SQL & More SQL Examples 28


More Examples
Purchase(product, date, price, quantity)

Product Date Price Quantity


Bagel 10/21 1 20
Banana 10/3 0.5 10
Banana 10/10 1 10
Bagel 10/25 1.50 20
SELECT Sum(price * quantity)
FROM Purchase;

SELECT Sum(price * quantity)


FROM Purchase
WHERE product = ‘bagel’;
Chapter 8: Adv. SQL & More SQL Examples 29
Simple Aggregations

Purchase
Product Date Price Quantity
Bagel 10/21 1 20
Banana 10/3 0.5 10
Banana 10/10 1 10
Bagel 10/25 1.50 20

SELECT Sum(price * quantity)


50 (= 20+30)
FROM Purchase
WHERE product = ‘bagel’;

Chapter 8: Adv. SQL & More SQL Examples 30


Grouping and Aggregation

Purchase(product, date, price, quantity)

Find total sales after 10/1/2005 per product.

SELECT product, Sum(price*quantity) AS TotalSales


FROM Purchase
WHERE date > ‘10/1/2005’
GROUP BY product;

Let’s see what this means…

Chapter 8: Adv. SQL & More SQL Examples 31


Product Date Price Quantity Product TotalSales
Bagel 10/21 1 20
Bagel 10/25 1.50 20 Bagel 50
Banana 10/3 0.5 10
Banana 10/10 1 10
Banana 15

SELECT product, Sum(price*quantity) AS TotalSales


FROM Purchase
WHERE date > ‘10/1’
GROUP BY product;

Chapter 8: Adv. SQL & More SQL Examples 32


HAVING Clause

SELECT product, Sum(price * quantity)


FROM Purchase
WHERE date > ‘10/1’
GROUP BY product
HAVING Sum(price * quantity) > 30;

HAVING clause contains conditions on aggregates


(outputs Bagel only).

Chapter 8: Adv. SQL & More SQL Examples 33


Product ( pname, price, company)

Company( cname, city)

1. Find cities of companies with some product prices ³ 100


SELECT DISTINCT city
FROM Company
WHERE cname IN (SELECT DISTINCT company
FROM Product
WHERE price >= 100);

2. Find cities of all companies with all their products having prices < 100
SELECT DISTINCT city
FROM Company
WHERE cname NOT IN (SELECT DISTINCT company
FROM Product
WHERE price >= 100);

Chapter 8: Adv. SQL & More SQL Examples 34


Group-by
Author(login, name)

Wrote(login, url)
Mentions(url, word)

SELECT Author.login, name


FROM Author, Wrote, Mentions
WHERE Author.login=Wrote.login AND Wrote.url=Mentions.url
GROUP BY Author.login, name
HAVING count(distinct word) > 10000;

Chapter 8: Adv. SQL & More SQL Examples 35


Group-by

• Find all authors who wrote at least 10


documents (url):

SELECT Author.login, name


FROM Author, Wrote
WHERE Author.login=Wrote.login
GROUP BY Author.login, name
HAVING count(url) > 10;

No need for DISTINCT: automatically from GROUP BY

Chapter 8: Adv. SQL & More SQL Examples 36


One more SubQuery example
Product JOIN Store
Store(sid, sname) PID Pname Price StoreID StoreName

111 Bagel 1 S1 NTU


Product(pid, pname, price, sid) 112 Bagel 1.50 S1 NTU
113 Banana 0.5 S1 NTU
114 Banana 1 S2 JW
For each store, find its most 115 Bagel 2 S2 JW

expensive product
SELECT sname, x.pname
FROM Store, Product x
WHERE Store.sid = x.sid
AND x.price >=
ALL (SELECT y.price
FROM Product y
WHERE Store.sid = y.sid )
GROUP BY sname;

Chapter 8: Adv. SQL & More SQL Examples 37


NULLS in SQL

• Whenever we don’t have a value, we can put a NULL


• Can mean many things:
• Value does not exists
• Value exists but is unknown
• Value not applicable

• The schema specifies for each attribute if it can be null


(nullable attribute) or not

• How does SQL cope with tables that have NULLs ?

Chapter 8: Adv. SQL & More SQL Examples 38


Null Values

Unexpected behavior:

SELECT *
FROM Person
WHERE age < 25 OR age >= 25;

Some Persons are not included !

Chapter 8: Adv. SQL & More SQL Examples 39


Null Values

Can test for NULL explicitly:


• x IS NULL
• x IS NOT NULL

SELECT *
FROM Person
WHERE age < 25 OR age >= 25 OR age IS NULL ;

Now it includes all Persons


Chapter 8: Adv. SQL & More SQL Examples 40
InnerJoin:
focuses on the
commonality
between two tables
IJ: requires a specified
column to match on.
More precise control over
the join condition.

NJ: automatch columns


with the same name.
Returns
all matched rows only.
More convenient to use but
can be less precise.
Chapter 8: Adv. SQL & More SQL Examples Source: https://www.diffen.com/difference/Inner_Join_vs_Outer_Join 41
LeftOuterJoin
finds and returns
matching data and some
dissimilar data from T1

Chapter 8: Adv. SQL & More SQL Examples Source: https://www.diffen.com/difference/Inner_Join_vs_Outer_Join 42


RightOuterJoin
finds and returns
matching data and some
dissimilar data from T2

Product Price Quantity


Potatoes £3 45
Avocados $4 63
Kiwis $2 19
Onions $1 20
Melons $5 66
Broccoli NULL 27
Squash NULL 92
Chapter 8: Adv. SQL & More SQL Examples Source: https://www.diffen.com/difference/Inner_Join_vs_Outer_Join 43
FullJoin = UninJion
finds and returns all data
from T1 and T2
(not in mySQL )

NJ: only returns


matching rows.

FullJoin: returns all


rows
from both tables.

Chapter 8: Adv. SQL & More SQL Examples Source: https://www.diffen.com/difference/Inner_Join_vs_Outer_Join 44


Summary: Noncorrelated vs Correlated Subquery

What is subquery: a subquery is a query that is nested inside a SELECT,


INSERT, UPDATE, or DELETE statement, or inside another subquery

Subqueries can be categorized into two types:


noncorrelated vs correlated
What's the difference:
• Noncorrelated (simple) subquery obtains its
results independently of its containing (outer)
statement.
• Correlated subquery requires values from its
outer query in order to execute.

Chapter 8: Adv. SQL & More SQL Examples 45


Week 7 – Exercise 1
Exercise 1. Consider the database tables below as in Week6
exercise3. Write SQL commands for the additional requirements
stated below.

(a) List all courses (and course details) for which Professor John Tan is
qualified.
(b) Find the IDs of any lecturers who are qualified to teach ISM3113
but not qualified to teach ISM3114.
(c) Find out how many students are enrolled in course ISM3113 during
semester I-98.
(d) Find out which students were not enrolled in any courses during
semester I-98. Show their IDs and names.

Chapter 8: Adv. SQL & More SQL Examples 46


Ex3.

Chapter 8: Adv. SQL & More SQL Examples 47


Week 7 – Exercise 2
Exercise 2. Given a library database with the following relations:
Reader (ReaderID, ReaderName, Rating)
Book ( BookNO, BookName, Color)
Reserve(ReaderID, BookNo, Date)

Provide SQL statements to:


(a.1) Create a view RReader to include those readers (reader IDs and
names) who have a rating 2 or less and those readers who have
reserved more than two books with different ISBN numbers.
(a.2) Create a view RReader to include those readers (reader IDs and
names) who have a rating 2 or less and those readers who have
reserved two books with different ISBN numbers.
(b) Add a new column Author to the Book table.
(c) Record the following reservations in the database.
On 1-Mar-02, ReaderID R1 reserved books with ISBN numbers B5
and B6.
Chapter 8: Adv. SQL & More SQL Examples 48
Week 7 – Exercise 2 cont.
(d.1) List the IDs of the readers who have reserved a blue book.
(d.2) List the names of the readers who have reserved a blue book.
(e1) Find the number of blue books.
(e2) For each book, find the number of reservations for this book.
(e3) For each blue book, find the number of reservations for this book.
(f) Find the names and ratings of persons who have reserved two or
more books with different ISBN numbers on the same date.
(g1) Find the names of readers who have reserved a blue or a black
book.
(g2) Find the names of readers who have reserved both a blue and a
black book.
(h) Remove those reserve records older than 31-Jan-02.
(i) Update Author column to ‘****’ for those books

Chapter 8: Adv. SQL & More SQL Examples 49

You might also like