Data Base Management Systems
        (DBMS) – (1)

         Code :   INF311

            Lecture 4
In this Lecture

Introduction to SQL
SQL

   SQL is acronym for
                    "Structured Query Language".
   SQL is a high-level language for defining,
    querying, modifying, and controlling the
    data in a relational database.

   SQL is not case sensitive (the verb
    SELECT is the same as verb SelEcT).
SQL Commands
Category                  SQL        Description
                          commands
                          CREATE     Creation of tables
Data Description (DDL)    ALTER      Modification of tables
                          DROP       Removal of tables
                          INSERT     Insertion of rows in a table
Data Manipulation (DML)   UPDATE     Update of rows in a table
                          DELETE     Removal of rows in a table
                          GRANT      Grant of access rights
                          REVOKE     Removal of access rights
Data Control (DCL)
                          COMMIT     Treatment of updates
                          ROLLBACK   Removal of updates
Interrogation             SELECT     Queries
Data Definition Language
The SQL data-definition language (DDL)
allows the specification of information about
relations, including:
   The schema for each relation.
   The domain of values associated with each attribute.
   Integrity constraints
   And as we will see later, also other information such as
     – The set of indices to be maintained for each relations.
     – Security and authorization information for each relation.
     – The physical storage structure of each relation on disk.
Domain Types in SQL
   char(n): Fixed length character string, with user-specified
    length n.
   varchar(n): Variable length character strings, with user-
    specified maximum length n.
   Int: Integer (a finite subset of the integers that is machine-
    dependent).
   Smallint: Small integer (a machine-dependent subset of the
    integer domain type).
   numeric(p,d): Fixed point number, with user-specified
    precision of p digits, with n digits to the right of decimal point.
   real, double precision: Floating point and double-
    precision floating point numbers, with machine-dependent
    precision.
   float(n): Floating point number, with user-specified precision
    of at least n digits.
   More are covered later.
Create Table Construct
   An SQL relation is defined using the create table
    command:
    create table r (A1 D1, A2 D2, ..., An Dn ,
                    (integrity-constraint1),
                           ...,
                    (integrity-constraintk) );
     – r is the name of the relation
     – each Ai is an attribute name in the schema of
       relation r
     – Di is the data type of values in the domain of
       attribute Ai
Integrity Constraints in Create Table

   not null

   primary key (A1, ..., An )

   foreign key (Am, ..., An ) references r

   Unique Key

   Check
Create Example 1

create table instructor (
  ID         char (5),
  name       varchar (20) not null ,
  dept_name varchar (20),
   salary    numeric (8,2) );
Create Example 2
   Declare dept_name as the primary key for
    department.

    create table instructor (
     ID        char (5),
     name       varchar (20) not null,
     dept_name varchar (20),
     salary     numeric (8,2),
     primary key (ID),
     foreign key (dept_name) references department );
   primary key declaration on an attribute automatically
    ensures not null
Create Example 3
Create table employee (
Fname varchar (20) NOT NULL ,
Lname varchar (20) NOT NULL ,
SSN char (9),
Bdate Date ,
Address varchar (30),
Sex Char NoT NULL ,
Salary decimal (10,2),
SuperSSN char (9),
Dno int NOT NULL ,
Primary key (SSN) );
And more still
   create table course (
    course_id      varchar (8) primary key ,
    title          varchar( 50),
    dept_name      varchar (20),
    credits        numeric (2,0),
     foreign key (dept_name) references
    department) );

   Primary key declaration can be combined with
    attribute declaration as shown above
Alter Table Constructs
   alter table r add A D ;
     – where A is the name of the attribute to be added
       to relation r and D is the domain of A.
     – All tuples in the relation are assigned null as the
       value for the new attribute.
   alter table r drop A ;
    – where A is the name of an attribute of relation r
    – Dropping of attributes not supported by many
      databases
Drop Table Constructs
   drop table table_name ;
     – Deletes the table and its contents

   delete from table_name ;
     – Deletes all contents of table, but retains table
Data Manipulation Language
   The DML provide Modification of the Database .
INSERT operation
   Add a new tuple to a table


INSERT
INTO table [ (field [,field] … )]
VALUES (literal[,literal ] …) ;
Insert examples
   insert into course (course_id, title, dept_name, credits)
          values (’CS-437’, ’Database Systems’, ’Comp. Sci.’,
    4);

   insert into course
         values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);

   insert into student
            values (’3003’, ’Green’, ’Finance’, null);

   insert into course (course_id, title)
          values (’CS-437’, ’Database Systems’);
