SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
1
Course Name: Database Management System
Course Code: CT – 2212
Chapter Eight
SQL (Structured query language)
Denekew Tadele (Maj.)
Tel: +251913793506
Email: denekew.tad@gmail.com
Contents
 The SQL Query Language
 Data Definition
 Basic Query Structure
 Additional Basic Operations
 Set Operations
 Aggregate Functions
2
3
• Structured Query Language (SQL) is the
standard language for accessing information a
database.
• Terminology:
• Syntax notes:
 Some interfaces require each statement
to end with a semicolon.
 SQL is not case-sensitive
Structured Query Language
Relational Model SQL
relation table
tuple row
attribute column
SQL Environment
• Data Definition Language (DDL)
- Commands that define a database, including creating,
altering, and dropping tables and establishing constraints
- CREATE / DROP / ALTER, …
• Data Manipulation Language (DML)
- Commands that maintain and query a database
- INSERT, UPDATE, DELETE, SELECT, …
• Data Control Language (DCL)
- Commands that control a database, including administering
privileges and committing data
- GRANT, ADD, REVOKE
4
SQL Data Definition
• Data Definition Language (DDL)
• Major CREATE statements:
- CREATE TABLE–defines a new table and its columns
- CREATE VIEW–defines a logical table from one or more tables or views
5
Steps in table creation:
1. Identify data types for attributes
2. Identify columns that can and
cannot be null
3. Identify columns that must be
unique (candidate keys)
4. Identify primary key
5. Determine default values
6. Identify constraints on columns
(domain specifications)
7. Identify foreign keys
General syntax for CREATE
TABLE
used in data definition language
CREATE TABLE table_name (
field type constraints,
field2 type2,
CONSTRAINT name ...,
...
);
CREATE TABLE Book (
ISBN CHAR(9) NOT NULL,
Title VARCHAR(20) UNIQUE,
Pages INTEGER,
CONSTRAINT ISBN PRIMARY KEY
);
SQL Data Types
6
TABLE 1 Sample SQL Data Types
7
Basic Data Types
 Numeric data types
• Integer numbers: INT, INTEGER, SMALLINT, BIGINT
• Floating-point (real) numbers: REAL, DOUBLE , FLOAT
• Fixed-point numbers: DECIMAL(n,m), DEC(n,m),
NUMERIC(n,m), NUM(n,m)
• Character-string data types
• Fixed length: CHAR(n), CHARACTER(n)
• Varying length: VARCHAR(n), CHAR VARYING(n), CHARACTER
VARYING(n), LONG VARCHAR
 Large object data types
• Characters: CLOB, CHAR LARGE OBJECT , CHARACTER LARGE
OBJECT
• Bits: BLOB, BINARY LARGE OBJECT
 Boolean data type
• Values of TRUE or FALSE or NULL
 DATE data type
• T
en positions
• Components are YEAR, MONTH, and DAY in the form YYYY-MM-DD
More DataTypes
8
 Additional data types
• TIMESTAMPdata type
• Includes the DATE and TIMEfields
• Plus a minimum of six positions for decimal fractions of seconds
• Optional WITH TIME ZONEqualifier
• INTERVAL data type
• Specifies a relative value that can be used to increment or decrement an
absolute value of a date, time, or timestamp
 Columns can be declared to be NOT NULL
 Columns can be declared to have a default value
• Assigned to column in any tuple for which a value is not specified
 Example
CREATE TABLE EMPLOYEE (
…
NICKNAME VARCHAR(20) DEFAULT NULL,
…
Province CHAR(2) NOT NULL DEFAULT 'ON',
…
);
More DataTypes
9
 Additional data types
• TIMESTAMPdata type
• Includes the DATE and TIME fields
• Plus a minimum of six positions for decimal fractions of seconds
• Optional WITH TIME ZONEqualifier
• INTERVAL data type
• Specifies a relative value that can be used to increment or decrement
an absolute value of a date, time, or timestamp
 Columns can be declared to be NOT NULL
 Columns can be declared to have a default value
