1
02 Introduction to Relational
           Model
          CRI2E4 Basis Data
                                                           2
    Learning Outcomes
Students can explain and understand the Relational Model
            Outline
                                    3
Structure of Relational Databases
Database Schema
Keys
Schema Diagram
                          4
Structure of Relational
      Databases
                             Basic Concepts
                                                  5
•   A relational database consists of a
    collection of tables, each of which is
    assigned a unique name.
•   A row in a table represents a
    relationship among a set of values.
•   In mathematical terminology, a tuple is
    simply a sequence (or list) of values.
•   Thus, in the relational model the term
    relation is used to refer to a table, while
    the term tuple is used to refer to a row.
    Similarly, the term attribute refers to a
    column of a table.
            Relation Schema and Instances
                                                                            6
•   A1, A2, …, An are attributes
•   R = (A1, A2, …, An ) is a relation schema
    Example:
          instructor = (ID, name, dept_name, salary)
•   Relations are unordered. Order of tuples is irrelevant (tuples may be
    stored in an arbitrary order)
    Example: instructor relation with unordered tuples
                                Attributes
                                                                                   7
•   The set of allowed values for each attribute is called the domain of the
    attribute
•   Attribute values are (normally) required to be atomic; that is, indivisible
•   The special value null is a member of every domain. Indicated that the value
    is “unknown”
•   The null value causes complications in the definition of many operations
Example of a Instructor Relation
                                          8
                             attributes
                           (or columns)
                             tuples
                           (or rows)
                  9
Database Schema
                             Database Schema
                                                                                10
•   Database schema -- is the logical structure of the database.
•   Database instance -- is a snapshot of the data in the database at a given
    instant in time.
•   Example:
    schema: instructor (ID, name, dept_name, salary)
    Instance:
       11
Keys
                                      Keys
                                                                                        12
•   Let K  R
•   K is a superkey of R if values for K are sufficient to identify a unique tuple of
    each possible relation r(R)
•   Superkey K is a candidate key if K is minimal
•   One of the candidate keys is selected to be the primary key. Primary key
    attributes are also underlined.
•   The primary key should be chosen such that its attribute values are never, or
    are very rarely, changed.
•   Foreign key constraint: Value in one relation must appear in another
    • Referencing relation
    • Referenced relation
•   Note that in a foreign-key constraint, the referenced attribute(s) must be the
    primary key of the referenced relation.
                 13
Schema Diagram
                          Schema Diagram
                                                                                 14
•   A database schema, along with primary key and foreign-key constraints, can
    be depicted by schema diagrams.
                                                                         15
                             References
[1] Silberschatz, Korth, and Sudarshan. Database System Concepts – 7th
    Edition. McGraw-Hill. 2019.
[2] Slides adapted from Database System Concepts Slide.
    Source: https://db-book.com/slides-dir/index.html
Questions
            16
                           1
02 Introduction to SQL
       CRI2E4 Basis Data
                                                            2
     Learning Outcomes
Students can explain and understand DDL, DML, Basic query
                         structure
            Outline
                                 3
Overview of SQL Query Language
SQL Data Definition
Basic Structure of SQL Queries
Modification of the Database
                        4
Overview of SQL Query
      Language
                                      History
                                                                               5
•   IBM Sequel language developed as part of System R project at the IBM San
    Jose Research Laboratory
•   Renamed Structured Query Language (SQL)
•   ANSI and ISO standard SQL:
    •   SQL-86
    •   SQL-89
    •   SQL-92
    •   SQL:1999 (language name became Y2K compliant!)
    •   SQL:2003
•   Many products now support the SQL language.
•   SQL has clearly established itself as the standard relational database
    language.
                                       SQL Parts
                                                                                                      6
The SQL language has several parts:
•   Data-definition language (DDL). The SQL DDL provides commands for defining relation
    schemas, deleting relations, and modifying relation schemas.
•   Data-manipulation language (DML). The SQL DML provides the ability to query information
    from the database and to insert tuples into, delete tuples from, and modify tuples in the
    database.
•   Integrity. The SQL DDL includes commands for specifying integrity constraints that the data
    stored in the database must satisfy. Updates that violate integrity constraints are disallowed.
•   View definition. The SQL DDL includes commands for defining views.
•   Transaction control. SQL includes commands for specifying the beginning and end points of
    transactions.
•   Embedded SQL and dynamic SQL. Embedded and dynamic SQL define how SQL statements
    can be embedded within general-purpose programming languages, such as C, C++, and Java.