UPDATE operation
   General format


UPDATE table
SET field = scalar-expression
    [, field = scalar-expression ] …..
[ WHERE condition ] ;
UPDATE examples
 Increase salaries of instructors whose salary is over
  $100,000 by 3%
update instructor
   set salary = salary * 1.03
    where salary > 100000;

   UPDATE Store_Information
    SET Sales = 500
    WHERE store_name = "Los Angeles"
    AND Date = "Jan-08-1999“;
DELETE operation
   Delete all records in a “table” that satisfy a
    “condition”
   General format


DELETE FROM table [ WHERE condition ] ;
DELETE examples
   Delete all instructors
               delete from instructor ;

   Delete all instructors from the Finance department
             delete from instructor
                   where dept_name= ’Finance’;
Interrogation operation
   Queries are done by using SELECT command
   The result of an SQL query is a relation.
   Syntax of the SELECT command


SELECT [DISTINCT ] {* | expr [AS alias], ... }
 FROM table [alias], ...
 [WHERE { conditions | under conditions} ]
 [GROUP BY expr, ...] [HAVING conditions]
 [ORDER BY {expr | num}{ASC | DESC }, ...];
SELECT command
   Syntactical agreements
    CAPITAL LETTERS : (SELECT) Enter values exactly as presented.
    Italic                     : column, table. Parameter having to be replaced
    by the suitable value.
    Alias                     : Synonym of a name of table or column.
    Conditions             : Expression having the true or false value.
    Under conditions     : Expression containing a subquery.
    Expr                      : Column, or calculated attribute (+,-, *, /)
    Num                              : Column number
    {}                          : Ex {ON|OFF}. One of the values separated by "|"
    must obligatory be typed in.
    [ ]                          : optional Value.
    ( )                          : the brackets and commas must be type in as
    presented.
    ...                           : The preceding values can be repeated several
    times
    _ Underlined            : indicate the default value.
The select Clause
   An asterisk in the select clause denotes “all
    attributes”
   To force the elimination of duplicates, insert the
    keyword distinct after select.
SQL: Projection
   The operation of projection consists in selecting the
    name of the columns of table(s) which one wishes
    to see appearing in the answer.
   If one wants to display all the columns "*" should be
    used.
   The columns are given after the SELECT clause.
Projection examples
Display the contents of the table STUDENT
SELECT *
 FROM STUDENT;

Display the Name and the ID of the students
SELECT st_name, st_id
  FROM STUDENT;
SQL: Selection
   The operation of selection consists in selecting
    rows (tuples) of one (or several) table(s) which
    satisfy certain conditions.

   The conditions are expressed after the WHERE
    clause.
Selection examples
Display the list of the students of male sex.
SELECT * 
 FROM STUDENT
 WHERE Cdsexe=‘M';

  Display department ID and name that are located in
   Cairo
Select dept_id, dept_name
from departments
where location = ‘Cairo’;
Projection and Selection
   The operations of projection and selection can
    obviously be used in the same SQL request.

   Display the number and the name of the students
    born in 1980

SELECT st_id, st_name
 FROM STUDENT
 WHERE Dtnaiss >= '1980-01-01' AND Dtnaiss <=
 '1980-12-31';
Comparison Conditions
   = Equal
   > greater than
   >= greater than or equal
   < less than
   <= less than or equal
   <> not equal

   Between …… AND ….. (between two values)
   IN (set) (Match any of a list of values)
   All ( set) (Match all values in the list)
Examples
  Select last_name, salary
from employees
where salary >1000 ;

   SELECT *
    FROM suppliers
    WHERE supplier_id between 5000 AND 5010;

 Select emp_id, last_name, salary, manager_id
From employees
where manager_id IN (100, 101, 200);
Logical Conditions
   AND
   OR
   NOT

Select emp_id, last_name, salary, manager_id
From employees
where manager_id NOT IN (100, 101, 200);
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;
Order by Clause

   Retrieval with ordering (ASC, DESC)
   ASC is the default

Select fname, dept_id, hire_date
from employees
Order by hire_date DESC;

Select fname, dept_id, salary
from employees
Order by dept_id, Salary ASC;
The FROM clause
   The from clause lists the relations involved in the
    query
     – Corresponds to the Cartesian product operation
       of the relational algebra.
   Find the Cartesian product instructor X teaches
                      select ∗
                      from instructor, teaches
     – generates every possible instructor – teaches
       pair, with all attributes from both relations
   Cartesian product not very useful directly, but useful
    combined with where-clause condition
