You are on page 1of 32

Misurata University

Faculty of Information Technology

Advanced Database

LECTURE 2
Structured Query Language
(SQL)
Instructor Aisha Lusta
SQL Introduction
2

 The name SQL is derived from Structured Query


Language
 SQL is a comprehensive database language
 It has statements for data definition, query, and
update.
 it has facilities for defining views on the database, for
specifying security and authorization
 It considered one of the major reasons for the success
of relational model in the database industry
 SQL uses the terms table, row, and column for
relation, tuple, and attribute
SQL Statements
3

 Data Definition Language (DDL)


– Statements to define the database schema
 Data Manipulation Language (DML)
– Statements to manipulate the data
 Data Control Language(DCL)
– Statements to specify transaction control, semantic
integrity, authorization and management of
privileges
– Statements for specifying the physical storage
parameters such as file structures and access paths
(indexes)
Data Definition Language
4

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

o Security and authorization information for each relation.


o The physical storage structure of each relation on disk.
DDL Commands
5

 Create table
 Alter table
o add (column, constraint)
o modify(column)
o drop(column,constraint)
 Drop table
DML Commands
6

 Statements to manipulate the data


These statements work on database instances and
produce new database states
 Basic SQL DML Statements

– Retrieval
• SELECT
– Update
• INSERT
• DELETE
• UPDATE
The select Clause
7

• SQL has one basic statement for retrieving information from a database;

• In the SELECT statement, users specify what the result of the query should be, and the DBMS decides
the operations and order of execution.

• SQL allows a table (relation) to have two or more tuples that are identical in all their attribute values

• SQL relations can be constrained to be sets by specifying PRIMARY KEY or by using the DISTINCT
option in a query
SELECT Basic Syntax
8

SELECT <attribute list>


FROM <table list>
WHERE <condition>

o <attribute list> is a list of attribute names whose values are to be retrieved by


the query
o <table list> is a list of the relation names required to process the query
o <condition> is a conditional (Boolean) expression that identifies the tuples to be
retrieved by the query
Select Statement Notes
9

 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 names of all departments with instructor, and remove duplicates
select distinct dept_name
from instructor
 The keyword all specifies that duplicates not be removed.
select all dept_name
from instructor
10

 An asterisk in the select clause denotes “all attributes”


select *
from instructor
 The select clause can contain arithmetic expressions involving the
operation, +, –, , and /, and operating on constants or attributes of
tuples.
select ID, name, dept_name, salary/12
from instructor
Where Clause
11

 The where clause specifies conditions that the result must satisfy
 To find all instructors in Comp. Sci. dept with salary > 800
select name
from instructor
where dept_name = ‘Comp. Sci' and salary > 80000
 Comparison results can be combined using the logical connectives and, or, and not.
 Comparisons can be applied to results of arithmetic expressions.
Select Example
12

 find all instructors except the instructors in Comp. Sci dept, or the instructors in Music dept with
salaries = 70000
select name from instructor
where not (dept_name = ‘Comp. Sci’

or dept_name = ‘Music’ and salary = 70000)


Cartesian product operation
13

 The Cartesian product, also referred to as a cross-join, returns all:


 the rows in all the tables listed in the query.
 Each row in the first table is paired with all the rows in the second
table.
 This happens when there is no relationship defined between the two
tables
Cartesian product operation Example
14

 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)
15

Instructor

teaches
16
INNER JOIN vs. OUTER JOIN
17

 INNER JOIN
 These two queries are equivalent
1- SELECT emp_name, dname
FROM Employee INNER JOIN Department ON
Dno=dnum

2- SELECT emp_name, dname


FROM Employee , Department where
Employee. Dno=Department. dnum
 the query answer does not include
– an employee that does not have a department
– a department that is not assigned to any
employee
OUTER JOIN
18

 A LEFT OUTER JOIN will include all matches plus all


employees that do not have a department
SELECT emp_name, dname
FROM Employee Left outer JOIN Department ON
Dno=dnum
 A RIGHT OUTER JOIN will include all matches plus all
department that are not assigned to any employee
SELECT emp_name, dname
FROM Employee Right outer JOIN Department ON
Dno=dnum
 A FULL OUTER JOIN will include all of these
