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

Structured Query Language (SQL) : By: Shahinaz Azab 2009

The document discusses Structured Query Language (SQL) which includes data definition language (DDL) for defining database schemas and objects, data manipulation language (DML) for manipulating data, and data control language (DCL) for controlling access to data. It covers SQL data types, database constraints, the CREATE, DROP, ALTER, INSERT, UPDATE, DELETE and TRUNCATE commands, comparison and logical operators for queries, arithmetic expressions, ordering results, and joining tables.

Uploaded by

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

Structured Query Language (SQL) : By: Shahinaz Azab 2009

The document discusses Structured Query Language (SQL) which includes data definition language (DDL) for defining database schemas and objects, data manipulation language (DML) for manipulating data, and data control language (DCL) for controlling access to data. It covers SQL data types, database constraints, the CREATE, DROP, ALTER, INSERT, UPDATE, DELETE and TRUNCATE commands, comparison and logical operators for queries, arithmetic expressions, ordering results, and joining tables.

Uploaded by

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

Structured Query

Language(SQL)

by:
Shahinaz Azab
2009
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
A. Create Command

CREATE TABLE "table_name"


("column 1" "data_type_for_column_1",
"column 2" "data_type_for_column_2",
... )
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);

6
7
B. Drop Table
Sometimes we may decide that we need to get rid of a table
in the database for some reason.

DROP TABLE "table_name"


DROP TABLE Students

8
C. Alter Command
ALTER TABLE statement is used to add or drop columns in an
existing table.
- ALTER TABLE table_name ADD column_name datatype

- ALTER TABLE table_name DROP COLUMN column_name

LastName FirstName Address


Pettersen Kari Storgt 20
Example(1)
To add a column named "City" in the "Person" table:
ALTER TABLE students ADD City varchar(30)

Result:

LastName FirstName Address City


Pettersen Kari Storgt 20  

9
Data Manipulation Language
A. INSERT Command
INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...)

Table Store_Information Column Name Data Type


store_name char(50)
Sales float
Date datetime

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

10
Example (2)
INSERT INTO table_name (column1, column2,...) VALUES (value1,
value2,....)
Insert a New Row
This “Students" table:

FirstName Address City


LastName
El-Sayed Mohamed Nasr City Cairo
And this SQL statement:

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

Will give this result:


LastName FirstName Address City

El-Sayed Mohamed Nasr City Cairo


Saleh Ahmed Moharam bak. Alex.
11
Example(3) Insert Data in Specified Columns
This “Students" table:
FirstName Address City
LastName
El-Sayed Mohamed Nasr City Cairo
Saleh Ahmed Moharam bak. Alex.
And This SQL statement:

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

Will give this result:

FirstName Address City


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

12
B. Update Command
UPDATE "table_name"
SET "column_1" = [new value]
WHERE {condition}

Example (1) 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
13
Example(2)Update several Columns in a Row

We want to change the address the name of the city:


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

UPDATE Person SET Address = ‘241 El-haram ', City = ‘Giza' WHERE
LastName = ‘El-Sayed'
Result:

FirstName Address City


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

14
C. Delete Command
DELETE FROM "table_name"
WHERE {condition}
Table Store_Information
store_name Sales Date

Los Angeles $1500 Jan-05-1999

San Diego $250 Jan-07-1999

Los Angeles $300 Jan-08-1999

Boston $700 Jan-08-1999

DELETE FROM store_name Sales Date


Store_Information Jan-07-
San Diego $250
1999
Jan-08-
WHERE store_name = "Los Angeles" Boston $700
1999

15
Truncate Table

DDL not DML


TRUNCATE TABLE is functionally identical to
DELETE statement with no WHERE clause

•TRUNCATE TABLE "table_name"

•TRUNCATE TABLE customer.

16
Simple Queries
Select <attribute list >
From < table list>
Where <condition>

- select *
from departments;

- select emp_id, emp_name, dept_id


from employees;

- select distinct dept_id


from employees;

17
Simple Queries (Cont’d)

- Select dept_id, dept_name


from departments
where location = ‘Cairo’;

18
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

19
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

20
Other Comparison Conditions (Cont’d)
- 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);

- Select first_name
from employees
where first_name Like ‘_s%’;

21
Logical Conditions

• AND
• OR
• NOT

- Select emp_id, last_name, salary, manager_id


From employees
where manager_id NOT IN (100, 101, 200);

22
Arithmetic Expressions

- Select last_name, salary, salary + 300


from employees;

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

- Select last_name, salary, 10 * (salary + 300)


from employees;

23
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 DESC, Salary DESC;

24
Types of Join

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


match in both tables

• Outer JOIN : Return rows when there is no match in


one of the tables

25
Join Queries (Inner Join)