•   Authorization. The SQL DDL includes commands for specifying access rights to relations
    and views.
                      7
SQL Data Definition
                           SQL Data Definition
                                                                                8
•   The set of relations in a database are specified using a data-definition
    language (DDL).
•   The SQL DDL allows specification of not only a set of relations, but also
    information about each relation, including:
    •   The schema for each relation.
    •   The types of values associated with each attribute
    •   The Integrity constraints
    •   The set of indices to be maintained for each relation.
    •   Security and authorization information for each relation.
    •   The physical storage structure of each relation on disk.
                                Basic Types
                                                                                      9
•   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 d digits to the right of decimal point. (ex., numeric(3,1), allows 44.5 to
    be stores exactly, but not 444.5 or 0.32)
•   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.
                        Basic Schema Definition
                                                                  10
•   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
•   Example:
                 create table instructor (
                    ID            char(5),
                    name          varchar(20),
                    dept_name varchar(20),
                    salary        numeric(8,2))
           Integrity Constraints in Create Table
                                                                                     11
•   Types of integrity constraints
    • primary key (A1, ..., An )
    • foreign key (Am, ..., An ) references r
    • not null
•   SQL prevents any update to the database that violates an integrity constraint.
•   Example:
     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);
•   Try to create 4 other tables in the university database
                                Update to Tables
                                                                                                     12
•   Insert
    • insert into instructor values ('10211', 'Smith', 'Biology', 66000);
•   Delete : Remove all tuples from the relation
        • delete from r
•   Drop Table : Remove a relation from an SQL database
       • drop table r
•   Alter
    • 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 exiting 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.
                         13
Basic Structure of SQL
       Queries
                       Basic Query Structure
                                                14
•   A typical SQL query has the form:
                select A1, A2, ..., An
                from r1, r2, ..., rm
                where P
    • Ai represents an attribute
    • Ri represents a relation
    • P is a predicate.
•   The result of an SQL query is a relation.
                               The Select Cause
                                                                                             15
•   The select clause lists the attributes desired in the result of a query
    • corresponds to the projection operation of the relational algebra
•   Example: find the names of all instructors:
                       select name
                       from instructor
•   NOTE: SQL names are case insensitive (i.e., you may use upper- or lower-case letters.)
    E.g., Name ≡ NAME ≡ name
                     The Select Cause (cont.)
                                                                                16
•   SQL allows duplicates in relations as well as in query results.
•   To force the elimination of duplicates, insert the keyword distinct after
    select.
•   Find the department names of all instructors, and remove duplicates
                select distinct dept_name
                from instructor
                       The Select Cause (cont.)
                                                                                          17
•   An asterisk in the select clause denotes “all attributes”
                        select *
                        from instructor
•   An attribute can be a literal with no from clause
                        select '437'
    • Results is a table with one column and a single row with value “437”
    • Can give the column a name using:
                select '437' as FOO
•   An attribute can be a literal with from clause
                        select 'A'
                        from instructor
    • Result is a table with one column and N rows (number of tuples in the instructors
      table), each row with value “A”
                       The Select Cause (cont.)
                                                                                                 18
•   The select clause can contain arithmetic expressions involving the operation, +, –, , and
    /, and operating on constants or attributes of tuples.
•   The query:
                 select ID, name, salary/12
                 from instructor
    would return a relation that is the same as the instructor relation, except that the value
    of the attribute salary is divided by 12.
•   Can rename “salary/12” using the as clause:
           select ID, name, salary/12 as monthly_salary
                             The Where Clause
                                                                                          19
•   The where clause specifies conditions that the result must satisfy
    • Corresponds to the selection predicate of the relational algebra.
•   To find all instructors in Comp. Sci. dept
           select name
           from instructor
           where dept_name = 'Comp. Sci.'
•   SQL allows the use of the logical connectives and, or, and not
•   The operands of the logical connectives can be expressions involving the comparison
    operators <, <=, >, >=, =, and <>.
•   Comparisons can be applied to results of arithmetic expressions
•   To find all instructors in Comp. Sci. dept with salary > 70000
      select name
      from instructor
      where dept_name = 'Comp. Sci.' and salary > 70000
                              The From Clause
                                                                                            20
•   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.
    • For common attributes (e.g., ID), the attributes in the resulting table are renamed
      using the relation name (e.g., instructor.ID)
