6_SQL_Post_1
6_SQL_Post_1
Hazra Imran
Slides are adapted from Jukic material with necessary modification
(Acknowledging work on these slides by CPSC 304 instructors over the years)
SQL 1
Reminders and Important Dates
Mar 3, 2020
Upcoming deadlines
1. Learning goals
2. Basic SQL
• Select
• From
• Where
• Distinct
• Group By
3. Practice Exercise
4. Revisit learning objectives
4
Databases: the continuing saga
SQL 5
Learning Goals
Given the schemas of a relation you will be able to:
2. Show that there are alternative ways of coding SQL queries to yield the
same result. Determine whether or not two SQL queries are equivalent.
4. Explain the purpose of NULL values and justify their use. Also describe
the difficulties added by having nulls.
SQL 7
You can write your own queries
• Your Oracle (DBMS) accounts on the department servers are ready
• Your login is "ora_[CWL ID]" Your password is "a[your student id]“. To
login:
• Log onto remote.students.cs.ubc.ca.
• Start sqlplus (the interface to Oracle by typing "sqlplus [Oracle
login]@stu" (”stu" is the specific database to access)
• Note: if you run into problems getting things to work, make sure that:
You're logging onto remote.students.cs.ubc.ca
• Login to the undergraduate machine using your regular user
name and password
• You have the "@stu" at the end of logging in (that says what
database to access)
• you don't forget to prepend your student ID with an "a" for your
sql login
SQL 8
You can write your own queries
• https://apex.oracle.com/en/ (online and freely available)
• XAMPP (free)
SQL 9
Introduction
SQL 10
SQL Command
➢ CREATE
Data Definition Language ➢ ALTER
(DDL) ➢ DROP
➢ INSERT INTO
Data Manipulation ➢ UPDATE
SQL command ➢
Language (DML) DELETE
➢ SELECT
SQL 11
Domain Types in SQL Reference Sheet
12
SQL 12
Date/Time Types in SQL Reference Sheet
13
SQL 13
Specifying Attribute Constraints
• CHECK clause
• Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber <
21);
SQL 14
Basic Constraints in SQL
SQL 15
Specifying Key and Referential Integrity
Constraints
• PRIMARY KEY clause
- Specifies one or more attributes that make up the primary key of a relation
- Dnumber INT PRIMARY KEY;
• UNIQUE clause
- Specifies alternate (secondary) keys (called CANDIDATE keys in the relational
model).
- Dname VARCHAR(15) UNIQUE;
SQL 16
Basic SQL
SQL 17
CREATE TABLE
• CREATE TABLE
- Used for creating and connecting relational tables
SQL 18
TABLE vs VIEW
Table 1
View
Create
VIEW
Table 2 View created based on Table 1 and Table 2
- Query stored in the database
- It is computed dynamically
Main purpose:
• Simplify the complex SQL queries.
• Provide restriction to users from accessing
sensitive data.
SQL 19
CREATE TABLE
SQL 20
Relational schema: ZAGI Retail Company Sales Department Database
CREATE TABLE statements for ZAGI Retail Company Sales
Department Database
SQL 24
INSERT INTO
- Used to populate the created relations with data
SQL 25
Data records: ZAGI Retail Company Sales Department
Database
INSERT INTO statements for ZAGI Retail Company Sales Department Database
- Basic form:
SELECT <columns>
FROM <table>
Query 1 result:
SQL 30
SELECT
Query 1a result:
SQL 31
SELECT
Query 2 text: Retrieve the entire contents of the relation PRODUCT and
show the columns in the following order: ProductName,
ProductID, VendorID, CategoryID, ProductPrice
Query 2 result:
SQL 32
SELECT
Query 3 text: For the relation PRODUCT, show the columns ProductID and
ProductPrice
Query 3 result:
SQL 33
SELECT
Query 3 text: For the relation PRODUCT, show the columns ProductID and
ProductPrice
Query 3 result:
SQL 34
SELECT
- In addition to displaying columns, the SELECT clause can be
used to display derived attributes (calculated columns)
represented as expressions
SQL 35
SELECT
Query 4 text: For the relation PRODUCT, show the columns ProductID and
ProductPrice and a column showing ProductPrice increased by
10%
Query 4 result:
SQL 36
Clicker Question
• Given the table scores:
what is result of
SELECT Score1, Score2
Team1 Team2 Score1 Score2
FROM Scores;
Dragons Tigers 5 3
Carp Swallows 4 6
• Which of the
Bay Stars Giants 2 1
following rows is
Marines Hawks 5 3
in the answer?
Ham Fighters Buffaloes 1 6
A. (1,2)
Lions Golden 8 12
B. (5,3) Eagles
C. (8,6)
D. All are in the answer
E. None are in the answer
SQL 37
Clicker Question: SQL projection
• Given the table scores:
what is result of
SELECT Score1,Score2
FROM Scores; Team1 Team2 Score1 Score2
Dragons Tigers 5 3
• Which of the Carp Swallows 4 6
Bay Stars Giants 2 1
following rows is Marines Hawks 5 3
in the answer? Ham Fighters Buffaloes 1 6
Lions Golden 8 12
A. (1,2) Eagles
B. (5,3) Correct
C. (8,6)
D. All are in the answer
E. None are in the answer
SQL 38
SELECT
- The SELECT FROM statement can contain other optional
keywords, such as WHERE, GROUP BY, HAVING, and
ORDER BY, appearing in this order:
SQL 39
WHERE
Query 5 result:
SQL 41
Clicker Question: Selection
• Consider Scores1(Team, Opponent, RunsFor, RunsAgainst) and
query
SELECT * Team Opponent RunsFo RunsAgainst
FROM Scores1 r
Dragons Tigers 5 3
WHERE RunsFor > 5 ;
Carp Swallows 4 6
Bay Stars Giants 2 1
• Which tuple is Marines Hawks 5 3
in the result? Ham Fighters Buffaloes 1 6
SQL 42
Clicker Question: Selection
SELECT *
FROM Scores1
WHERE RunsFor > 5 ;
SQL 43
Clicker Question: Selection
• Consider Scores1(Team, Opponent, RunsFor, RunsAgainst) and
query
SELECT * Team Opponent RunsFor RunsAgainst
FROM Scores1
Dragons Tigers 5 3
WHERE RunsFor > 5 ;
Carp Swallows 4 6
Bay Stars Giants 2 1
• Which tuple is Marines Hawks 5 3
in the result? Ham Fighters Buffaloes 1 6
A. (Swallows, Carp,6, 4) answer A Lions Golden Eagles 8 12
SQL 44
So how does a typical SQL query relate to relational
algebra then?
SQL:
SELECT A1, A2, ..., An
FROM r1, r2, ..., rm
WHERE P
Is approximately equal to
Relational algebra
πA1, A2, ..., An(σP (r1 x r2 x ... x rm))
Difference? Duplicates.
Remove them? Distinct
45
SQL 45
DISTINCT
SQL 46
DISTINCT
Query 6 text: Retrieve the VendorID value for each record in the relation
PRODUCT
Query 6 result:
SQL 47
DISTINCT
Query 7 result:
SQL 48
Clicker question:
distinct
SQL 49
Clicker question: distinct
SELECT DISTINCT Team, RunsFor
FROM Scores4
TEAM RUNSFOR
Bay Stars 2
Marines 5
Swallows 6
Hawks 3
Carp 4
Giants 1
Golden Eagles 12
Tigers 3
Buffaloes 6
Ham Fighters 1
Lions 8
Dragons 5
SQL 50
Clicker question: distinct
• Consider the relation: Team Opponent Runs Runs
Scores4(Team, Opponent, For Against
Dragons Tigers 5 3
RunsFor, RunsAgainst) and
Carp Swallows 4 6
the query: Bay Stars Giants 2 1
SELECT DISTINCT Team, Marines Hawks 5 3
RunsFor Ham Buffaloes 1 6
Fighters
FROM Scores4 Lions Golden 8 12
Eagles
Tigers Dragons 3 5
• Which is true: Swallows Carp 6 4
A. 1 appears once Giants Bay Stars 1 2
B. 5 appears twice Correct Hawks Marines 3 5
Buffaloes Ham Fighters 6 1
C. 6 appears 4 times Golden Lions 12 8
D. All are true Eagles
- Used to sort the results of the query by one or more columns (or
expressions)
- By default it is ascending
SQL 52
ORDER BY
Query 8 text: Retrieve the product ID, product name, category ID, and
product price for each product in the FW product category,
sorted by product price
Query 8 result:
SQL 53
ORDER BY
Query 9 text: Retrieve the product ID, product name, category ID, and
product price for each product in the FW product category,
sorted by product price in descending order
Query 9 result:
SQL 54
Clicker question: Order By
C. (5,5,6) Right
SQL 57
AGGREGATE FUNCTIONS
Query 10 text: Retrieve the average price of all products
Query 10 result:
SQL 58
AGGREGATE FUNCTIONS
Query 11 result:
SQL 59
Aggregate Operators
These functions operate on the multiset of values of a column of
a relation, and return a value
AVG: average value
MIN: minimum value
MAX: maximum value
SUM: sum of values
COUNT: number of values
SQL 61
GROUP BY
SELECT AVG(productprice)
For i = ‘PG’, ‘MK’… FROM product
WHERE vendorid= ‘PG’;
◼ Problem:
We don’t know how many Vendor ID exist, not to mention this is not
good practice
SQL 62
GROUP BY
Query 12 text: For each vendor, retrieve the vendor ID, number of products
supplied by the vendor, and average price of the products
supplied by the vendor
Query 12 result:
SQL 63
GROUP BY
• All columns in the SELECT list that are not in aggregate
functions must be in the GROUP BY clause.
Query 13.
SELECT vendorid, COUNT(*), AVG(productprice)
FROM product
GROUP BY vendorid;
SQL 64
GROUP BY
4 121.2
2 95
SQL 65
GROUP BY - on Multiple Columns
MK CP 2 200
PG CP 1 100
MK FW 2 42.5
PG FW 1 90
SQL 66
Illegal Query
• Any column or expression in the SELECT list that is not
an aggregate function must be in the GROUP BY clause:
SQL 67
Illegal Query
• We cannot use the WHERE clause to restrict groups.
• We have to use the HAVING clause to restrict groups.
• You cannot use aggregate functions in the WHERE clause.
SQL 68
Practice Exercise – Try!
Query 1. Retrieve the product ID, product name, vendor ID, categoryid, and product
price for each product in the FW category whose price is equal to or below $200
Query 2. Retrieve the number of products, average product price, lowest product
price, and highest product price in the CP product category.
Query 3. Display the ProductID, ProductName, and ProductPrice for products in the
category whose CategoryID value is ‘CP’. Sort the results by ProductID.
Ques 4. Display the TID and the total number of items (of all products) sold within all
sales transactions.
Practice Exercise – Try!
Query 1. Retrieve the product ID, product name, vendor ID, categoryid, and product
price for each product in the FW category whose price is equal to or below $200
SELECT ProductID, ProductName, VendorID, CategoryID, ProductPrice
FROM PRODUCT
WHERE CategoryID = 'FW' AND ProductPrice <= 200;
Query 2. Retrieve the number of products, average product price, lowest product
price, and highest product price in the CP product category.
SELECT COUNT(*), AVG(ProductPrice), MIN(ProductPrice), MAX(ProductPrice)
FROM PRODUCT
WHERE CategoryID = 'CP’;
Ques 3 . Display the ProductID, ProductName, and ProductPrice for products in the
category whose CategoryID value is ‘CP’. Sort the results by ProductID.
SELECT ProductID, ProductName, ProductPrice
FROM PRODUCT
WHERE CategoryID = 'CP'
ORDER BY ProductID;
Practice Exercise – Try!
Ques 4. Display the TID and the total number of items (of all products) sold within all
sales transactions.
2. Show that there are alternative ways of coding SQL queries to yield the
same result. Determine whether or not two SQL queries are equivalent.
4. Explain the purpose of NULL values and justify their use. Also describe
the difficulties added by having nulls.