Lesson 4
Lesson 4
Language(SQL)
Made by:
Shahinaz S. Azab
Edited by:
Mona Saleh
1
Structured Query Language (SQL)
• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Control Language (DCL)
2
Database Schema
Schema Definition
3
Data types
4
Database Constraints
• Not Null
• Unique Key
• Referential Integrity ( FK )
• Check
5
Data Definition Language (DDL)
• CREATE command
• ALTER command
• DROP command
• TRUNCATE command
6
CREATE Command
• Syntax
CREATE TABLE table_name
(column1 DATA_TYPE [CONS_TYPE CONS_NAME],
column2 DATA_TYPE [CONS_TYPE CONS_NAME],... )
• Example
CREATE TABLE Students
(ID NUMBER(15) PRIMARY KEY, First_Name CHAR(50) NOT
NULL, Last_Name CHAR(50), Address CHAR(50), City
CHAR(50), Country CHAR(25), Birth_Date DATE);
7
8
8
DROP Command
• Syntax
DROP TABLE table_name
• Example
DROP TABLE Students
9
ALTER Command
• Syntax
- ALTER TABLE table_name ADD column_name datatype
- ALTER TABLE table_name DROP COLUMN column_name
10
10
ALTER Example
Result:
11
11
Data Manipulation Language (DML)
• INSERT Command
• UPDATE Command
• DELETE Command
• SELECT Command
12
12
INSERT Command
• Syntax
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
• Example
INSERT INTO Store_Information (store_name, Sales, Date)
VALUES ('Los Angeles', 900, 'Jan-10-1999')
13
13
INSERT Example 2
Result
14
14
INSERT Example 3
Result
15
15
UPDATE Command
• Syntax
UPDATE table_name
SET column_1= new value, column_2= new value
WHERE condition
16
16
UPDATE Example
UPDATE Store_Information
SET Sales = 500
WHERE store_name = ‘Los Angeles’ AND Date = ‘Jan-08-1999’
Before After
store_name Sales Date store_name Sales Date
Jan-05- Jan-05-
Los Angeles $1500 Los Angeles $1500
1999 1999
Jan-07- Jan-07-
San Diego $250 San Diego $250
1999 1999
Jan-08- Jan-08-
Los Angeles $300 Los Angeles $500
1999 1999
Jan-08- Jan-08-
Boston $700 Boston $700
1999 1999
17
17
UPDATE Example 2
UPDATE Person SET Address = ‘241 El-haram ', City = ‘Giza' WHERE
LastName = ‘El-Sayed'
Result:
18
18
DELETE Command
• Syntax
DELETE FROM table_name
WHERE condition
19
19
DELETE Example
Before After
20
20
TRUNCATE Vs DELETE
21
TRUNCATE:
• Deletes all data but keeps the structure of the table
• Deletes data unconditionally (doesn’t have WHERE clause)
• Can’t be rolled back because it’s a DDL statement
• De-allocates the physical memory assigned to data.
DELETE:
• Deletes all data but keeps the structure of the table (if it doesn’t have
WHERE clause)
• Can include a WHERE clause to delete data conditionally
• Can be rolled back since it is a DML statement
• Keeps the physical memory assigned to data until a commit or rollback is
issued.
21
Simple Queries
• Syntax
22
22
Examples
• SELECT *
FROM departments;
23
23
DISTINCT Keyword
• Example
Employees table
EmpNo Name DNo JobID
100 Ahmed 2 Sales_Rep
200 Mai 2 IT_PROG
300 Ali 2 Sales_Rep
400 Mahmoud 3 Sales_Rep
Output
DNo
• SELECT DISTINCT dept_id
2
FROM employees; 3
24
24
DISTINCT Keyword (cont.)
• Example
Employees table
EmpNo Name DNo JobID
100 Ahmed 2 Sales_Rep
200 Mai 2 IT_PROG
300 Ali 2 Sales_Rep
400 Mahmoud 3 Sales_Rep
25
25
Comparison Conditions
= Equal
> greater than
>= greater than or equal
< less than
<= less than or equal
<>not equal
26
26
Other Comparison Conditions
27
Example #1 - Numbers
The following is an SQL statement that uses the BETWEEN function:
SELECT *
FROM suppliers
WHERE supplier_id between 5000 AND 5010;
This would return all rows where the supplier_id is between 5000 and 5010,
inclusive. It is equivalent to the following SQL statement:
SELECT *
FROM suppliers
WHERE supplier_id >= 5000
AND supplier_id <= 5010;
Example #2 - Dates
You can also use the BETWEEN function with dates.
SELECT *
FROM orders
WHERE order_date between to_date ('2003/01/01', 'yyyy/mm/dd')
AND to_date ('2003/12/31', 'yyyy/mm/dd');
This SQL statement would return all orders where the order_date is between
27
Jan 1, 2003 and Dec 31, 2003 (inclusive).
It would be equivalent to the following SQL statement:
SELECT *
FROM orders
WHERE order_date >= to_date('2003/01/01', 'yyyy/mm/dd')
AND order_date <= to_date('2003/12/31','yyyy/mm/dd');
27
Examples
• SELECT first_name
FROM employees
WHERE first_name LIKE ‘_s%’;
28
28
Logical Conditions
• AND
• OR
• NOT
29
29
Arithmetic Expressions
• Order of precedence: * , / , +, -
You can enforce priority by adding parentheses
30
30
Order by Clause
(ASC, DESC)
31
In some DBMS You can mention ASC , DESC after each column
31
Types of Join
32
32
Join Queries (Inner Join)
33
33
Ambiguous Column Names
• When you query two tables with the same column name
➢ There is a column called “ name “ in both tables.
➢ There is a column called “ ID “ in both tables.
34
34
Example
35
35
Table Alias
36
36
Self Join
37
-------------
Select e.Fname + e.Lname as Employee_name , s.Fname + s.lname as
Supervisor
From employee e , employee s
Where e.SuperSSN = s.SSN
--------------
If we replace table names/aliases in where like example below the result will
be supervisors in employees list and employees will appear as supervisors
37
From employee e , employee s
Where s.SuperSSN = e.SSN
37
Outer Join
• LEFT JOIN: Return all rows from the left table, even if
there are no matches in the right table
• RIGHT JOIN: Return all rows from the right table,
even if there are no matches in the left table
• FULL JOIN: Return rows when there is a match in
one of the tables
38
38
Outer Join
39
Some DBMSs use the (+) notation to represent left or right outer join like
Oracle
The above syntax is equivalent to the right outer join syntax in the slides.
39
Equijoins and Non-Equijoins
40
40
Example (Non-Equijoin)
job_grades employees
LowSal HighSal Grade EmpNo Name Salary
1000 4000 B 100 Ahmed 5000
4000 7000 A 200 Mai 3000
41
41
Sub-Queries
42
42
Examples
SELECT name
FROM Employee
WHERE Dno IN (SELECT Dnumber
FROM dept
WHERE location=‘giza’)
43
43
Examples (Cont’d )
SELECT dname
FROM dept
WHERE deptno = (SELECT deptno
FROM emp
WHERE sal =
(SELECT MAX(sal)
FROM EMP));
44
44
Examples (Cont’d)
45
45
Union Operator
46
46
Examples
SELECT dnumber
FROM department WHERE MRGSSN= 10
One
Union Result
SELECT dnumber
FROM dept_locations
WHERE dlocation=‘GIZA’
47
Note: The UNION operator selects only distinct values by default. To allow
duplicate values, use UNION ALL.
47
Examples (Cont’d)
SELECT Name
FROM Employees
UNION
SELECT Name
FROM Employees_retired
48
48
Correlated Sub-Query
49
SELECT *
FROM suppliers
WHERE EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);
49
Exists Keyword
• Syntax
SELECT columns
FROM tables
WHERE EXISTS (sub-query );
50
SELECT *
FROM suppliers
WHERE EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);
50
Example
SELECT *
FROM suppliers
WHERE EXISTS
(SELECT *
FROM orders
WHERE suppliers.supplier_id=
orders.supplier_id);
51
SELECT *
FROM suppliers
WHERE EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);
51
Example 2
SELECT name
FROM employee
WHERE NOT EXISTS (SELECT *
FROM dependent
WHERE ssn=Essn)
52
52
Exists Condition With DML
53
53
Aggregate Functions
54
54
Examples
• Find the sum, maximum, minimum and average
salaries of all employees
SELECT SUM (salary) , MAX (salary), MIN (salary),
AVG (salary)
FROM Employees
55
55
Grouping
56
56
Grouping Examples
57
57
Grouping Examples (Cont’d)
58
58
C. Data Control Language
Grant Revoke
59
59
Views
60
60
Advantages of Views
61
Advantages of Views
• Views restrict access to the data because it displays selected
columns from the table.
• Views can be used to make simple queries to retrieve the
results of complicated queries. For example, views can be
used to query information from multiple tables without the user
knowing how to write a join statement.
• Views provide data independence for ad hoc users and
application programs. One view can be used to retrieve data
from several tables.
• Views provide groups of users access to data according to
their particular criteria.
61
Simple Views and Complex Views
62
62
Creating Views
63
63
Creating Views (Cont’d)
64
64
Retrieving Data from a View
• SELECT *
FROM vw_work_hrs
65
65
Views with Check option
66
With check options indicates that UPDATE and INSERT operations against the
view are to be checked to ensure that every updated or inserted row still
satisfies the view defining condition ( Status > 15 )
66
Modifying a View
• Syntax
CREATE OR REPLACE VIEW view_name
AS
Sub-query
• Example
CREATE OR REPLACE VIEW vw_work_hrs
AS
SELECT Fname , Lname , Pname , Hours
FROM Employee, Project , Works_on
WHERE SSN=ESSN AND PNO=PNUMBER AND Dno = 5;
67
67
Removing a View
• Syntax
DROP VIEW view_name;
• Example
DROP VIEW vw_work_hrs
68
68
Indexes
69
69
Indexes (Cont’d)
S2 Jones 10 Paris
London
70
70
Index Creation Guidelines
The table is small or most queries are expected to retrieve more than 2%
to 4% of the rows in the table
The table is updated frequently
71
71
Indexes (Cont’d)
• Creation
CREATE INDEX index_name ON Table_name (column_name);
• Removing
DROP INDEX index_name;
72
72
SQLTutorials
73
73
Questions?
74
74