Lecture8: Relational Algebra, Data Manipulation in
SQL , Simple SQL queries
Ref. Chapter4&5
1
Coll
ege
of
Com
pute
r an
d I
nfo
rmat
ion S
cien
ces
-In
form
atio
n S
yst
ems
Dep
t.
Prepared by L. Nouf Almujally & Aisha AlArfaj
IS220 : Dat abase Fundament a l s
The Process of Database Design
Real World Domain
Conceptual model (ERD)
Relational Data Model
Create schema
(DDL)
Load Data
(DML)
Lec
ture
8
2
Tables in the Examples
Customer(custNo, custName, custSt, custCity, age)
Product(prodNo, prodName, prodDes, price)
Orders(ordNo, ordDate, custNo, prodNo, quantity)
Where
custName, custSt, custCity, prodName, prodDes are strings
ordDate is date
Others are numbers
Lec
ture
8
3
Sample Data in Customer Table
custNo custName custSt custCity age
1 C1 Olaya St Jeddah 20
2 C2 Mains St Riyadh 30
3 C3 Mains Rd Riyadh 25
4 C4 Mains Rd Dammam
5 C5 Mains Rd Riyadh
Lec
ture
8
4
Sample Data in Product Table
prodNo prodName prodDes price
100 P0 Food 100
101 P1 healthy Food 100
102 P2 200
103 P3 self_raising
flour,80%wheat
300
104 P4 network 80x 300
Lec
ture
8
5
Sample Data in Orders Table
ordNo ordDate custNo prodNo quantity
1 01-jan-2003 1 100 2
2 02-jan-2003 1 101 1
3 01-jan-2003 2 102 1
4 01-jan-2003 3 100 2
5 03-jan-2003 1 101 1
6 06-mar-2003 2 100 10
Lec
ture
8
6
Relational Algebra
• Operations on relations (sets of records) to produce a relation as result.
• The output from one operation can become the input to another operation (nested relational algebra)
• Eight fundamental operations in relational algebra:
Unary operations: work on one relation
Selection
Projection
Binary operations: work on pairs of relations
Cartesian product Join
Union Intersection
Set difference Division
Lec
ture
8
8
9
Algebra Operators
abc
xy
aabbcc
xyxyxy
Cartesian Product
a1a2a3
b1b2b3
b1b2b3
c1c2c3
a1a2a3
b1b2b3
c1c2c3
Join
xy
aaaabc
xyzxy
Divide
Selection Project
Union Intersection Difference
Lec
ture
8
Selection Operation
• Select[cond](R)- selects tuples out of relation R that meet specified condition cond to result in a new relation.
• Denoted by ⱷ (R)
Where R is the relation and ⱷ is the logical condition
• Example:
List all products which are priced more than 100.
price > 100 (product)
Lec
ture
8
10
prodNo prodName prodDes price
102 P2 200
103 P3 self_raising
flour,80%wheat
300
104 P4 network 80x 300
Examples
Example 1: Find all orders of product 100 before 02/01/03.
(prodNo = 100) AND (ordDate <'02-jan-2003‘ ) (orders)
Example 2: Find all products priced less than 200 or greater than 300.
(price < 200 ) OR (price >300) (product)
ordNo ordDate custNo prodNo quantity
1 01-jan-2003 1 100 2
4 01-jan-2003 3 100 2
prodNo prodName prodDes price
100 P0 Food 100
101 P1 healthy food 100
Lec
ture
8
11
Projection Operation
• Project[attr-list](R) - selects columns specified in the attributes list out of R to result in a new relation.
• Denoted by < attribute list> (R)
• Example:
List prodNo and price of all products.
prodNo, price(product)
Lec
ture
8
12
prodNo price
100 100
101 100
102 200
103 300
104 300
Examples
Example 1: List all products (by prodNo and price) which are priced more than 100.
prodNo, price( price > 100 (product))
Example 2: What is the name of the customer whose custNo is 1?
custName ( custNo=1 (customer))
prodNo price
102 200
103 300
104 300
custName
C1
Lec
ture
8
13
Data Manipulation Language (DML)
• DML is used to retrieve and modify data in the tables
• Four basic statements
• Insert Into
• Select
• Update
• delete From
Lec
ture
8
16
Insert Statement
• The INSERT statement adds one or more new rows of data to a database table.
• Syntax
• Note:• value list must correspond to column list
• If column list is omitted, then a value for every attribute is required
• The data types must be correct
Lec
ture
8
17
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
INSERT INTO table_name
VALUES (value1,value2,value3,...);
• Example: for table Customer,
Insert into Customer(custNo, custName) values (6, 'John');
Output: 1 row inserted
Insert into Customer values (7, 'David ', 'St1','City1', 20);
Output: 1 row inserted
Insert Statement Example
Lec
ture
8
18
Simple SELECT Queries
• The SELECT command is used for submitting queries to the DBMS.
• Syntax
Lec
ture
8
19
SELECT expression_listFROM table_list
[WHERE condition][ORDER BY expression_list];
Simple SELECT Queries
Expression in SELECT statement :
Condition in WHERE statement:
• an expression that can be evaluated to TRUE or FALSE.
• Only rows satisfying the condition will be chosen.
• Condition can be simple comparison or compound expression
Expression Example
column names SELECT prodNo
arithmetic operators for numbers: +, -, *, / SELECT Price+10
Constant SELECT 'The first name is', fnameFROM customer
Lec
ture
8
20
Conditions in the WHERE Clause
WHERE clause consists of five basic search conditions:
• Comparison: Compare the value of one expression to the value of
another expression (= , <, >, <=, >=, <>).
• Range: Test whether the value of an expression falls within a specified
range of values (BETWEEN/ NOT BETWEEN).
• Set membership: Test whether the value of an expression equals one of
a set of values (IN/ NOT IN).
• Pattern match: Test whether a string matches a specified pattern (LIKE/
NOT LIKE).
• NULL: Test whether a column has null value (IS NULL/ IS NOT NULL).
Note: Basic comparisons can be compounded by AND, OR, NOT
• Eg, prodNo=100 and ordDate='01-jan-2003'
21
Lec
ture
8
Simple Queries : Comparison search condition
Comparison operators: = , < , > , <= , >= , <>
Example 1: List all products (by prodNo and price) which are priced more than 100.
Select prodNo, priceFrom Product
Where price >100;
Example 2: What is the name of the customer whose custNo is 1?
Select custNameFrom customer
Where custNo=1;
prodNo price
102 200
103 300
104 300
custName
C1
Lec
ture
8
22
Listing All Data in a Table
• If WHERE clause is omitted, all rows will be listed.
Example: List all data in the customer table
SELECT custNo, custName, custSt, custCity, age
FROM customer;
OR (use * for all columns)
SELECT * FROM CUSTOMER;
custNo custName custSt custCity age
1 C1 Olaya St Jeddah 20
2 C2 Mains St Riyadh 30
3 C3 Mains Rd
Riyadh 25
4 C4 Mains Rd
Dammam
5 C5 Mains Rd
Riyadh
Lec
ture
8
23
Simple Queries : Compound comparison search condition
• Compound comparison operators: AND , OR , NOT , ( )
• Order of evaluation:• Expression is evaluated left to right
• Between brackets
• NOT
• AND
• OR
Lec
ture
8
24
Examples
Example 1: Find all orders of product 100 before 02/01/03.SELECT *
FROM ordersWHERE prodNo = 100 AND ordDate <'02-jan-2003';
Example 2: Find all products priced less than 200 or greater than 300
SELECT * FROM product
WHERE price < 200 OR price >300;
ordNo ordDate custNo prodNo quantity
1 01-jan-2003 1 100 2
4 01-jan-2003 3 100 2
prodNo prodName prodDes price
100 P0 Food 100
101 P1 healthy food 100
Lec
ture
8
25
More Examples
Example: Find the customer with name C1 and live in Riyadh or Jeddah
SELECT *
FROM customers
WHERE custName ='C1‘ AND (custCity='Jeddah' OR custCity='Riyadh');
custNo custName custSt custCity age
1 C1 Olaya St Jeddah 20
Lec
ture
8
26
Simple Queries : BETWEEN / NOT BETWEEN
• The BETWEEN operator is used to select values within a range.
• The NOT BETWEEN checks if a value is outside a range.
• Syntax:
Lec
ture
8
27
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN |NOT BETWEEN
value1 AND value2;
BETWEEN Example
Example: List products priced between 200 and 300.
SELECT *
FROM product
WHERE price >=200 and price <=300;
or equivalently
SELECT *
FROM product
WHERE price between 200 and 300;
prodNo prodName prodDes price
102 P2 200
103 P3 self_raisingflour,80%wheat
300
104 P4 network 80x 300
Lec
ture
8
28
Simple Queries : IN / NOT IN
• IN tests whether a data value matches one of a list values.
• NOT IN checks for data values that do not lie in a specific list of values
• Syntax
Lec
ture
8
29
SELECT column_name(s)
FROM table_name
WHERE column_name IN| NOT IN (value1,value2,...);
IN Example
Example: List all customers living in Riyadh, or Dammam, or Jeddah.
SELECT *
FROM Customer
WHERE custCity = 'Jeddah' OR custCity = 'Riyadh' OR
custCity = 'Dammam';
or equivalently
SELECT *
FROM Customer
WHERE custCity IN (‘Jeddah', ‘Riyadh', ‘Dammam');
Lec
ture
8
30
custNo custName custSt custCity age
1 C1 Olaya St Jeddah 20
2 C2 Mains St Riyadh 30
3 C3 Mains Rd Riyadh 25
4 C4 Mains Rd Dammam
5 C5 Mains Rd Riyadh
Simple Queries : LIKE / NOT LOKE
• LIKE is used to search for a specified pattern in a column.
• NOT LIKE allows you to select records that does NOT match the pattern.
• Syntax
• SQL has special pattern matching symbol
• % represents any sequence of zero or more characters
• _ represents any single character
Lec
ture
8
31
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE | NOT LIKE ‘pattern’;
LIKE Example
Example: List all products whose description contain the string 'Food'.
SELECT *
FROM product
WHERE prodDes LIKE '%Food%';
prodNo prodName prodDes price
100 P0 Food 100
101 P1 healthy food 100
Lec
ture
8
32
More Examples of LIKE | NOT LIKE
LIKE 'H_' : any string beginning with H and exactly 2 characters long
NOT LIKE 'H%': any string not beginning with H
LIKE '%y': any string ending with 'y' Lec
ture
8
33
Simple Queries : IS NULL and IS NOT NULL
• It is not possible to test for NULL values with comparisonoperators, such as =, <, or <>.
• To test for null values in a query, use IS NULL or IS NOT NULL inthe WHERE clause.
• Comparisons between a NULL and any other value, returnunknown and the result will not be included in the final results
• Syntax
Lec
ture
8
34
SELECT column_name(s)
FROM table_name
WHERE column_name IS NULL | IS NOT NULL ;
IS NULL and IS NOT NULL Examples
Example: List all products with a product description.
SELECT *
FROM product
WHERE prodDes IS NOT NULL;
Similarly, to list products without description, use
SELECT *
FROM product
WHERE prodDes IS NULL;
prodNo prodName prodDes price
100 P0 Food 100
101 P1 healthy Food 100
103 P3 self_raisingflour,80%wheat
300
104 P4 network 80x 300
prodNo prodName prodDes price
102 P2 200
Lec
ture
8
35
Simple Queries : Use of DISTINCT
• Use Distinct in the select statement To remove duplicate values
• Syntax
Lec
ture
8
37
SELECT DISTINCT column_name,column_name
FROM table_name;
Use of DISTINCT Example
Example: List all customer cities.
SELECT custCity FROM customer;
• A city will be repeated if there are more than one customer in that city. To eliminate the duplicates, use:
SELECT DISTINCT custCity FROM customer;
custCity
Jeddah
Riyadh
Dammam
custCity
Jeddah
Riyadh
Riyadh
Dammam
Riyadh
Lec
ture
8
38
Simple Queries : Ordering of Rows
• Rows can be put in ascending or descending order of some columns. To do this, use ORDER BY
• Syntax
• Default order (ie, if desc is not used) is ascending
Lec
ture
8
39
SELECT column_name,column_name
FROM table_name
WHERE Condition
ORDER BY column_name,column_name ASC|DESC ;
Ordering of Rows Example
• Example: list all products in descending order of price
SELECT *
FROM product
ORDER BY price desc;
• Can also order by several attributes, eg.
ORDER BY price desc, prodName;
prodNo prodName prodDes price
103 P3 self_raisingflour,80%wheat
300
104 P4 network 80x 300
102 P2 200
100 P0 Food 100
101 P1 healthy Food 100
Lec
ture
8
40
Operators summary
Lec
ture
8
42
Operator Function
= equal to
< less than
> greater than
<= less than equal to
>= greater than equal to
<> not equal to
LIKE % used as wildcard. eg. LIKE ‘%PRE%’
IN test for in an enumerated list.
BETWEEN used to select values within a range
Update Statement
• The UPDATE statement is used to update records in a table
• Syntax
Notice the WHERE clause in the SQL UPDATE statement!The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!
Lec
ture
8
44
UPDATE table_name
SET column1=value1, column2=value2,...
WHERE some_column=some_value ;
Update Statement Example
• Example : Customer C1 has changed his city to Riyadh.
UPDATE CustomerSET custCity=‘Riyadh‘ , custSt='12 Mains Rd'
WHERE CustName=C1';
Output: 1 row updated
Select * From Customer ;
Lec
ture
8
45
custNo custName custSt custCity age
1 C1 12 Main Rd Riyadh 20
2 C2 Mains St Riyadh 30
3 C3 Mains Rd Riyadh 25
4 C4 Mains Rd Dammam
5 C5 Mains Rd Riyadh
Update Statement Example
Be careful when updating records. If we had omitted the WHERE clause, in the example before, like this:
UPDATE CustomerSET custCity=‘Riyadh‘ , custSt='12 Mains Rd' ;
Output: 5 rows updated
Select * From Customer ;
Lec
ture
8
46
custNo custName custSt custCity age
1 C1 12 Main Rd Riyadh 20
2 C2 12 Main Rd Riyadh 30
3 C3 12 Main Rd Riyadh 25
4 C4 12 Main Rd Riyadh
5 C5 12 Main Rd Riyadh
Delete Statement
• The DELETE statement is used to delete records in a table.
• Syntax
Notice the WHERE clause in the SQL DELETE statement!The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
DELETE does not delete the table itself, only
rows in the table.
Lec
ture
8
47
DELETE FROM table_name
WHERE some_column=some_value;
Delete Statement Example
• Example : Delete Customer C1
DELETE FROM CustomerWHERE CustName=‘C1';
Output: 1 row deleted
Select * From Customer ;
Lec
ture
8
48
custNo custName custSt custCity age
2 C2 Mains St Riyadh 30
3 C3 Mains Rd Riyadh 25
4 C4 Mains Rd Dammam
5 C5 Mains Rd Riyadh
Delete Statement Example
• Example : Delete all Customers
DELETE FROM Customer;
Output: 5 row deleted
Select * From Customer ;
Lec
ture
8
49
custNo custName custSt custCity age
Truncate Statement
• TRUNCATE deletes all data in a table and frees storage space for the table rows ( deletes data faster but you cannot rollback)
• Syntax
TRUNCATE get rid of the data but not the table itself (DROP)
Lec
ture
8
50
Truncate table table_name;
Truncate Example
• Example : Delete all Products
TRUNCATE TABLE product;
Lec
ture
8
51
prodNo prodName prodDes price
Lec
ture
8
52
Truncate vs Delete
Delete Truncate
To remove rows from a table To remove all rows from a table
WHERE Clause can be used , if no where clause is specified all
rows will be removed
We cant use WHERE clause
DML command DDL command
You can rollback You can’t rollback
Employee No. First Name Last Name Dept Number Salary
E1 Mandy Smith D1 50000
E2 Daniel Hodges D2 45000
E3 Shaskia Ramanthan D2 58000
Dept Number Dept Name Location Mail Number
D1 Computer Science Bundoora 39
D2 Information Science Bendigo 30
D3 Physics Bundoora 37
D4 Chemistry Bendigo 35
Lec
ture
8
54
1)Basic SQL SELECT Queries
SELECT firstName, lastName
FROM Employee
WHERE employeeNo = ‘E1’;
Lec
ture
8
55
2)Compound Comparison
SELECT deptNumber
FROM EMPLOYEE
WHERE lastName = ‘Smith’OR lastName = ‘Hodges’;
SQL Queries Example
Lec
ture
8
56
SELECT DISTINCT deptNumber
FROM EMPLOYEE;
3)Duplicate Removal
4)Set Membership Search ( IN)
SELECT deptNumber, mailNumber
FROM DEPARTMENT
WHERE deptName IN ( ‘Computer Science’, ‘Physics’);
SQL Queries Example
5)Pattern Match Search ( LIKE)
SELECT employeeNo, deptNumber
FROM EMPLOYEE
WHERE firstName LIKE ‘%an%’;
Lec
ture
8
57
SELECT employeeNo , lastName
FROM EMPLOYEE
ORDER BY lastName;
6)Sorting Output from Queries
SQL Queries Example
Lec
ture
8
58
Relation Algebra Queries Example
Rewrite queries 1, 2, and 4 by using the ralational
algebra