lesson 09 - sql

Upload: hisham-munas

Post on 06-Apr-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Lesson 09 - SQL

    1/46

    1

    Structured Query Language

    Lesson 09

  • 8/3/2019 Lesson 09 - SQL

    2/46

    2

    History of SQL Developed by IBM

    Adopted as standard language for commercialRDBMS

    A comprehensive non-procedural databaselanguage package that supports standard

    Supports both DDL and DML Provides facilities to specify security, authorization

    (mainly through DCL), and constraints

  • 8/3/2019 Lesson 09 - SQL

    3/46

    3

    SQL Data Definition Commands Create Schema

    Create tables

    Create Domain Create view

    Alter Table/Schema

    Drop Table/Schema

  • 8/3/2019 Lesson 09 - SQL

    4/46

    4

    Data Definition Language CREATE

    ALTER DROP

  • 8/3/2019 Lesson 09 - SQL

    5/46

    5

    Schema and Catalog SQL schema

    Used to group table and related constructs i

    dentified by Schema name

    Contains elements such as; Tables ConstraintsViews and domainsAuthorization constructs

    Catalog Named collection of schema

  • 8/3/2019 Lesson 09 - SQL

    6/46

    6

    Create Schema CREATE SCHEMA

    [AUTHORIZATION ]

    E.g. CREATE SCHEMA CompanyAUTHORIZATION

    JSMITH JSMITH is Schema Owner

  • 8/3/2019 Lesson 09 - SQL

    7/46

    7

    Attribute Data Types and

    Domains in SQL Basic Data types

    Numeric

    Integer, Real

    Char string

    Fixed length (CHAR(n))

    Varying length (VARCHAR(n)

    date/time

    Boolean (T,F, Unknown)

    User defined data type Domain in SQL

    CREATE DOMAIN DEP_TYPEAS CHAR (9);

  • 8/3/2019 Lesson 09 - SQL

    8/46

    8

    Create Table CREATE TABLE [Schema Name]. (Attribute List)

    E.g. CREATE TABLE Company.Employees

    ( EmpID int,FirstName varchar(20),Last Name varchar(20),

    Address varchar(100))

    CREATE TABLE Employees ..

  • 8/3/2019 Lesson 09 - SQL

    9/46

    9

    Specifying Constraints using

    SQL Constraints and default values can

    specified on each table, tuple, andattributes

    Integrity Constraints will be in 3 forms

    Domain Integrity

    Entity Integrity

    Referential Integrity

  • 8/3/2019 Lesson 09 - SQL

    10/46

    10

    Domain Integrity CHECK Constraints

    NOT NULL DEFAULT Value

  • 8/3/2019 Lesson 09 - SQL

    11/46

    11

    Using CHECK Constraint Use CHECKfor more general constraints Used at the end of schema

    Applies to individual tuples E.g.,

    Supposing that DNUMBER should be between1 and 10 DNUMBER INT CHECK(DNUMBER>0AND

    DNUMBER 0AND D_NUM

  • 8/3/2019 Lesson 09 - SQL

    12/46

    12

    Using NOT NULL

    E.g.

    Suppose that DNUMBER cannot be leftblank

    DNUMBER INT NOT NULL CHECK(DNUMBER>0AND DNUMBER 0AND D_NUM

  • 8/3/2019 Lesson 09 - SQL

    13/46

    13

    Specifying Entity Integrity PRIMARY KEY CLUASE used to specify PK

    E.g., PRIMARY KEY(DNUMBER);

    UNIQUE CLAUSE

    Used for secondary keys

    NICNo varchar(20) UNIQUE

  • 8/3/2019 Lesson 09 - SQL

    14/46

    14

    Specifying Referential

    Integrity FOREIGN KEY CLUASE used to specify

    FK

    FOREIGN KEY(DNUMBER) REFERENCESDEPARTMENT (DUNMBER)

  • 8/3/2019 Lesson 09 - SQL

    15/46

    15

    Example CREATE TABLE Employees(

    EmpID Int,FirstName nvarchar(20) NOT NULL,LastName nvarchar(20),NICNo nvarchar(15) UNIQUE,DeptNo int CHECK (DeptNo>0 AND DeptNO

  • 8/3/2019 Lesson 09 - SQL

    16/46

    16

    SCHEMA CHANGE COMMANDS

    IN SQL THE DROP COMMAND

    Used to drop the named schema elementsfrom database schema

    E.g.,

    DROP SCHEMA COMPANYCASCADE

    DROP TABLE DEPENDENT CASCADE

  • 8/3/2019 Lesson 09 - SQL

    17/46

    17

    The ALTER TABLE Command Used to change the definition of base table

    E.g.,

    ALTER TABLE COMPANY.EMPLOYEEADD JOBVARCHAR(12)

    ALTER TABLE COMPANY.EMPLOYEE DROPADDRESSCASCADE;

    ALTER TABLE COMPANY.DEPARTMENTALTER MGRSSNDROP DEFAULT;

    ALTER TABLE COMPANY.DEPARTMENTALTER MGRSSNSET DEFAULT344556677

    ALTER TABLE COMPANY.EMPLOYEE DROP CONSTRAINTEMPSUPERFKCASCADE

  • 8/3/2019 Lesson 09 - SQL

    18/46

    18

    Data Manipulation Language SELECT

    INSERT UPDATE

    DELETE

  • 8/3/2019 Lesson 09 - SQL

    19/46

    19

    SELECT Statement General Form:

    SELECT

    FROM

    WHERE

  • 8/3/2019 Lesson 09 - SQL

    20/46

    20

    SELECT Statement SELECT *

    FROM Employee

    Selects all the attributes and all thetuples from Employee Table

  • 8/3/2019 Lesson 09 - SQL

    21/46

    21

    ORDER BY Clause SELECT *

    FROM Employee

    ORDER BY deptno SELECT *

    FROM EmployeeORDER BY deptno, name

    SELECT name, job, salary, EmpIDFROM EmployeeORDER BY salary DESC

  • 8/3/2019 Lesson 09 - SQL

    22/46

    22

    IN, BETWEEN and LIKE SELECT *

    FROM EmployeeWHERE deptno IN (10,20,50)

    SELECT *FROM EmployeeWHERE job = salaryBETWEEN 35000 AND 45000

    SELECT *FROM EmployeeWHERE nameLIKE 'W%'

  • 8/3/2019 Lesson 09 - SQL

    23/46

    23

    Aggregate Functions SELECT AVG(salary)

    FROM Employee

    SELECT COUNT(*)FROM Employee

    SELECT COUNT(FirstName)FROM Employee

    SELECT COUNT DISTINCT(FirstName)FROM Employee

    SELECT MAX(salary)FROM Employee

  • 8/3/2019 Lesson 09 - SQL

    24/46

    24

    JOINING Tables:

    Ambiguous Attribute Names and Renaming

    Need to qualify the attributes whenthey are the same

    use . separator to qualify the attribute e.g.,

    SELECT FNAME, EMPLOYEE.NAME, ADDRESS

    FROM EMPLOYEE, DEPARTMENT

    WHERE DEPARTMENT.DNUMBER =EMPLOYEE.DNUMBERAND

    DEPARTMENT.NAME = Research

  • 8/3/2019 Lesson 09 - SQL

    25/46

    25

    Ambiguity: Recursive

    relationships For each employee, find the employees first

    and last name and the first and last name of

    her immediate supervisor SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME

    FROM EMPLOYEEAS E, EMPLOYEEAS S

    WHERE E.SUPERSSN=S.SSN

  • 8/3/2019 Lesson 09 - SQL

    26/46

    26

    Unspecified WHERE-Clause No WHERE-clause means no

    conditions

    No condition means Cross productoperations

  • 8/3/2019 Lesson 09 - SQL

    27/46

    27

    No WHERE Clause Get all combinations of EMPLOYEE.SSN

    and DEPARTMENT.DNAME

    SELECT SSN, DNAME

    FROM EMPLOYEE, DEPARTMENT

  • 8/3/2019 Lesson 09 - SQL

    28/46

    28

    Nested Queries Some queries need the existing valuesin the database to be retrieved

    Nested queries used to formulate suchqueries

  • 8/3/2019 Lesson 09 - SQL

    29/46

    29

    Nested Query SELECT DISTINCT PNUMBER

    FROM PROJECT

    WHERE PNUMBER IN (SELECT PNUMBER FROM DEPARTMENT, EMPLOYEE , PROJECT

    WHERE DNUM = DNUMBERAND MGRSSN = SSNAND LNAME = Smith)

    OR

    PNUMBER IN (SELECT PNO FROM WORKS_ON, EMPLOYEE

    WHERE ESSN=SSNAND LNAME = Smith)

  • 8/3/2019 Lesson 09 - SQL

    30/46

    30

    Correlated nested queries Correlated Queries:

    When a condition in WHERE clause of anested query references attribute(s) of arelation defined in the outer query

  • 8/3/2019 Lesson 09 - SQL

    31/46

    31

    Correlated query Get the name of each employee who has a

    dependent with the same first name and the same

    sex

    as the employee SELECT E.FNAME, E.LNAME

    FROM EMPLOYEEAS E

    WHERE E.SSN IN (SELECT ESSN

    FROM DEPENDENTWHERE E.FNAME=DEPENDENT_NAME

    AND E.SEX=SEX);

  • 8/3/2019 Lesson 09 - SQL

    32/46

    32

    Correlated query A nested query involving = or IN can be replaced

    by simple query SELECT E.FNAME,E.LNAME

    FROM EMPLOYEEAS E, DEPEDENTAS D

    WHERE E.SSN=D.ESSNAND E.FNAME=D.DEPENDENT_NAMEANDE.SEX=D.SEX);

  • 8/3/2019 Lesson 09 - SQL

    33/46

    33

    EXISTS EXISTS:

    Checks the result to see if a correlated

    nested query is empty or not

    If the result (i.e., set) is empty it returnsfalse

    If the resultis Not empty it returns true

  • 8/3/2019 Lesson 09 - SQL

    34/46

    34

    EXISTS Find the name of each employee who has a

    dependent with the same first name and same sex asthe employee

    SELECT E.FNAME, E.LNAME

    FROM EMPLOYEE E

    WHERE EXISTS (SELECT *

    FROM DEPENDENT

    WHERE E.SSN=ESSNAND SEX=E.SEXAND

    E.FNAME=DEPENT_NAME)

  • 8/3/2019 Lesson 09 - SQL

    35/46

    35

    NOT EXISTS Find the name of each employee who

    has no dependent SELECT FNAME, LNAME

    FROM EMPLOYEE E

    WHERE NOT EXISTS (SELECT *

    FROM DEPENDENT

    WHERE SSN=ESSN)

  • 8/3/2019 Lesson 09 - SQL

    36/46

    36

    NULL Null can be interpreted as

    Unknown

    Unavailable Not applicable

    Retrieve the names of all employees who donot have supervisors

    SELECT FNAME, LNAME

    FROM EMPLOYEE

    WHERE SUPERSSN IS NULL;

  • 8/3/2019 Lesson 09 - SQL

    37/46

    37

    Grouping and COUNT GROUP BY CLUASE

    Used to partition the relation into sub-relation

    Works with

    aggregate functions

    grouping attribute

    Grouping attribute (s) need to be specify in SELECT clause

    Create separate group for the grouping attribute with NULLvalues

  • 8/3/2019 Lesson 09 - SQL

    38/46

    38

    GROUP BY For each department, retrieve the

    department number, the number of

    employees in the department, and theiraverage salary

    SELECT DNO, COUNT(*),AVG(SALARY)

    FROM EMPLOYEE

    GROUP BYDNO;

  • 8/3/2019 Lesson 09 - SQL

    39/46

    39

    HAVING Clause Used with GROUP BY clause

    Provides a condition on the sub relations or

    groups Groups satisfying the conditions are selected

  • 8/3/2019 Lesson 09 - SQL

    40/46

    40

    Having For each project on which more than two employees

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

    SELECT PNUMBER, PNAME, COUNT(*)

    FROM PROJECT, WORKS_ON

    WHERE PNUMBER=PNO

    GROUP BYPNUMBER, PNAME

    HAVING COUNT(*)>2;

  • 8/3/2019 Lesson 09 - SQL

    41/46

    41

    HAVING and COUNT SELECT DNUMBER, COUNT (*)

    FROM DEPARTMENT, EMPLOYEE

    WHERE DNUMBER=DNOANDSALARY>4000AND DNO IN (SELECT DNO FROM EMPLOYEE

    GROUP BY DNO HAVING COUNT(*)>5)

    GROUP BYDNNUMBER

  • 8/3/2019 Lesson 09 - SQL

    42/46

    42

    Insert, Delete, and Update The Insert Command

    To add a new tuple to employee INSERT INTO EMPLOYEEVALUES(1, John, Smith,12/07/1980,10))

    To enter a new tuple with knownattributes INSERT INTO EMPLOYEE (EmpID,

    FirstName, LastName)

    VALUES (3,John, Smith);

  • 8/3/2019 Lesson 09 - SQL

    43/46

    43

    Insert Multiple tuples INSERT command can be used to load

    multiple tuples as the same time Suppose

    CREAT TABLE DEPT_INFO (DEPT_NAME VARCHAR(15),

    NO_OF_EMPS INTEGER,TOTAL_SAL INTEGER);

    INSERT INTO DEPTS_INF (DEPT_NAME, NO_OF_EMPS,TOTAL_SAL)

    SELECT DNAME, COUNT(*), SUM (SALARY)FROM (DEPARTMENT JOIN EMPLOYEE ON

    DNUMBER=DNO)GROUP BY DNAME;

  • 8/3/2019 Lesson 09 - SQL

    44/46

    44

    The DELECT Command Removes tuples from a relation one at a

    time

    DELETE FROM EMPLOYEE

    WHERE LNAME=Brown

    Deletion can be cascaded to other relations

    using referential triggered actions specifiedin schema

  • 8/3/2019 Lesson 09 - SQL

    45/46

    45

    DELETE One or more tuples can be deleted

    E.g.. Delete all employees who work for

    research dept. DELETE FROM EMPLOYEE

    WHERE DNO IN

    (SELECT DNUMBER

    FROM DEPARTMENT

    WHERE DNAME=Research);

  • 8/3/2019 Lesson 09 - SQL

    46/46

    46

    UPDATE Command

    Used to modify values of one (or multiple)

    selected tuples associated with ONE relation E.g.,

    Change the location and controlling departmentnumber of project number 10 to Grand Forks and5

    UPDATE PROJECT

    SET PLOCATION = Grand Forks, DNUM=5

    WHERE PNUMBER=10;