• Assigned to column in any tuple for which a value is not specified
 Example
CREATE TABLE EMPLOYEE (
…
NICKNAME VARCHAR(20) DEFAULT NULL,
…
Province CHAR(2) NOT NULL DEFAULT 'ON',
…
);
10
Figure 1
SQL CREATE TABLE
Specifying Key Constraints
11
 PRIMARY KEY clause
• Specifies one or more attributes that make up the primary key of a
relation
Dnumber INT NOT NULL PRIMARY KEY,
• Primary key attributes must be declared NOT NULL
 UNIQUE clause
• Specifies alternate (candidate) keys
Dname VARCHAR(15) UNIQUE;
• May or may not allow null values, depending on declaration
 If no key constraints, two or more tuples may be identical
in all
columns.
• SQL deviates from pure relational model!
• Multiset (bag) behaviour
Referential Constraints
12
 FOREIGNKEYclause
FOREIGN KEY (Dept) REFERENCES DEPARTMENT
(Dnum),
• Default operation: reject update on violation
• Attach referential triggered action clause in case referenced
tuple is deleted
• Options include SET NULL, CASCADE, and SET
DEFAULT
 Foreign key declaration must refer to a table already created
Specifying Tuple Constraints
13
 Some constraints involve several columns
 CHECK clause at the end of a CREATE
TABLEstatement
•Apply to each tuple individually
 Example
•CHECK (Dept_create_date <= Mgr_start_date)
Example
14
 Recall Employee example:
Figure 2
Referential integrity constraints
displayed on the COMPANY
database schema
15
Figure 3
Example illustrating how
default attribute values
and referential integrity
triggered actions are
specified in SQL
16
Figure 1
SQL CREATE TABLE data
definition statements
defining the COMPANY
schema from Figure 2
Basic Sql RetrievalQueries
17
 All retrievals use SELECTstatement:
SELECT
FROM
[ WHERE
where
<return list>
<table list>
<condition> ] ;
<return list>is a list of expressions or column names whose values are
to be retrieved by the query
<table list> is a list of relation names required to process the
query
<condition> is a Boolean expression that identifies the tuples to
be retrieved by the query
 Example
SELECT title, year, genre FROM
Film
WHERE director = 'Steven Spielberg' AND year > 1990;
 Omitting WHERE clause implies all tuples selected.
Semantics For 1 Relation
18
1. Start with the relation named in the FROM clause
2. Consider each tuple one after the other, eliminating those that do
not satisfy the WHERE clause.
• Boolean condition that must be true for any retrieved tuple
• Logical comparison operators
=, <, <=, >, >=, and <>
3. For each remaining tuple, create a return tuple with columns for
each expression (column name) in the SELECT clause.
• Use SELECT * to select all columns.
Film
title genre year director minutes budget gross
The Company Men drama 2010 John Wells 104 15,000,000 4,439,063
Lincoln biography 2012 Steven Spielberg 150 65,000,000 181,408,467
War Horse drama 2011 Steven Spielberg 146 66,000,000 79,883,359
Argo drama 2012 Ben Affleck 120 44,500,000 135,178,251
Select-from-where Semantics
19
 What if there are several relations in the FROM clause?
1. Start with cross-product of all relation(s) listed in the FROM clause.
• Every tuple in R1 paired up with every tuple in R2 paired up with…
2. Consider each tuple one after the other, eliminating those that do
not satisfy the WHERE clause.
3. For each remaining tuple, create a return tuple with columns for
each expression (column name) in the SELECT clause.
Steps 2 and 3 are just the same as before.
SELECT actor, birth, movie
FROM Role, Person
WHERE actor = name and birth > 1940;
Role
actor movie persona
BenAffleck Argo Tony Mendez
AlanArkin Argo Lester Siegel
BenAffleck The Company Men Bobby Walker
Tommy Lee Jones The Company Men Gene McClary
Person
name birth city
BenAffleck 1972 Berkeley
AlanArkin 1934 New York
Tommy Lee Jones 1946 San Saba
Ambiguous ColumnNames
20
 Same name may be used for two (or more) columns (in
different relations)
• Must qualify the column name with the relation name to
prevent ambiguity
SELECT name, date, product,
quantity FROM Customer, Sale,
LineItem
WHERE price > 100 AND Customer.custid =
Sale.custid AND
Sale.saleid = LineItem.saleid;
 Note
