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

Lesson 4

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lesson 4

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 74

Structured Query

Language(SQL)

Lecturer: Rana
Salah
[email protected]
Room:3005

Made by:
Shahinaz S. Azab
Edited by:
Mona Saleh
Structured Query Language
(SQL)
• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Control Language (DCL)

2
Database Schema

A schema is a group of related objects in a database. There is


one owner of a schema who has access to manipulate the
structure of any object in the schema. A schema does not
represent a person, although the schema is associated with a
user that resides in the database.

3
Data types

A data type determines the type of data that can be stored in a


database column. The most commonly used data types are:

1. Alphanumeric: data types used to store characters,


numbers, special characters, or nearly any combination.
2. Numeric
3. Date and Time

4
Database Constraints

• Primary Key ( Not Null + Unique)

• 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
CREATE TABLE DEPARTMENT
(DNUMBER NUMBER(15) CONTSRAINT DEPT_ID_PK PRIMARY
KEY, DNAME VARCHAR(30) NOT NULL, MGRSTARTDATE
DATE, MGRSSN NUMBER(15) CONTSRAINT DEPT_SSN_FK
FOREIGN KEY REFERENCES EMPLOYEE (SSN) );

SALARY NUMBER(15) CONSTRAINT SAL_CHK CHECK


(SALARY >3000)
8
DROP Command

• Syntax
DROP TABLE table_name

• Example
DROP TABLE Students

9
ALTER Command

• ALTER TABLE statement is used to add or drop


columns in an existing table.

• Syntax
- ALTER TABLE table_name ADD column_name datatype
CONSTRAINT
- ALTER TABLE table_name DROP COLUMN column_name

10
ALTER Example

LastName FirstName Address


Pettersen Kari Storgt 20

To add a column named "City" in the “Students" table:

ALTER TABLE Students ADD City


varchar(30)
Result:

City
LastName FirstName Address
(NN)
Pettersen Kari Storgt 20

11
Data Manipulation Language
(DML)
• INSERT Command
• UPDATE Command
• DELETE Command
• SELECT Command

12
INSERT Command

• Syntax
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)

Column Name Data Type


Table Store_Information store_name char(50)
Sales float
Date datetime

• Example
INSERT INTO Store_Information (store_name, Sales, Date)
VALUES ('Los Angeles', 900, 'Jan-10-1999')

13
INSERT Example 2

FirstName Address City


LastName
El-Sayed Mohamed Nasr City Cairo

