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

Week5 Lecture

The document discusses the introduction to databases course and provides information on the professor, program, and session. It covers Structured Query Language (SQL) and chapter 5, providing background on the history of SQL and popular databases and programming languages. Examples are given of using SQL data definition language to create tables in a sample boating club database.

Uploaded by

ahmed lahlou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Week5 Lecture

The document discusses the introduction to databases course and provides information on the professor, program, and session. It covers Structured Query Language (SQL) and chapter 5, providing background on the history of SQL and popular databases and programming languages. Examples are given of using SQL data definition language to create tables in a sample boating club database.

Uploaded by

ahmed lahlou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Course

Introduction to Databases

Professor: Karima Echihabi


Program: Computer Engineering
Session: Fall 2023

1
Databases
Structured Query Language (SQL)
Chapter 5

2
History
• Developed at IBM in 1970’s as part of System R (vs. Quel in Ingres)
• Theoretical relational model has real practical importance
• Keep in mind that SQL does not strictly implement the relational model
• Became popular in 1980’s
• Oracle was first to sell an SQL database
• 40+ years of existence and still relevant today, despite:
• 90’s: Object-Oriented DBMS
• 2000’s: XML
• 2010’s: NoSQL and MapReduce
Most Popular Databases

4
Source: Stackoverflow, 2020
Most Popular Languages

5
Source: Stackoverflow, 2020
SQL is here to stay!

• Principles and ideas behind relational databases still apply to


virtually “all” forms of data management:
• Avoid redundancy and inconsistency
• Enable rich (declarative) access to the data
• Synchronize concurrent data access
• Recover after system failures
• Guarantee Security and privacy
• Facilitate reuse of the data
• Make user’s lives easier!

6
Review

• A database is a large, integrated collection of data.


• A relational database consists of a set of relations (tables)
• A relation consists of a schema (description) and an instance (data)
• A Database Management System (DBMS) is a software package
designed to store and manage databases.

7
Review

• A database is a large, integrated collection of data.


• A relational database consists of a set of relations (tables)
• A relation consists of a schema (description) and an instance (data)
• A Database Management System (DBMS) is a software package
designed to store and manage databases.
Attribute (Column, Field)

sid bid day


22 101 10/10/96
58 103 11/12/96
8
Review

• A database is a large, integrated collection of data.


• A relational database consists of a set of relations (tables)
• A relation consists of a schema (description) and an instance (data)
• A Database Management System (DBMS) is a software package
designed to store and manage databases.

sid bid day


Tuple (Row, Record ) 22 101 10/10/96
58 103 11/12/96 9
Review

• A relational table
• Fixed schema
• Variable instance
• Attributes
• Unique names
• Atomic types
• Tuples:
• Set in relational, multiset in SQL (duplicates allowed)

10
SQL Language
• Four main components:
• Data Definition Language (DDL) to define/modify schemas (add/delete
tables/columns/views/indexes) and specify constraints
• Data Manipulation Language (DML) to manipulate the data
(insert/delete/modify/query rows)
• Data Control Language (DCL)
• Transaction Control Language (TCL)
• Declarative!
• The user tells the RDBMS what it wants not how to get it.
• The RDBMS decides which algorithms/data structures to use to answer a
query

11
SQL Language Overview

[1] https://www.w3schools.in/mysql/ddl-dml-dcl

Create/delete/modify the data structures

12
SQL Language Overview

[1] https://www.w3schools.in/mysql/ddl-dml-dcl

13
Manipulate the data/query
SQL Language Overview

[1] https://www.w3schools.in/mysql/ddl-dml-dcl

Rights/permissions and other controls

14
SQL Language Overview

[1] https://www.w3schools.in/mysql/ddl-dml-dcl

Control transactions

15
SQL Language Overview

[1] https://www.w3schools.in/mysql/ddl-dml-dcl

Week 10
Week 6

Week4