• If SELECT clause includes custid, it must specify whether
to use Customer.custid or Sale.custid even though the
values are guaranteed to be identical.
Customer
custid name address phone
Sale
saleid date custid
LineItem
saleid product quantity price
2-relation Select-from-where
21
Honours.movie award category winner actor Role.movie persona
Lincoln Critic's Choice actor Daniel Day-Lewis Ben Affleck Argo Tony Mendez 
Lincoln Critic's Choice actor Daniel Day-Lewis Tommy Lee Jones Lincoln Thaddeus Stevens 
Lincoln Critic's Choice actor Daniel Day-Lewis Daniel Day-Lewis The Boxer Danny Flynn 
Lincoln Critic's Choice actor Daniel Day-Lewis Daniel Day-Lewis Lincoln Abraham Lincoln 
Argo Critic's Choice director Ben Affleck Ben Affleck Argo Tony Mendez 
Argo Critic's Choice director Ben Affleck Tommy Lee Jones Lincoln Thaddeus Stevens 
Argo Critic's Choice director Ben Affleck Daniel Day-Lewis The Boxer Danny Flynn 
Argo Critic's Choice director Ben Affleck Daniel Day-Lewis Lincoln Abraham Lincoln 
Lincoln SAG supporting actor Tommy Lee Jones Ben Affleck Argo Tony Mendez 
Lincoln SAG supporting actor Tommy Lee Jones Tommy Lee Jones Lincoln Thaddeus Stevens 
Lincoln SAG supporting actor Tommy Lee Jones Daniel Day-Lewis The Boxer Danny Flynn 
…
Role
actor movie persona
Ben Affleck Argo Tony Mendez
Tommy Lee Jones Lincoln Thaddeus Stevens
Daniel Day-Lewis The Boxer Danny Flynn
Daniel Day-Lewis Lincoln Abraham Lincoln
SELECT award, actor, persona, Role.movie
FROM Honours, Role
WHERE category = 'actor' AND winner = actor
AND Honours.movie = Role.movie
Honours
movie award category winner
Lincoln Critic's Choice actor Daniel Day-Lewis
Argo Critic's Choice director Ben Affleck
Lincoln SAG supporting actor Tommy Lee Jones
Lincoln Critic's Choice screenplay Tony Kushner
War Horse BMI Flim music John Williams
Recall SampleTables
22
Figure 4
One possible database state for the COMPANY relational schema
Set-Difference Example (2)
23
Figure 4
One possible database state for the COMPANY relational schema
24
Figure 5
In Figure 4 (a) Q0. (b) Q1. (c) Q2. (d) Q8. e Q9. (f) Q10. (g) Q1C.
25
In Figure 4 (a) Q0. (b) Q1. (c) Q2. (d) Q8. e Q9. (f) Q10. (g) Q1C.
Figure 5
TablesAs Sets InSql
26
 Duplicate tuples may appear in query results
•From duplicates in base tables
•From projecting out distinguishing columns
 Keyword DISTINCT in the SELECT clause
eliminates duplicates
Set Operations
27
 Result treated as a set (no duplicates)
• UNION, EXCEPT (difference), INTERSECT
 Corresponding multiset(bag) operations:
• UNION ALL, EXCEPT ALL, INTERSECT ALL
 Arguments must be union-compatible
• Same number of columns
• Corresponding columns of same type
OtherOperators
28
 Standard arithmetic operators:
• Addition (+), subtraction (–), multiplication (*), and division (/)
 [NOT] LIKE comparison operator