INSERT INTO Students VALUES (‘Saleh’, ‘Ahmed', ‘Moharam bak',


‘Alex.')
Result

LastName FirstName Address City

El-Sayed Mohamed Nasr City Cairo


Saleh Ahmed Moharam bak. Alex.

14
INSERT Example 3

FirstName Address City


LastName
El-Sayed Mohamed Nasr City Cairo
Saleh Ahmed Moharam bak. Alex.

INSERT INTO Students (LastName, City) VALUES (‘Hassan',


‘Assuit’)
INSERT INTO STUDENTS VALUES
Result
(‘HASSAN’,NULL,NULL,’ASSUIT’)

FirstName Address City


LastName
El-Sayed Mohamed Nasr City Cairo
Saleh Ahmed Moharam bak. Alex.
Hassan Assuit

15
UPDATE Command

• Syntax
UPDATE table_name
SET column_1= new value, column_2= new value
WHERE condition

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
UPDATE Example 2

LastName FirstName Address City


El-Sayed Mohamed Nasr City Cairo
Saleh Ahmed Moharam bak. Alex.
UPDATE Student SET Address = ‘241 El-haram ', City = ‘Giza'
WHERE LastName = ‘El-Sayed’
UPDATE STUDENT SET CITY = NULL WHERE Name = ‘elsayed’

Result:

FirstName Address City


LastName
El-Sayed Mohamed 241 El-haram
Saleh Ahmed Moharam bak.

18
DELETE Command

• Syntax
DELETE FROM table_name
WHERE condition

19
DELETE Example

DELETE FROM Store_Information


WHERE store_name = ‘Los Angeles’

Before After

store_name Sales Date store_name Sales Date


Jan-05- San Diego $250 Jan-07-1999
Los Angeles $1500
1999
Jan-07- Boston $700 Jan-08-1999
San Diego $250
1999
Jan-08-
Los Angeles $300
1999
Jan-08-
Boston $700
1999

20
TRUNCATE Vs DELETE

TRUNCATE TABLE is functionally identical to


DELETE statement with no WHERE clause
•TRUNCATE TABLE table_name
•TRUNCATE TABLE customer
•1- delete where , truncate nowhere cond
•2- trunc DDL w delete DML
3- truncate much faster than delete
•4- truncate shift delete (deallocation ll disk space)
•Delete (deallocation when commit happens)
•5- Truncate autocommit (rollback), delete can be
rolled back
21
Simple Queries

• Syntax

SELECT <attribute list >


FROM <table list>
WHERE <condition>
ORDER BY <attribute list >

22
Examples

• SELECT *
FROM departments;

• SELECT emp_id, emp_name, dept_id


FROM employees;

• SELECT dept_id, dept_name


FROM departments
WHERE location = ‘Cairo’;

23
DISTINCT Keyword

• It’s a row keyword that displays unique rows

• 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 DNo
2
FROM employees; 3

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

• SELECT DISTINCT DNo,JobID Output


FROM employees; DNo JobID
2 Sales_Rep
2 IT_PROG
3 Sales_Rep

25
Comparison Conditions

= Equal
> greater than
>= greater than or equal
< less than
<= less than or equal
<>not equal

SELECT last_name, salary


FROM employees
WHERE salary >1000

26
Other Comparison Conditions

• BETWEEN …… AND ….. (between two values inclusive)

• IN (set) (Match any of a list of values)


ALL ( set) (Match all values in the list)

• LIKE (Match a character Pattern) ( _ under score stands for


any single character , % Percent stands for any sequence of n
character where n >= 0) ANSI

27
Examples
• SELECT last_name, salary
FROM employees
WHERE salary BETWEEN 1000 AND 3000;

• SELECT emp_id, last_name, salary, manager_id


FROM employees
WHERE manager_id IN (100, 101, 200);
Where manager_id = 100 or manager_id=101 or
manager_id=200

• SELECT first_name
FROM employees
WHERE first_name LIKE ‘_s%’;
WHERE first_name LIKE ‘?s*’;

28
Logical Conditions

• AND
• OR
• NOT

SELECT emp_id, last_name, salary, manager_id


FROM employees
WHERE manager_id NOT IN (100, 101, 200)
AND (salary >1000 or salary <3000);

29
Arithmetic Expressions

• SELECT last_name, salary, salary + 300 as new_sal


FROM employees;

• Order of precedence: * , / , +, -
You can enforce priority by adding parentheses

• SELECT last_name, salary, 10 * (salary + 300) AS


“Proposed salary”
FROM employees;

30
Order by Clause
(ASC, DESC)

• SELECT fname, dept_id, hire_date


FROM employees
ORDER BY hire_date DESC;

• SELECT fname, dept_id, salary


FROM employees
ORDER BY dept_id ASC, Salary DESC;
10 5000
10 3000
20 7000
31
Types of Join

• INNER JOIN: Returns rows when there is at least one


match in both tables

• Outer JOIN: Returns matched rows as well as rows


when there is no match in one of the tables

• Cartesian Product: Returns all possible combination


of rows

32
Join Queries (Inner Join)

Retrieve the name , address of all employees who work


for Research Department

SELECT fname , Lname, address


FROMEmployee , Department
WHERE Dname=‘research’ AND
department.number= employee.dno

Department.mgrssn = employee.ssn (Manage)

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.

• You should prefix the ambiguous column names with


table name

• It’s generally recommended that you prefix all column


names with table name for better performance

34
Example

• Query All employees working for any department.

SELECT department.name, employee.ID,


employee.name, employee.Salary
FROM department, employee
WHERE department.id= employee.deptid (JOIN
condition)
ORDER BY department.name

Ambiguity for column names

35
Table Alias

• You can add alternative name (Alias) for Table name


• Alias can be useful for long or complex table names
• You can use table alias instead of table name to
resolve ambiguity

SELECT e.ID , d.name , e.name , e.Salary


FROM department as d , employee as e
WHERE d.id = e.deptid
ORDER BY d.name

36
Self Join

• Query the employees table to list name of each


employee and his supervisor name.

SELECT e.name Employee_name , s.name Supervisor


FROM employees e , employees s
WHERE e.supervisorID = s.ID

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
Outer Join

• Display all departments’ information even if they have


no employees assigned.

SELECT e.name AS Employee, d.dept_ id,


d.name AS Department
FROM employees e RIGHT OUTER JOIN departments
d
ON e.dept_ id= d.id ;
Employees Dept_ID Departments
Ahmed Ali 100 IT
Mohamed Samir 200 Marketing
Mona Selim 100 IT
300 HR

39
Equijoins and Non-Equijoins

• Equijoin: when the join condition is based on the


equality operator (Ex. D.dno=e.deptno)

• Non-Equijoin: when the join condition is based on any


operator rather than the equality operator

40
Example (Non-Equijoin)

• Display employees information ( name , salary , title)


with salary grade for each employee.

SELECT e. name, e. salary, j.grade


FROM employees e, job_ grades j
WHERE e. salary BETWEEN j.lowsal
AND j.highsal;

job_grades employees
LowSal HighSal Grade EmpNo Name Salary
1000 4000 B 100 Ahmed 5000
4000 7000 A 200 Mai 3000

41
Sub-Queries

• Sub-Query (Nested Query): is a complete SELECT


query inside another SELECT

• The Inner query is executed first then the outer query

• The inner query is usually placed in the WHERE or


HAVING clauses

• Sometimes it is placed in the FROM clause and called


“inline view”

42
Examples

• Find the names of employees whose working


locations are giza

SELECT name
FROM Employee
WHEREDno IN (SELECT Dnumber
FROM dept
WHERE location=‘giza’)

43
Examples (Cont’d )

• Display department name for the highest paid


employee

SELECT dname
FROM dept
WHERE deptno = (SELECT deptno
FROM emp
WHERE sal =
(SELECT MAX(sal)
FROM EMP));

44
Examples (Cont’d)

• Find the names of employees whose salary is greater


than the salary of the employees in department 5

SELECT Lname , Fname


FROM employee
WHERE salary > ALL ( SELECT salary
FROM employee
WHERE Dno=5)

45
Union Operator

• UNION operator is one of the set operators that unifies the


output of two select statements into one result.
• Two conditions must apply for the two selects
• Same number of columns
• Same data type of columns
• The result displays the names of the first query
• If one row is contained in the result of the two selects it is
displayed only once.
• UNION ALL is functionally equivalent to UNION operator,
except that it doesn’t eliminate repetition in the result set

46
Examples

• Find the departments numbers whose


location in GIZA or manager no = 10

SELECT dnumber
FROM department WHERE MRGSSN= 10
One
Union Result
SELECT dnumber
FROM dept_locations
WHERE dlocation=‘GIZA’

47
Examples (Cont’d)

• Display names of current employees as well as


previous employees

SELECT Name
FROM Employees
UNION
SELECT Name
FROM Employees_retired

48
Correlated Sub-Query

• When the inner query references one of the attributes


of the outer query.

• The inner query is executed once per row of the outer


query

49
Exists Keyword

• The EXISTs keyword is used with correlated sub-


queries

• The EXISTS condition is considered "to be met" if the


sub-query returns at least one row.

• Syntax
SELECT columns
FROM tables
WHERE EXISTS (sub-query );

50
Example

• Display suppliers information who have orders.

SELECT *
FROM suppliers
WHERE EXISTS
(SELECT *
FROM orders
WHERE
suppliers.supplier_id=
orders.supplier_id);

51
Example 2

• Retrieve the name of employees who have no


dependents

SELECT name
FROM employee
WHERE NOT EXISTS (SELECT *
FROM dependent
WHERE ssn=Essn)

52
Exists Condition With DML

• DELETE FROM suppliers


WHERE NOT EXISTS
(SELECT *
FROM orders
WHERE suppliers.supplier_id =
orders.supplier_id);

53
Aggregate Functions

• Aggregate Functions (group functions): perform a


specific operation on a number of rows and return one
result per group

• Examples: COUNT , SUM , MAX, MIN and AVG

• Group Functions ignore Null values in the columns

54
Examples
• Find the sum, maximum, minimum and average
salaries of all employees
SELECT SUM (salary) , MAX (salary), MIN (salary),
AVG (salary)
FROM Employees

• Find the total number of employees in the company?


SELECT COUNT(*)
FROM employees

• Find the number of employees in the research


department?
SELECT COUNT(*)
FROM employee , department
WHERE dno=dnumber AND dname =‘Research’
55
Grouping

• If you want to apply aggregate functions to subgroups


of tuples, use GROUP BY clause

• GROUP BY clause must be used in conjunction with


aggregate functions

• You can filter group results using HAVING clause

• HAVING clause is used for applying conditions on


group functions

56
Grouping Examples

• For each department, retrieve the department


number, the number of employees in the department,
and their average salaries

SELECT dno , COUNT (*) , AVG (salary)


FROM employee
GROUP BY dno

57
Grouping Examples (Cont’d)

• For each project on which more than two employees


work, retrieve the project number, the project name ,
and the number of employees who work on the
project

SELECT pnumber, pname ,count (works_on.pno)


FROM project , Works_on
WHERE Pnumber = Pno
GROUP BY pnumber, pname
HAVING COUNT (*) > 2
ORDER BY Pnumber

58
C. Data Control Language

Grant Revoke

• GRANT SELECT ON TABLE -REVOKE UPDATE ON TABLE


employees TO Ahmed; department
• GRANT ALL ON TABLE FROM Mary;
department TO Mary, Ahmed;
• GRANT SELECT ON TABLE
employees TO Ahmed WITH - REVOKE ALL ON TABLE
GRANT OPTION; department FROM Mary, Ahmed;

59
Views

• A view is a logical table based on a table or another


view

• A view contains no data of its own, but is like a


window through which data from tables can be viewed
or changed

• The tables on which a view is based are called base


tables

• The view is stored as a SELECT statement in the data


dictionary.

60
Advantages of Views

• Restrict data access

• Make complex queries easy

• Provide data independence

• Present different views of the same data

61
Simple Views and Complex Views

Feature Simple Views Complex Views


Number of tables One One or more

Contain functions No Yes

Contain groups of data No Yes


DML operations through a Yes Not always
view

• DML operations can be performed on simple views, however


for complex views they are not always applicable

62
Creating Views

CREATE VIEW view [ (column 1 [ , column2 ] … ) ]


AS subquery
[ With Check Option ] ;

63
Creating Views (Cont’d)

• Create a view to display employee names and total


hours employee worked on a project

CREATE VIEW vw_work_hrs


AS
SELECT Fname as First_name , Lname , Pname ,
Hours
FROM Employee, Project , Works_on
WHERE SSN=ESSN AND PNO=PNUMBER

64
Retrieving Data from a View

• SELECT fname, lname, hours


FROM vw_work_hrs

• SELECT *
FROM vw_work_hrs

65
Views with Check option

CREATE VIEW Suppliers


AS
SELECT *
FROM suppliers
WHERE status > 15
WITH CHECK OPTION;

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
Removing a View

• Syntax
DROP VIEW view_name;

• Example
DROP VIEW vw_work_hrs

68
Indexes

• They are used to speed up the retrieval of records in


response to certain search conditions.

• May be defined on multiple columns

• Can be created by the user or by the DBMS

• Are used and maintained by the DBMS

69
Indexes (Cont’d)

Athens S1 Smith 20 London

S2 Jones 10 Paris
London

London S3 Blake 30 Paris

Paris S4 Clark 20 London

Paris S5 Adams 30 Athens

file (index) Supplier file (data)

70
Index Creation Guidelines

Create an index when:


A column contains a wide range of values

A column contains a large number of null values


One or more columns are frequently used together in a WHERE clause or
a join condition
The table is large and most queries are expected to retrieve less than 2%
to 4% of the rows in the table
Do not create an index when:
The columns are not often used as a condition in the query

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

The indexed columns are referenced as part of an expression

71
Indexes (Cont’d)

• Creation
CREATE INDEX index_name ON Table_name (column_name);

CREATE INDEX emp_inx ON Employee (Salary);

• Removing
DROP INDEX index_name;

DROP INDEX emp_inx;

72
SQLTutorials

• Oracle SQL URL : beginner-sql-tutorial.com


• Sybase SQL URL :
http://infocenter.sybase.com/help/index.jsp
• ANSI SQL URL :
http://www.w3schools.com/SQL/sql_join.asp
• MS SQL URL :
http://msdn.microsoft.com/en-us/library/bb264565.aspx
• IBM Informix SQL :
http://publib.boulder.ibm.com/infocenter/idshelp/v10/
index.jsp?topic=/com.ibm.sqlt.doc/sqltmst104.htm

73
Questions?

74

You might also like