16
Weeks 4 & 5
SQL DDL Example
• Given the following instances of the relations Sailors, Boats and Reserves
that belong to the BoatingClub database
Sailors Boats
sid sname rating age bid bname color
1 Mohamed 6 60 101 Boughaz blue
2 Amina 2 22 102 Battouta red
3 Imane 7 30 103 Intilaqa green
4 Ahmed 2 45 104 Flouqa red

Reserves
sid bid day
1 101 28/02/2023
3 101 25/02/2023
17
SQL DDL Example
• Drop/Create/Rename/Select a database

DROP DATABASE Boating_Club;

CREATE DATABASE Boating_Club;

RENAME DATABASE Boating_Club To BoatingClub;

USE BoatingClub;

18
SQL DDL Example
CREATE TABLE Sailors
Sailors sid sname rating age ( sid INTEGER,
1 Mohamed 6 60 sname CHAR(30),
rating INTEGER,
2 Amina 2 22 age FLOAT,
PRIMARY KEY (sid)
3 Imane 7 30 );
4 Ahmed 2 45

19
SQL DDL Example
CREATE TABLE Sailors
Sailors sid sname rating age ( sid INTEGER,
1 Mohamed 6 60 sname CHAR(30),
rating INTEGER,
2 Amina 2 22 age FLOAT,
PRIMARY KEY (sid)
3 Imane 7 30 );
4 Ahmed 2 45
CREATE TABLE Boats
Boats bid bname color ( bid INTEGER,
bname CHAR(20),
101 Boughaz blue color CHAR (10),
PRIMARY KEY (bid)
102 Battouta red );
103 Intilaqa green
104 Flouqa red

20
SQL DDL Example
CREATE TABLE Sailors
Sailors sid sname rating age ( sid INTEGER,
1 Mohamed 6 60 sname CHAR(30),
rating INTEGER,
2 Amina 2 22 age FLOAT,
PRIMARY KEY (sid)
3 Imane 7 30 );
4 Ahmed 2 45
CREATE TABLE Boats
Boats bid bname color ( bid INTEGER,
bname CHAR(20),
101 Boughaz blue color CHAR (10),
PRIMARY KEY (bid)
102 Battouta red );
103 Intilaqa green
104 Flouqa red
Reserves sid bid day
1 101 28/02/2023
3 101 25/02/2023 21
SQL DDL Example
CREATE TABLE Sailors
Sailors sid sname rating age ( sid INTEGER,
1 Mohamed 6 60 sname CHAR(30),
rating INTEGER,
2 Amina 2 22 age FLOAT,
PRIMARY KEY (sid)
3 Imane 7 30 );
4 Ahmed 2 45
CREATE TABLE Boats
Boats bid bname color ( bid INTEGER,
bname CHAR(20),
101 Boughaz blue color CHAR (10),
PRIMARY KEY (bid)
102 Battouta red );
103 Intilaqa green
104 Flouqa red CREATE TABLE Reserves
( sid INTEGER,
Reserves bid INTEGER,
sid bid day day DATE,
1 101 28/02/2023 PRIMARY KEY (bid,day),
FOREIGN KEY (sid) REFERENCES Sailors (sid),
3 101 25/02/2023 FOREIGN KEY (bid) REFERENCES Boats (bid) 22
);
SQL DDL Example
• Some other table-related DDL statements (non-exhaustive):

DROP TABLE Sailors; //delete entire table

ALTER TABLE ADD column-name column-type;

ALTER TABLE MODIFY column-name column-type;

ALTER TABLE DROP COLUMN column-name;

23
SQL DDL Example
• Indexes/Views:

CREATE INDEX index-name ON table-name (column-list);

ALTER TABLE table-name ADD INDEX index-name (column-list);

DROP INDEX index-name ON table-name;

CREATE VIEW view-name AS sql-query; //a view is a virtual table defined using an SQL statement