• Used for string pattern matching
• Percent sign (%) matches zero or more characters
• Underscore (_) matches a single character
e.g., to also match Tommy Lee Jones as supporting actor:
SELECT award, actor, persona,
Role.movie FROM Honours, Role
WHERE category LIKE '%actor' AND winner =
actor AND Honours.movie =
Role.movie;
 [NOT] BETWEEN comparison operator
WHERE year BETWEEN 1990 AND 2010
equivalent to WHERE year >= 1990 AND YEAR <= 2010
Aggregate Functions
29
•These functions operate on the multiset of
values of a column of a relation, and return a
value
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
Aggregate Functions (Cont.)
30
•Find the average salary of instructors in the Computer
Science department
•select avg (salary)
from instructor
where dept_name= ’Comp. Sci.’;
•Find the total number of instructors who teach a course
in the Spring 2010 semester
•select count (distinct ID)
from teaches
where semester = ’Spring’ and year = 2010;
•Find the number of tuples in the course relation
•select count (*)
from course;
Aggregate Functions – Group By
31
• Find the average salary of instructors in each department
• select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name;
Aggregate Functions (Cont.)
32
•Attributes in select clause outside of aggregate
functions must appear in group by list
•/* erroneous query */
select dept_name, ID, avg (salary)
from instructor
group by dept_name;
Aggregate Functions – Having Clause
33
• Find the names and average salaries of all departments
whose average salary is greater than 42000
Note: predicates in the having clause are applied after the
formation of groups whereas predicates in the
where
clause are applied before forming groups
select dept_name, avg (salary)
from instructor
group by dept_name
having avg (salary) > 42000;
34

Weitere ähnliche Inhalte

Ähnlich wie Chapter_8_SQL.pdf

Ähnlich wie Chapter_8_SQL.pdf (20)

chapter9-SQL.pptx
chapter9-SQL.pptxchapter9-SQL.pptx
chapter9-SQL.pptx
 
Introduction to sql
Introduction to sqlIntroduction to sql
Introduction to sql
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Structure Query Language (SQL).pptx
Structure Query Language (SQL).pptxStructure Query Language (SQL).pptx
Structure Query Language (SQL).pptx
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Advanced SQL Webinar
Advanced SQL WebinarAdvanced SQL Webinar
Advanced SQL Webinar
 
Sql
SqlSql
Sql
 
Structure query language (sql)
Structure query language (sql)Structure query language (sql)
Structure query language (sql)
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
Dbms
DbmsDbms
Dbms
 
Lab
LabLab
Lab
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
 
CS121Lec04.pdf
CS121Lec04.pdfCS121Lec04.pdf
CS121Lec04.pdf
 
chapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfchapter-14-sql-commands.pdf
chapter-14-sql-commands.pdf
 
Lesson-02 (1).pptx
Lesson-02 (1).pptxLesson-02 (1).pptx
Lesson-02 (1).pptx
 
Module 3
Module 3Module 3
Module 3
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 

Kürzlich hochgeladen

me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Akarthi keyan
 
Clutches and brkesSelect any 3 position random motion out of real world and d...
Clutches and brkesSelect any 3 position random motion out of real world and d...Clutches and brkesSelect any 3 position random motion out of real world and d...
Clutches and brkesSelect any 3 position random motion out of real world and d...sahb78428
 
Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Bahzad5
 
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxVertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxLMW Machine Tool Division
 
Power System electrical and electronics .pptx
Power System electrical and electronics .pptxPower System electrical and electronics .pptx
Power System electrical and electronics .pptxMUKULKUMAR210
 
Test of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxTest of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxHome
 
Design of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptxDesign of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptxYogeshKumarKJMIT
 
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratoryدليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide LaboratoryBahzad5
 
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchrohitcse52
 