Define Cartesian Product ?

Match rows in both tables

Retrieve the name , address of all employees who work


for Research Department

Select fname , Lname, address


From Employee , Department
Where Dname=‘research’ and
Department.number=employee.Dno

26
Ambiguous Column Names

• 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.

• Query All employees working for any department.

Select department.name , employee.ID , employee.name ,


Salary
From department , employee
Where department.id = employee.deptid
Order by department.name

27
SQL Alias

• Alias for Table name or Column name

• very long or complex table names or column names.

• To resolve ambiguity for same column names in more than


one table.

Select e.ID , d.name , e.name , Salary


From department d , employee e
Where d.id = e.deptid
Order by d.name

28
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

29
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

30
Outer Join

• Display department information regardless it has


employees or not.
SELECT e. name AS Employees,
e. dept_ id AS Dept_ID, d. name AS Departments
FROM employees e, departments d
WHERE e. dept_ id(+) = d. id ;
Employees Dept_ID Departments
Ahmed Ali 100 IT
Mohamed Samir 200 Marketing
Mona Selim 100 IT
300 HR

31
Equijoins and Non-Equijoins

• Using Equal Operator not satisfy all join conditions.

• 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.lowest_ sal AND j. highest_ sal;

32
Sub-Queries

• Find the names of employees whose working location


= giza

Select name
from Employee
where Dno in
( select Dnumber from dept
where location=‘giza’)

33
Sub-Queries (Cont’d )

• Display department name with the highest paid


employee

1- Highest Salary


2- Deptno for this Employee
3- Department name

SELECT dname FROM dept


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

34
Nested Queries (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)

35
Union Operator

• 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’

36
Union Operator ( Cont’d)

The UNION operator selects only distinct values by


default. To allow duplicate values, use UNION ALL.

Display names for all employees who is or was working


in the organization.

SELECT Name FROM Employees


UNION SELECT Name FROM Employees_retired

37
Exists Condition

Check if the result of correlated subquery is empty


The EXISTS condition is considered "to be met" if the
subquery returns at least one row.

Display suppliers information who have orders.


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

38
Exists Condition

• Retrieve the name of employees who have no


dependents

Select name
From employee
Where Not Exists ( select * from dependent where
ssn=Essn)

39
Exists Condition With DML

• DELETE FROM suppliers


WHERE Not EXISTS
  (select *
    from orders
    where suppliers.supplier_id = orders.supplier_id);

40
Aggregate Functions
COUNT , SUM , MAX, MIN and AVG

• Find the sum of salaries of all employees , the maximum,


the minimum salary, and the average salary

Select Sum(salary) , Max(salary), Min(salary), Avg(salary)


from Employees

Find the total number of employees in the company?


Find the number of employees in the research department?
Note : Group Functions ignore Null values in the
columns

41
Grouping

Apply aggregate functions to a subgroups of


tuples

For each department retrieve the department


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

Select dno , count(*) , avg(salary)


From employee Group by dno

42
Grouping (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

43
C. Data Control Language

Grant Revoke

- Grant Select on table employees to -Revoke update on Table department


Ahmed;
From Mary;
- Grant All on Table department to
Mary, Ahmed;
- Grant Select on table employees to - Revoke All on Table department
Ahmed with grant Option; From Mary, Ahmed;

Note: Example in the notes 44


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/ind
ex.jsp?topic=/com.ibm.sqlt.doc/sqltmst104.htm

45
Views

 Definition: It is a virtual table that is derived from other


tables. These other tables could be base tables or
previously defined views. A view doesn't exist in a physical
form; in contrast to base tables whose tuples are actually
stored in the database. (This limits update capabilities)

 We can think of a view as a way of specifying a table that


we need to reference frequently, even though it doesn’t
exist physically.

46
Advantages of Views

• They allow the same data to be seen by different


users in different ways. ( to focus on the data of
concern to them)
• They provide security for the rest of the hidden data.

47
Views

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


AS subquery
[ With Check Option ] ;

48
Views (Cont’d)

Create a view to display employee names and total


hours

CREATE VIEW vw_work_hrs


AS select Fname , Lname , Pname , Hours
From Employee, Project , Works_on
Where SSN=ESSN and PNO=PNUMBER

49
Views ( cont’d)

A view is not updatable :


1- based on multiple tables
2- defined using grouping and aggregate functions

50
Views with Check option

- Create View Suppliers


As
Select *
From suppliers
Where status > 15
With Check Option;
Drop the view
DROP VIEW vw_work_hrs

51
Indexes

- Definition: They are used to speed up the retrieval of


records in response to certain search conditions.
- May be defined on multiple columns

- Create Index emp_inx on Employee (Salary);

- Drop Index emp_inx;

52
Index

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)

53

You might also like