24
Integrity Constraints (Review)

• An IC describes conditions that every legal instance of a relation


must satisfy.
• Inserts/deletes/updates that violate IC’s are disallowed.
• Can be used to ensure application semantics (e.g., sid is a key), or
prevent inconsistencies (e.g., sname has to be a string, age must be <
200)
• Types of IC’s: Domain constraints, primary key constraints, foreign
key constraints, general constraints.
• Domain constraints: Field values must be of right type. Always enforced.

25
General Constraints
CREATE TABLE Sailors
• Useful when more ( sid INTEGER,
general ICs than keys sname CHAR(30),
rating INTEGER,
are involved. age FLOAT,
PRIMARY KEY (sid),
• Can use queries to CHECK (rating > =1 AND rating <= 10)
express constraint. );

• Constraints can be CREATE TABLE Reserves


named. ( sid INTEGER,
bid INTEGER,
day DATE,
PRIMARY KEY (bid,day),
FOREIGN KEY (sid) REFERENCES Sailors,
FOREIGN KEY (bid) REFERENCES Boats,
CONSTRAINT noBattoutaReservation
CHECK (‘Battouta’ <>
( SELECT B.bname
FROM Boats B
WHERE B.bid = bid))
);
SQL DML Overview
• Some DML statements (non-exhaustive):

SELECT column-list FROM tables WHERE condition;

INSERT INTO table_name (column1, column2, column3....) VALUES (value1, value2, value3.....);

DELETE FROM TABLE table-name; //delete all rows

DELETE FROM TABLE table-name [WHERE condition]; //delete all rows that satisfy condition

TRUNCATE TABLE table-name; //removes all rows and frees space

27
SQL-DML: Basic SQL Query
SELECT [DISTINCT] target-list
FROM relation-list
[WHERE qualification]

• relation-list A list of relation names (possibly with a range-variable


after each name).
• target-list A list of attributes of relations in relation-list
• qualification Comparisons (Attr op const or Attr1 op Attr2, where
op is one of , , = , , ,  ) combined using AND, OR and
NOT.
• DISTINCT is an optional keyword indicating that the answer should
not contain duplicates. Default is that duplicates are not
eliminated!
28
Conceptual Evaluation Strategy

• Semantics of an SQL query defined in terms of the following


conceptual evaluation strategy:
• Compute the cross-product of relation-list.
• Discard resulting tuples if they fail qualifications.
• Delete attributes that are not in target-list.
• If DISTINCT is specified, eliminate duplicate rows.
• This strategy is probably the least efficient way to compute a
query! An optimizer will find more efficient strategies to compute
the same answers.

29
Query Examples – Simple Query
Sailors sid sname rating age
1 Mohamed 6 60
2 Amina 2 22
3 Imane 8 30
4 Ahmed 2 45

SELECT S.sname, S.rating SELECT S.rating SELECT DISTINCT S.rating


FROM Sailors S FROM Sailors S FROM Sailors S
WHERE age < 60; WHERE age < 60; WHERE age < 60;

sname rating rating rating


Amina 2 2 2
Imane 8 8 8
Ahmed 2 2
30
Query Examples – ORDER BY
Sailors sid sname rating age
1 Mohamed 6 60
2 Amina 2 22
3 Imane 8 30
4 Ahmed 2 45

SELECT S.sname, S.rating


FROM Sailors S
WHERE age < 60
ORDER BY S.rating, S.sname;

rating sname
2 Ahmed
2 Amina
8 Imane 31
Query Examples – ORDER BY
Sailors sid sname rating age
1 Mohamed 6 60
2 Amina 2 22
3 Imane 8 30
4 Ahmed 2 45

SELECT S.sname, S.rating SELECT S.sname, S.rating


FROM Sailors S FROM Sailors S
WHERE age < 60 WHERE age < 60
ORDER BY S.rating, S.sname; ORDER BY S.rating ASC, S.sname DESC;