Engineering Mechanics Chapter 5 Equilibrium of a Rigid Body
Engineering Mechanics  Chapter 5  Equilibrium of a Rigid BodyEngineering Mechanics  Chapter 5  Equilibrium of a Rigid Body
Engineering Mechanics Chapter 5 Equilibrium of a Rigid BodyAhmadHajasad2
 
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecGuardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecTrupti Shiralkar, CISSP
 
Gender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 ProjectGender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 Projectreemakb03
 
nvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptxnvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptxjasonsedano2
 
IT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptxIT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptxSAJITHABANUS
 
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxUNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxrealme6igamerr
 
Basic Principle of Electrochemical Sensor
Basic Principle of  Electrochemical SensorBasic Principle of  Electrochemical Sensor
Basic Principle of Electrochemical SensorTanvir Moin
 
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxSUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxNaveenVerma126
 
Multicomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdfMulticomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdfGiovanaGhasary1
 
Modelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovationsModelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovationsYusuf Yıldız
 

Kürzlich hochgeladen (20)

me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part A
 
Clutches and brkesSelect any 3 position random motion out of real world and d...
Clutches and brkesSelect any 3 position random motion out of real world and d...Clutches and brkesSelect any 3 position random motion out of real world and d...
Clutches and brkesSelect any 3 position random motion out of real world and d...
 
Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)
 
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxVertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
 
Power System electrical and electronics .pptx
Power System electrical and electronics .pptxPower System electrical and electronics .pptx
Power System electrical and electronics .pptx
 
Test of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxTest of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptx
 
Design of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptxDesign of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptx
 
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratoryدليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
 
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
 
Engineering Mechanics Chapter 5 Equilibrium of a Rigid Body
Engineering Mechanics  Chapter 5  Equilibrium of a Rigid BodyEngineering Mechanics  Chapter 5  Equilibrium of a Rigid Body
Engineering Mechanics Chapter 5 Equilibrium of a Rigid Body
 
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecGuardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
 
Gender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 ProjectGender Bias in Engineer, Honors 203 Project
Gender Bias in Engineer, Honors 203 Project
 
nvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptxnvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptx
 
IT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptxIT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptx
 
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxUNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
 
Lecture 2 .pdf
Lecture 2                           .pdfLecture 2                           .pdf
Lecture 2 .pdf
 
Basic Principle of Electrochemical Sensor
Basic Principle of  Electrochemical SensorBasic Principle of  Electrochemical Sensor
Basic Principle of Electrochemical Sensor
 
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxSUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
 
Multicomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdfMulticomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdf
 
Modelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovationsModelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovations
 