Example
19

 Select * from Customer inner join Saleperson on


 Salesperson = Number gives:
1 Smith 123 X St 700 10000 9000 55 55 Miller 555 A St 100
2 Jones 222 Y St 700 8000 3750 65 65 Rojas 555 A St 101
 LEFT OUTER JOIN Salesperson on Salesperson = .Number gives us:
1 Smith 123 X St 700 10000 9000 55 55 Miller 555 A St 100
2 Jones 222 Y St 700 8000 3750 65 65 Rojas 555 A St 101
3 Wei 111 Z St 700 11000 9000 NULL NULL NULL NULL NULL
 RIGHT OUTER JOIN Salesperson on Salesperson = Number gives us:
1 Smith 123 X St 700 10000 9000 55 55 Miller 555 A St 100
2 Jones 222 Y St 700 8000 3750 65 65 Rojas 555 A St 101
NULL NULL NULL NULL NULL NULL NULL 75 MarYn 777 B St 200
Examples
20

 Find the names of all instructors who have taught some courses and the course_id
Answer1: select name, course_id
from instructor , teaches
where instructor.ID = teaches.ID

Answer2: select name, course_id


from instructor join teaches
On instructor.ID = teaches.ID
 Find the names of all instructors in the music department who have taught some courses and the
course_id
select name, course_id
from instructor join teaches
on instructor.ID = teaches.ID where instructor. dept_name = ‘music’
The Rename Operation
21

 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
22

 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%'
String Operations (Cont.)
23

 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.


String Operations Examples
24

 Find the names of all instructors whose name starts with “A”
Select name
From instructor
Where name like “A%”;
 Find the names of all instructors whose name starts with “A” , ends with “s”, and
includes only four letters.
Select name
From instructor
Where name like “A_ _s”;
25

 Find the names of all instructors whose name starts with “A” , ends with
“d”, and includes at least five letters.
Select name
From instructor
Where name like “A_ _ _%d”
 Find the names of all instructors whose name starts with “M” , the second
letter is “u” , ends with “a”, and includes at least four letters.
Select name
From instructor
Where name like “Mu_ %a”
Ordering the Display of Tuples
26

 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
27

 What is the result of the following query:


select dept_name ,name
from instructor
order by dept_name, name;
Set Operations
28

 The UNION , EXCEPT and INTERSECT Operators in SQL


 The UNION, EXCEPT and INTERSECT operators of SQL enable you to combine more than one SELECT
statement to form a single result set.
➢ The UNION operator returns all rows.
➢ The INTERSECT operator returns all rows that are in both result sets.
➢ The EXCEPT operator returns the rows that are only in the first result set but not in the second.
To use the The UNION , EXCEPT and INTERSECT Operators
for two queries, the following rules are applied:

1.The order and the number of columns must be the same.


2.The data types of the corresponding columns must be compatible.
Set Operations(count.)
29

 Find courses that ran in Fall 2017 or in Spring 2018


(select course_id from section where sem = 'Fall' and year = 2017)
union
(select course_id from section where sem = 'Spring' and year = 2018)
 Find courses that ran in Fall 2017 and in Spring 2018
(select course_id from section where sem = 'Fall' and year = 2017)
intersect
(select course_id from section where sem = 'Spring' and year = 2018)
 Find courses that ran in Fall 2017 but not in Spring 2018
(select course_id from section where sem = 'Fall' and year = 2017)
except
(select course_id from section where sem = 'Spring' and year = 2018)
Set Operations(count.)
30

 Set operations union, intersect, and except


 Each of the above operations automatically eliminates duplicates

 To retain all duplicates use the

o union all,

o intersect all

o except all.
Null Values
31

 It is possible for tuples to have a null value, denoted by null, for some of their
attributes
 null signifies an unknown value or that a value does not exist.
 The result of any arithmetic expression involving null is null
 Example: 5 + null returns null

 The predicate is null can be used to check for null values.


 Example: Find all instructors whose salary is null.

select name
from instructor
where salary is null
 The predicate is not null succeeds if the value on which it is applied is not null.
The End

You might also like