rating sname rating sname


2 Ahmed 2 Amina
2 Amina 2 Ahmed
8 Imane 8 Imane 32
Expressions and Strings
SELECT S.age, age1=S.age-5, 2*S.age AS age2 SELECT S.age, age1=S.age-5, 2*S.age AS age2
FROM Sailors S FROM Sailors S
WHERE S.sname LIKE ‘B_%’ WHERE S.sname ~ ‘B.*’

• Illustrates use of arithmetic expressions and string pattern


matching: Find triples (of ages of sailors and two fields defined by
expressions) for sailors whose names begin and end with B and
contain at least three characters.
• AS and = are two ways to name fields in result.
• LIKE is used for string matching. `_’ stands for any one character
and `%’ stands for 0 or more arbitrary characters.
33
Query Examples – ORDER BY
Sailors sid sname rating age
1 Mohamed 6 60
2 Amina 2 22
3 Imane 8 30
4 Ahmed 2 45

SELECT S.sname, S.rating SELECT S.sname, S.rating SELECT S.sname, S.rating


FROM Sailors S FROM Sailors S FROM Sailors S
WHERE age < 60 WHERE age < 60 WHERE age < 60
ORDER BY S.rating, S.sname; ORDER BY S.rating ASC, S.sname DESC; ORDER BY S.rating, S.name
LIMIT 2;
rating sname rating sname rating sname
2 Ahmed 2 Amina 2 Amina
2 Amina 2 Ahmed 2 Ahmed
8 Imane 8 Imane 34
Query Examples – Aggregates
• Compute a summary of some arithmetic expression in SELECT
statement
• Example aggregates:
• COUNT(*), COUNT (column-name), COUNT([DISTINCT] column-name)
• AVG([DISTINCT] column-name)
• SUM([DISTINCT] column-name)
• MAX (column-name), MIN (column-name)
• Can produce one row of output or more (GROUP BY)
• GROUP BY partitions table into groups with same GROUP BY column value
• Number of rows = # of distinct group of values

35
Query Examples – GROUP BY
Sailors sid sname rating age
1 Mohamed 6 60
2 Amina 2 22
3 Imane 8 30
4 Ahmed 2 45

SELECT AVG (S.age) AS avg_age SELECT S.rating, SELECT S.sname, S.rating


FROM Sailors S AVG (S.age) AS avg_age FROM Sailors S
WHERE S.rating < 7; FROM Sailors S WHERE age < 60
WHERE S.rating < 7 ORDER BY S.rating, S.name
GROUP BY S.rating ; LIMIT 2;
avg_age rating avg_age rating sname
42.3 2 33.5 2 Amina
6 60 2 Ahmed
36
Query Examples – Aggregates

• HAVING predicate
• Filters groups
• Can only be used with GROUP BY
• Optional and applied after grouping and aggregation
• Can contain anything that can go in the SELECT target-list
• Can be used with WHERE clause

37
HAVING vs WHERE
WHERE HAVING

Filters rows Filters groups

Can be used without GROUP BY clause Can only be used with GROUP BY clause

Row functions Column functions

Can be used with SELECT, UPDATE, DELETE Can only be used with SELECT statements
statements
Applied before GROUP BY clause Applied after the GROUP BY clause

WHERE clause cannot include SQL Aggregate HAVING clause can include SQL Aggregate
functions functions

38
Query Examples – HAVING
Sailors sid sname rating age
1 Mohamed 6 60
2 Amina 2 22
3 Imane 8 30
4 Ahmed 2 45

SELECT S.rating, AVG (S.age) AS avg_age,


COUNT(*) AS cnt
FROM Sailors S
WHERE S.rating < 7
GROUP BY S.rating
HAVING COUNT(*) > 1;
rating avg_age cnt
2 33.5 2
39
Query Examples – DISTINCT Aggregates
Sailors sid sname rating age
1 Mohamed 6 60
2 Amina 2 22
3 Imane 8 30
4 Ahmed 2 45