Chapter_8_SQL.pdf

  • 1. 1 Course Name: Database Management System Course Code: CT – 2212 Chapter Eight SQL (Structured query language) Denekew Tadele (Maj.) Tel: +251913793506 Email: denekew.tad@gmail.com
  • 2. Contents  The SQL Query Language  Data Definition  Basic Query Structure  Additional Basic Operations  Set Operations  Aggregate Functions 2
  • 3. 3 • Structured Query Language (SQL) is the standard language for accessing information a database. • Terminology: • Syntax notes:  Some interfaces require each statement to end with a semicolon.  SQL is not case-sensitive Structured Query Language Relational Model SQL relation table tuple row attribute column
  • 4. SQL Environment • Data Definition Language (DDL) - Commands that define a database, including creating, altering, and dropping tables and establishing constraints - CREATE / DROP / ALTER, … • Data Manipulation Language (DML) - Commands that maintain and query a database - INSERT, UPDATE, DELETE, SELECT, … • Data Control Language (DCL) - Commands that control a database, including administering privileges and committing data - GRANT, ADD, REVOKE 4
  • 5. SQL Data Definition • Data Definition Language (DDL) • Major CREATE statements: - CREATE TABLE–defines a new table and its columns - CREATE VIEW–defines a logical table from one or more tables or views 5 Steps in table creation: 1. Identify data types for attributes 2. Identify columns that can and cannot be null 3. Identify columns that must be unique (candidate keys) 4. Identify primary key 5. Determine default values 6. Identify constraints on columns (domain specifications) 7. Identify foreign keys General syntax for CREATE TABLE used in data definition language CREATE TABLE table_name ( field type constraints, field2 type2, CONSTRAINT name ..., ... ); CREATE TABLE Book ( ISBN CHAR(9) NOT NULL, Title VARCHAR(20) UNIQUE, Pages INTEGER, CONSTRAINT ISBN PRIMARY KEY );
  • 6. SQL Data Types 6 TABLE 1 Sample SQL Data Types
  • 7. 7 Basic Data Types  Numeric data types • Integer numbers: INT, INTEGER, SMALLINT, BIGINT • Floating-point (real) numbers: REAL, DOUBLE , FLOAT • Fixed-point numbers: DECIMAL(n,m), DEC(n,m), NUMERIC(n,m), NUM(n,m) • Character-string data types • Fixed length: CHAR(n), CHARACTER(n) • Varying length: VARCHAR(n), CHAR VARYING(n), CHARACTER VARYING(n), LONG VARCHAR  Large object data types • Characters: CLOB, CHAR LARGE OBJECT , CHARACTER LARGE OBJECT • Bits: BLOB, BINARY LARGE OBJECT  Boolean data type • Values of TRUE or FALSE or NULL  DATE data type • T en positions • Components are YEAR, MONTH, and DAY in the form YYYY-MM-DD
  • 8. More DataTypes 8  Additional data types • TIMESTAMPdata type • Includes the DATE and TIMEfields • Plus a minimum of six positions for decimal fractions of seconds • Optional WITH TIME ZONEqualifier • INTERVAL data type • Specifies a relative value that can be used to increment or decrement an absolute value of a date, time, or timestamp  Columns can be declared to be NOT NULL  Columns can be declared to have a default value • Assigned to column in any tuple for which a value is not specified  Example CREATE TABLE EMPLOYEE ( … NICKNAME VARCHAR(20) DEFAULT NULL, … Province CHAR(2) NOT NULL DEFAULT 'ON', … );
  • 9. More DataTypes 9  Additional data types • TIMESTAMPdata type • Includes the DATE and TIME fields • Plus a minimum of six positions for decimal fractions of seconds • Optional WITH TIME ZONEqualifier • INTERVAL data type • Specifies a relative value that can be used to increment or decrement an absolute value of a date, time, or timestamp  Columns can be declared to be NOT NULL  Columns can be declared to have a default value • Assigned to column in any tuple for which a value is not specified  Example CREATE TABLE EMPLOYEE ( … NICKNAME VARCHAR(20) DEFAULT NULL, … Province CHAR(2) NOT NULL DEFAULT 'ON', … );
  • 11. Specifying Key Constraints 11  PRIMARY KEY clause • Specifies one or more attributes that make up the primary key of a relation Dnumber INT NOT NULL PRIMARY KEY, • Primary key attributes must be declared NOT NULL  UNIQUE clause • Specifies alternate (candidate) keys Dname VARCHAR(15) UNIQUE; • May or may not allow null values, depending on declaration  If no key constraints, two or more tuples may be identical in all columns. • SQL deviates from pure relational model! • Multiset (bag) behaviour
  • 12. Referential Constraints 12  FOREIGNKEYclause FOREIGN KEY (Dept) REFERENCES DEPARTMENT (Dnum), • Default operation: reject update on violation • Attach referential triggered action clause in case referenced tuple is deleted • Options include SET NULL, CASCADE, and SET DEFAULT  Foreign key declaration must refer to a table already created
  • 13. Specifying Tuple Constraints 13  Some constraints involve several columns  CHECK clause at the end of a CREATE TABLEstatement •Apply to each tuple individually  Example •CHECK (Dept_create_date <= Mgr_start_date)
  • 14. Example 14  Recall Employee example: Figure 2 Referential integrity constraints displayed on the COMPANY database schema
  • 15. 15 Figure 3 Example illustrating how default attribute values and referential integrity triggered actions are specified in SQL
  • 16. 16 Figure 1 SQL CREATE TABLE data definition statements defining the COMPANY schema from Figure 2
  • 17. Basic Sql RetrievalQueries 17  All retrievals use SELECTstatement: SELECT FROM [ WHERE where <return list> <table list> <condition> ] ; <return list>is a list of expressions or column names whose values are to be retrieved by the query <table list> is a list of relation names required to process the query <condition> is a Boolean expression that identifies the tuples to be retrieved by the query  Example SELECT title, year, genre FROM Film WHERE director = 'Steven Spielberg' AND year > 1990;  Omitting WHERE clause implies all tuples selected.
  • 18. Semantics For 1 Relation 18 1. Start with the relation named in the FROM clause 2. Consider each tuple one after the other, eliminating those that do not satisfy the WHERE clause. • Boolean condition that must be true for any retrieved tuple • Logical comparison operators =, <, <=, >, >=, and <> 3. For each remaining tuple, create a return tuple with columns for each expression (column name) in the SELECT clause. • Use SELECT * to select all columns. Film title genre year director minutes budget gross The Company Men drama 2010 John Wells 104 15,000,000 4,439,063 Lincoln biography 2012 Steven Spielberg 150 65,000,000 181,408,467 War Horse drama 2011 Steven Spielberg 146 66,000,000 79,883,359 Argo drama 2012 Ben Affleck 120 44,500,000 135,178,251
  • 19. Select-from-where Semantics 19  What if there are several relations in the FROM clause? 1. Start with cross-product of all relation(s) listed in the FROM clause. • Every tuple in R1 paired up with every tuple in R2 paired up with… 2. Consider each tuple one after the other, eliminating those that do not satisfy the WHERE clause. 3. For each remaining tuple, create a return tuple with columns for each expression (column name) in the SELECT clause. Steps 2 and 3 are just the same as before. SELECT actor, birth, movie FROM Role, Person WHERE actor = name and birth > 1940; Role actor movie persona BenAffleck Argo Tony Mendez AlanArkin Argo Lester Siegel BenAffleck The Company Men Bobby Walker Tommy Lee Jones The Company Men Gene McClary Person name birth city BenAffleck 1972 Berkeley AlanArkin 1934 New York Tommy Lee Jones 1946 San Saba
  • 20. Ambiguous ColumnNames 20  Same name may be used for two (or more) columns (in different relations) • Must qualify the column name with the relation name to prevent ambiguity SELECT name, date, product, quantity FROM Customer, Sale, LineItem WHERE price > 100 AND Customer.custid = Sale.custid AND Sale.saleid = LineItem.saleid;  Note • If SELECT clause includes custid, it must specify whether to use Customer.custid or Sale.custid even though the values are guaranteed to be identical. Customer custid name address phone Sale saleid date custid LineItem saleid product quantity price
  • 21. 2-relation Select-from-where 21 Honours.movie award category winner actor Role.movie persona Lincoln Critic's Choice actor Daniel Day-Lewis Ben Affleck Argo Tony Mendez  Lincoln Critic's Choice actor Daniel Day-Lewis Tommy Lee Jones Lincoln Thaddeus Stevens  Lincoln Critic's Choice actor Daniel Day-Lewis Daniel Day-Lewis The Boxer Danny Flynn  Lincoln Critic's Choice actor Daniel Day-Lewis Daniel Day-Lewis Lincoln Abraham Lincoln  Argo Critic's Choice director Ben Affleck Ben Affleck Argo Tony Mendez  Argo Critic's Choice director Ben Affleck Tommy Lee Jones Lincoln Thaddeus Stevens  Argo Critic's Choice director Ben Affleck Daniel Day-Lewis The Boxer Danny Flynn  Argo Critic's Choice director Ben Affleck Daniel Day-Lewis Lincoln Abraham Lincoln  Lincoln SAG supporting actor Tommy Lee Jones Ben Affleck Argo Tony Mendez  Lincoln SAG supporting actor Tommy Lee Jones Tommy Lee Jones Lincoln Thaddeus Stevens  Lincoln SAG supporting actor Tommy Lee Jones Daniel Day-Lewis The Boxer Danny Flynn  … Role actor movie persona Ben Affleck Argo Tony Mendez Tommy Lee Jones Lincoln Thaddeus Stevens Daniel Day-Lewis The Boxer Danny Flynn Daniel Day-Lewis Lincoln Abraham Lincoln SELECT award, actor, persona, Role.movie FROM Honours, Role WHERE category = 'actor' AND winner = actor AND Honours.movie = Role.movie Honours movie award category winner Lincoln Critic's Choice actor Daniel Day-Lewis Argo Critic's Choice director Ben Affleck Lincoln SAG supporting actor Tommy Lee Jones Lincoln Critic's Choice screenplay Tony Kushner War Horse BMI Flim music John Williams
  • 22. Recall SampleTables 22 Figure 4 One possible database state for the COMPANY relational schema
  • 23. Set-Difference Example (2) 23 Figure 4 One possible database state for the COMPANY relational schema
  • 24. 24 Figure 5 In Figure 4 (a) Q0. (b) Q1. (c) Q2. (d) Q8. e Q9. (f) Q10. (g) Q1C.
  • 25. 25 In Figure 4 (a) Q0. (b) Q1. (c) Q2. (d) Q8. e Q9. (f) Q10. (g) Q1C. Figure 5
  • 26. TablesAs Sets InSql 26  Duplicate tuples may appear in query results •From duplicates in base tables •From projecting out distinguishing columns  Keyword DISTINCT in the SELECT clause eliminates duplicates
  • 27. Set Operations 27  Result treated as a set (no duplicates) • UNION, EXCEPT (difference), INTERSECT  Corresponding multiset(bag) operations: • UNION ALL, EXCEPT ALL, INTERSECT ALL  Arguments must be union-compatible • Same number of columns • Corresponding columns of same type
  • 28. OtherOperators 28  Standard arithmetic operators: • Addition (+), subtraction (–), multiplication (*), and division (/)  [NOT] LIKE comparison operator • Used for string pattern matching • Percent sign (%) matches zero or more characters • Underscore (_) matches a single character e.g., to also match Tommy Lee Jones as supporting actor: SELECT award, actor, persona, Role.movie FROM Honours, Role WHERE category LIKE '%actor' AND winner = actor AND Honours.movie = Role.movie;  [NOT] BETWEEN comparison operator WHERE year BETWEEN 1990 AND 2010 equivalent to WHERE year >= 1990 AND YEAR <= 2010
  • 29. Aggregate Functions 29 •These functions operate on the multiset of values of a column of a relation, and return a value avg: average value min: minimum value max: maximum value sum: sum of values count: number of values
  • 30. Aggregate Functions (Cont.) 30 •Find the average salary of instructors in the Computer Science department •select avg (salary) from instructor where dept_name= ’Comp. Sci.’; •Find the total number of instructors who teach a course in the Spring 2010 semester •select count (distinct ID) from teaches where semester = ’Spring’ and year = 2010; •Find the number of tuples in the course relation •select count (*) from course;
  • 31. Aggregate Functions – Group By 31 • Find the average salary of instructors in each department • select dept_name, avg (salary) as avg_salary from instructor group by dept_name;
  • 32. Aggregate Functions (Cont.) 32 •Attributes in select clause outside of aggregate functions must appear in group by list •/* erroneous query */ select dept_name, ID, avg (salary) from instructor group by dept_name;
  • 33. Aggregate Functions – Having Clause 33 • Find the names and average salaries of all departments whose average salary is greater than 42000 Note: predicates in the having clause are applied after the formation of groups whereas predicates in the where clause are applied before forming groups select dept_name, avg (salary) from instructor group by dept_name having avg (salary) > 42000;
  • 34. 34