Cartesian Product: instructor X teaches
     instructor              teaches
Next Lecture

   SQL more and more

Db1 lecture4

  • 1.
    Data Base ManagementSystems (DBMS) – (1) Code : INF311 Lecture 4
  • 2.
  • 3.
    SQL  SQL is acronym for "Structured Query Language".  SQL is a high-level language for defining, querying, modifying, and controlling the data in a relational database.  SQL is not case sensitive (the verb SELECT is the same as verb SelEcT).
  • 4.
    SQL Commands Category SQL Description commands CREATE Creation of tables Data Description (DDL) ALTER Modification of tables DROP Removal of tables INSERT Insertion of rows in a table Data Manipulation (DML) UPDATE Update of rows in a table DELETE Removal of rows in a table GRANT Grant of access rights REVOKE Removal of access rights Data Control (DCL) COMMIT Treatment of updates ROLLBACK Removal of updates Interrogation SELECT Queries
  • 5.
    Data Definition Language TheSQL data-definition language (DDL) allows the specification of information about relations, including:  The schema for each relation.  The domain of values associated with each attribute.  Integrity constraints  And as we will see later, also other information such as – The set of indices to be maintained for each relations. – Security and authorization information for each relation. – The physical storage structure of each relation on disk.
  • 6.
    Domain Types inSQL  char(n): Fixed length character string, with user-specified length n.  varchar(n): Variable length character strings, with user- specified maximum length n.  Int: Integer (a finite subset of the integers that is machine- dependent).  Smallint: Small integer (a machine-dependent subset of the integer domain type).  numeric(p,d): Fixed point number, with user-specified precision of p digits, with n digits to the right of decimal point.  real, double precision: Floating point and double- precision floating point numbers, with machine-dependent precision.  float(n): Floating point number, with user-specified precision of at least n digits.  More are covered later.
  • 7.
    Create Table Construct  An SQL relation is defined using the create table command: create table r (A1 D1, A2 D2, ..., An Dn , (integrity-constraint1), ..., (integrity-constraintk) ); – r is the name of the relation – each Ai is an attribute name in the schema of relation r – Di is the data type of values in the domain of attribute Ai
  • 8.
    Integrity Constraints inCreate Table  not null  primary key (A1, ..., An )  foreign key (Am, ..., An ) references r  Unique Key  Check
  • 9.
    Create Example 1 createtable instructor ( ID char (5), name varchar (20) not null , dept_name varchar (20), salary numeric (8,2) );
  • 10.
    Create Example 2  Declare dept_name as the primary key for department. create table instructor ( ID char (5), name varchar (20) not null, dept_name varchar (20), salary numeric (8,2), primary key (ID), foreign key (dept_name) references department );  primary key declaration on an attribute automatically ensures not null
  • 11.
    Create Example 3 Createtable employee ( Fname varchar (20) NOT NULL , Lname varchar (20) NOT NULL , SSN char (9), Bdate Date , Address varchar (30), Sex Char NoT NULL , Salary decimal (10,2), SuperSSN char (9), Dno int NOT NULL , Primary key (SSN) );
  • 12.
    And more still  create table course ( course_id varchar (8) primary key , title varchar( 50), dept_name varchar (20), credits numeric (2,0), foreign key (dept_name) references department) );  Primary key declaration can be combined with attribute declaration as shown above
  • 13.
    Alter Table Constructs  alter table r add A D ; – where A is the name of the attribute to be added to relation r and D is the domain of A. – All tuples in the relation are assigned null as the value for the new attribute.  alter table r drop A ; – where A is the name of an attribute of relation r – Dropping of attributes not supported by many databases
  • 14.
    Drop Table Constructs  drop table table_name ; – Deletes the table and its contents  delete from table_name ; – Deletes all contents of table, but retains table
  • 15.
    Data Manipulation Language  The DML provide Modification of the Database .
  • 16.
    INSERT operation  Add a new tuple to a table INSERT INTO table [ (field [,field] … )] VALUES (literal[,literal ] …) ;
  • 17.
    Insert examples  insert into course (course_id, title, dept_name, credits) values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);  insert into course values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);  insert into student values (’3003’, ’Green’, ’Finance’, null);  insert into course (course_id, title) values (’CS-437’, ’Database Systems’);
  • 18.
    UPDATE operation  General format UPDATE table SET field = scalar-expression [, field = scalar-expression ] ….. [ WHERE condition ] ;
  • 19.
    UPDATE examples  Increasesalaries of instructors whose salary is over $100,000 by 3% update instructor set salary = salary * 1.03 where salary > 100000;  UPDATE Store_Information SET Sales = 500 WHERE store_name = "Los Angeles" AND Date = "Jan-08-1999“;
  • 20.
    DELETE operation  Delete all records in a “table” that satisfy a “condition”  General format DELETE FROM table [ WHERE condition ] ;
  • 21.
    DELETE examples  Delete all instructors delete from instructor ;  Delete all instructors from the Finance department delete from instructor where dept_name= ’Finance’;
  • 22.
    Interrogation operation  Queries are done by using SELECT command  The result of an SQL query is a relation.  Syntax of the SELECT command SELECT [DISTINCT ] {* | expr [AS alias], ... } FROM table [alias], ... [WHERE { conditions | under conditions} ] [GROUP BY expr, ...] [HAVING conditions] [ORDER BY {expr | num}{ASC | DESC }, ...];
  • 23.
    SELECT command  Syntactical agreements CAPITAL LETTERS : (SELECT) Enter values exactly as presented. Italic                     : column, table. Parameter having to be replaced by the suitable value. Alias                     : Synonym of a name of table or column. Conditions             : Expression having the true or false value. Under conditions     : Expression containing a subquery. Expr                      : Column, or calculated attribute (+,-, *, /) Num                              : Column number {}                          : Ex {ON|OFF}. One of the values separated by "|" must obligatory be typed in. [ ]                          : optional Value. ( )                          : the brackets and commas must be type in as presented. ...                           : The preceding values can be repeated several times _ Underlined            : indicate the default value.
  • 24.
    The select Clause  An asterisk in the select clause denotes “all attributes”  To force the elimination of duplicates, insert the keyword distinct after select.
  • 25.
    SQL: Projection  The operation of projection consists in selecting the name of the columns of table(s) which one wishes to see appearing in the answer.  If one wants to display all the columns "*" should be used.  The columns are given after the SELECT clause.
  • 26.
    Projection examples Display thecontents of the table STUDENT SELECT * FROM STUDENT; Display the Name and the ID of the students SELECT st_name, st_id FROM STUDENT;
  • 27.
    SQL: Selection  The operation of selection consists in selecting rows (tuples) of one (or several) table(s) which satisfy certain conditions.  The conditions are expressed after the WHERE clause.
  • 28.
    Selection examples Display thelist of the students of male sex. SELECT *  FROM STUDENT WHERE Cdsexe=‘M';  Display department ID and name that are located in Cairo Select dept_id, dept_name from departments where location = ‘Cairo’;
  • 29.
    Projection and Selection  The operations of projection and selection can obviously be used in the same SQL request.  Display the number and the name of the students born in 1980 SELECT st_id, st_name FROM STUDENT WHERE Dtnaiss >= '1980-01-01' AND Dtnaiss <= '1980-12-31';
  • 30.
    Comparison Conditions  = Equal  > greater than  >= greater than or equal  < less than  <= less than or equal  <> not equal  Between …… AND ….. (between two values)  IN (set) (Match any of a list of values)  All ( set) (Match all values in the list)
  • 31.
    Examples  Selectlast_name, salary from employees where salary >1000 ;  SELECT * FROM suppliers WHERE supplier_id between 5000 AND 5010;  Select emp_id, last_name, salary, manager_id From employees where manager_id IN (100, 101, 200);
  • 32.
    Logical Conditions  AND  OR  NOT Select emp_id, last_name, salary, manager_id From employees where manager_id NOT IN (100, 101, 200);
  • 33.
    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;
  • 34.
    Order by Clause  Retrieval with ordering (ASC, DESC)  ASC is the default Select fname, dept_id, hire_date from employees Order by hire_date DESC; Select fname, dept_id, salary from employees Order by dept_id, Salary ASC;
  • 35.
    The FROM clause  The from clause lists the relations involved in the query – Corresponds to the Cartesian product operation of the relational algebra.  Find the Cartesian product instructor X teaches select ∗ from instructor, teaches – generates every possible instructor – teaches pair, with all attributes from both relations  Cartesian product not very useful directly, but useful combined with where-clause condition
  • 36.
    Cartesian Product: instructorX teaches instructor teaches
  • 37.
    Next Lecture  SQL more and more