SELECT COUNT(DISTINCT S.rating) as cnt SELECT DISTINCT COUNT(S.rating) as cnt


FROM Sailors S FROM Sailors S
WHERE age < 60; WHERE age < 60;

40
Query Examples – DISTINCT Aggregates
Sailors sid sname rating age
1 Mohamed 6 60
2 Amina 2 22
3 Imane 8 30
4 Ahmed 2 45

SELECT COUNT(DISTINCT S.rating) as cnt SELECT DISTINCT COUNT(S.rating) as cnt


FROM Sailors S FROM Sailors S
WHERE age < 60; WHERE age < 60;

cnt cnt
2 3

41
Summary
• Format DML query:
SELECT [DISTINCT] target-list
FROM relation-list
[WHERE predicate]
[GROUP BY column-list]
[HAVING predicate]
[ORDER BY column-list]
[LIMIT integer];

• Modern SQL extends the relational model


• Duplicate rows, aggregates, ordering
• The user tells the DBMS what he/she wants not how to execute it
• The DBMS is responsible for finding the fast way to execute the query

42
Summary
• How to interpret a query of the form: Specify table
FROM

Eliminate rows
SELECT [DISTINCT] target-list WHERE (satisfying the predicate)
FROM relation-list
[WHERE predicate] Eliminate columns
[GROUP BY column-list] SELECT (keep only columns listed in the target-list)
[HAVING predicate];

• Form groups and calculate aggregates


GROUP
BY
• Eliminate groups
HAVING • (satisfying the predicate)

• Eliminate duplicates
DISTINCT

43
A Note on Range Variables

• Really needed only if the same relation appears twice in the FROM
clause. The previous query can also be written as:

SELECT S.sname
FROM Sailors S, Reserves R It is good style,
however, to use
WHERE S.sid=R.sid AND bid=103
range variables
always!
OR SELECT sname
FROM Sailors, Reserves
WHERE Sailors.sid=Reserves.sid
AND bid=103

44
Triggers

• Trigger: procedure that starts automatically if specified changes


occur to the DBMS
• Three parts:
• Event (activates the trigger)
• Condition (tests whether the triggers should run)
• Action (what happens if the trigger runs)

45
Triggers: Example (SQL:1999)
CREATE TRIGGER youngSailorUpdate
AFTER INSERT ON SAILORS
REFERENCING NEW TABLE NewSailors
FOR EACH STATEMENT
INSERT
INTO YoungSailors(sid, name, age, rating)
SELECT sid, name, age, rating
FROM NewSailors N
WHERE N.age <= 18

46
Null Values
• Field values in a tuple are sometimes unknown (e.g., a rating has
not been assigned) or inapplicable (e.g., no spouse’s name).
• SQL provides a special value null for such situations.
• The presence of null complicates many issues. E.g.:
• Special operators needed to check if value is/is not null.
• Is rating>8 true or false when rating is equal to null? What about AND, OR
and NOT connectives?
• We need a 3-valued logic (true, false and unknown).
• Meaning of constructs must be defined carefully. (e.g., WHERE clause
eliminates rows that don’t evaluate to true.)
• New operators (in particular, outer joins) possible/needed.

47
Summary
• SQL was an important factor in the early acceptance of the
relational model; more natural than earlier, procedural query
languages.
• Relationally complete; in fact, significantly more expressive power
than relational algebra.
• Even queries that can be expressed in RA can often be expressed
more naturally in SQL.
• Many alternative ways to write a query; optimizer should look for
most efficient evaluation plan.
• In practice, users need to be aware of how queries are optimized and
evaluated for best results.

58
Summary (Contd.)

• NULL for unknown field values brings many complications


• SQL allows specification of rich integrity constraints
• Triggers respond to changes in the database

59

You might also like