•   Cartesian product not very useful directly, but useful combined with where-clause
    condition (selection operation in relational algebra).
                                Examples
                                                 21
•   Find the names of all instructors who have
    taught some course and the course_id
    • select name, course_id
       from instructor , teaches
       where instructor.ID = teaches.ID
                                     Examples
                                                       22
•   Find the names of all instructors in the Art
    department who have taught some course and
    the course_id
    • select name, course_id
       from instructor , teaches
       where instructor.ID = teaches.ID
            and instructor. dept_name = ‘Comp. Sci.'
                Additional Basic Operations
                                              23
•   Rename operations
•   String operations
•   Ordering the Display of Tuples
•   Where-Clause Predicates
                        Rename Operations
                                                                                      24
•   The SQL allows renaming relations and attributes using the as clause:
                old-name as new-name
•   Find the names of all instructors who have a higher salary than some instructor
    in 'Comp. Sci'.
    • select distinct T.name
       from instructor as T, instructor as S
       where T.salary > S.salary and S.dept_name = 'Comp. Sci.’
•   Keyword as is optional and may be omitted
          instructor as T ≡ instructor T
                            String Operations
                                                                                        25
•   SQL includes a string-matching operator for comparisons on character strings. The
    operator like uses patterns that are described using two special characters:
    • percent ( % ). The % character matches any substring.
    • underscore ( _ ). The _ character matches any character.
•   Find the names of all instructors whose name includes the substring “dar”.
                select name
                from instructor
                where name like '%dar%'
•   Match the string “100%”
                    like '100 \%' escape '\'
    in that above we use backslash (\) as the escape character.
                       String Operations (cont.)
                                                                      26
•   Patterns are case sensitive.
•   Pattern matching examples:
    • 'Intro%' matches any string beginning with “Intro”.
    • '%Comp%' matches any string containing “Comp” as a substring.
    • '_ _ _' matches any string of exactly three characters.
    • '_ _ _ %' matches any string of at least three characters.
•   SQL supports a variety of string operations such as
    • concatenation (using “||”)
    • converting from upper to lower case (and vice versa)
    • finding string length, extracting substrings, etc.
                Ordering the Display of Tuple
                                                                                    27
•   List in alphabetic order the names of all instructors
       select distinct name
       from instructor
       order by name
•   We may specify desc for descending order or asc for ascending order, for each
    attribute; ascending order is the default.
    • Example: order by name desc
•   Can sort on multiple attributes
    • Example: order by dept_name, name
                   Where Clauses Predicates
                                                                                 28
•   SQL includes a between comparison operator
•   Example: Find the names of all instructors with salary between $90,000 and
    $100,000 (that is,  $90,000 and  $100,000)
    • select name
      from instructor
      where salary between 90000 and 100000
•   Tuple comparison
    • select name, course_id
      from instructor, teaches
      where (instructor.ID, dept_name) = (teaches.ID, 'Biology');
                      29
Modification of the
   Database
                                    Deletion
                                                                                           30
•   Delete all instructors
             delete from instructor
•   Delete all instructors from the Finance department
                delete from instructor
                where dept_name= 'Finance’;
•   Delete all tuples in the instructor relation for those instructors associated with a
    department located in the Watson building.
                 delete from instructor
                 where dept name in (select dept name
                                      from department
                                      where building = 'Watson');
                                  Insertion
                                                                     31
•   Add a new tuple to course
      insert into course
          values ('CS-437', 'Database Systems', 'Comp. Sci.', 4);
•   or equivalently
       insert into course (course_id, title, dept_name, credits)
           values ('CS-437', 'Database Systems', 'Comp. Sci.', 4);
•   Add a new tuple to student with tot_creds set to null
      insert into student
          values ('3003', 'Green', 'Finance', null);
                                  Updates
                                                                              32
•   Give a 5% salary raise to all instructors
            update instructor
            set salary = salary * 1.05
•   Give a 5% salary raise to those instructors who earn less than 70000
            update instructor
            set salary = salary * 1.05
            where salary < 70000;
•   Give a 5% salary raise to instructors whose salary is less than average
              update instructor
              set salary = salary * 1.05
              where salary < (select avg (salary)
                           from instructor);
                                                                         33
                             References
[1] Silberschatz, Korth, and Sudarshan. Database System Concepts – 7th
    Edition. McGraw-Hill. 2019.
[2] Slides adapted from Database System Concepts Slide.
    Source: https://db-book.com/slides-dir/index.html
Questions
            34