SlideShare ist ein Scribd-Unternehmen logo
1 von 111
Database Systems
Structure Query Language
(SQL)
Dr. Ejaz Ahmed 2
Objectives
• Example Tables
• Introduction
• ISO SQL Data Types
• Comparison Operators in SQL
• Logical Operators in SQL
• Arithmetic Operators in SQL
• SQL Schema and Catalog
• SQL Data Definition Statements (DDL)
• SQL Data Manipulation Statements (DML)
• Other SQL Operators
Dr. Ejaz Ahmed 3
Example Table …
Car_Sales
City Year Cars_sol
d
Dhahran 2001 525
Dhahran 2002 456
Riyadh 2001 700
Riyadh 2002 654
Jeddah 2001 921
Jeddah 2002 752
Khobar 2002
Dr. Ejaz Ahmed 4
Example: Tables …
1
2
3
ICS
COE
SWE
dno dname
Lid Lname dno salary
1
2
3
4
5
6
7
Ahmed
Amin
Hani
Abdallah
Ageel
Yousef
Khalid
1
2
1
1
2
2
4000
3700
4200
4300
4000
3500
4500
Departments
Lecturers
Dr. Ejaz Ahmed 5
Objectives of SQL
• Ideally, database language should allow user to:
– create the database and relation structures;
– perform insertion, modification, deletion of data from relations;
– perform simple and complex queries.
• Must perform these tasks with minimal user effort and command
structure and syntax must be easy to learn.
• It must be portable.
• SQL does not contain flow control commands. These must be
implemented using a programming or job-control language, or
interactively by the decisions of the user.
Dr. Ejaz Ahmed 6
Objectives of SQL …
• SQL is relatively easy to learn:
– It is a non-procedural language - you specify what information you
require, rather than how to get it.
– It is essentially free-format.
• Can be used by a range of users including DBAs, management,
application programmers, and other types of end users.
• An ISO standard now exists for SQL, making it both the formal and
de facto standard language for relational databases.
Dr. Ejaz Ahmed 7
Objectives of SQL …
• Consists of standard English words:
CREATE TABLE staff(
sno VARCHAR(5),
lname VARCHAR(15),
salary NUMBER(7,2)
);
INSERT INTO staff
VALUES ('SG16', 'Brown', 8300);
SELECT sno, lname, salary
FROM staff
WHERE salary > 10000;
Dr. Ejaz Ahmed 8
History of SQL …
• In 1974, D. Chamberlin (IBM San Jose Laboratory) defined
language called 'Structured English Query Language' or SEQUEL.
• A revised version SEQUEL/2 was defined in 1976 but name was
subsequently changed to SQL for legal reasons.
• Still pronounced 'see-quel', though official pronunciation is 's-q-l'.
• IBM subsequently produced a prototype DBMS called System R,
based on SEQUEL/2.
• Roots of SQL, however, are in SQUARE (Specifying Queries as
Relational Expressions), which predates System R project.
Dr. Ejaz Ahmed 9
History of SQL …
• In late 70s, ORACLE appeared and was probably first commercial
RDBMS based on SQL.
• In 1987, ANSI and ISO published an initial standard for SQL.
• In 1989, ISO published an addendum that defined an 'Integrity
Enhancement Feature'.
• In 1992, first major revision to ISO standard occurred, referred to as
SQL2 or SQL/92.
Dr. Ejaz Ahmed 10
Importance of SQL …
• SQL has become part of application architectures such
as IBM's Systems Application Architecture (SAA).
• It is strategic choice of many large and influential
organizations (e.g. X/OPEN).
• SQL is Federal Information Processing Standard (FIPS)
to which conformance is required for all sales of
databases to American Government.
Dr. Ejaz Ahmed 11
Importance of SQL …
• SQL Access Group trying to define enhancements that
will support interoperability across disparate systems.
• SQL is used in other standards and even influences
development of other standards as a definitional tool.
Examples include:
– ISO's Information Resource Directory System (IRDS)
Standard
– Remote Data Access (RDA) Standard.
Dr. Ejaz Ahmed 12
Components of SQL
• A database language must have support for the
components listed below. Most implementations of SQL
support various components listed below:
– Data Definition Language (DDL)
– Interactive Data Manipulation Language (Interactive
DML)
– Embedded Data Manipulation Language (Embedded
DML)
– Views
– Integrity and transaction control
– Authorization & Security (DCL)
– Catalog and dictionary facility.
Dr. Ejaz Ahmed 13
Basic Guidelines for Writing SQL
Statements …
• SQL statement consists of reserved words and user-defined words.
– Reserved words are a fixed part of SQL and must be spelt exactly as
required and cannot be split across lines.
– User-defined words are made up by user and represent names of
various database objects such as relations, columns, views.
• Most components of an SQL statement are case insensitive, except
for literal character data.
• More readable with indentation and lineation:
– Each clause should begin on a new line.
– Start of a clause should line up with start of other clauses.
– If clause has several parts, should each appear on a separate line and
be indented under start of clause.
Dr. Ejaz Ahmed 14
Basic Guidelines for Writing SQL
Statements …
• Use extended form of BNF notation:
– Upper case letters represent reserved words.
– Lower case letters represent user-defined words.
– | indicates a choice among alternatives.
– Curly braces indicate a required element.
– Square brackets indicate an optional element.
– … indicates optional repetition (0 or more).
– ALL SQL is case less
Dr. Ejaz Ahmed 15
ISO SQL Data Types
Dr. Ejaz Ahmed 16
Comparison Operators in SQL
• There are six comparison operators in SQL. These operators are
used to build conditions that are used in the WHERE clause of a
DML statement:
Operator Meaning
=
<>
<
>
<=
>=
Equal
Not Equal
Less than
Greater than
Less than or Eqaul
Greater than or Eqaul
Dr. Ejaz Ahmed 17
Logical Operators in SQL
• There are three logical operators that help us to build
compound conditions to be used in the WHERE clause
of the SELECT statement.
– The AND operator joins two or more conditions, and
display a row only if that row’s data satisfies ALL the
specified conditions.
– The OR operator joins two or more conditions, and
display a row only if that row’s data satisfies any of
the specified conditions.
– The NOT is a unary operator, and is used to negates
a condition.
Dr. Ejaz Ahmed 18
Arithmetic Operators in SQL
• Another feature of SQL allows the use of arithmetic in
queries.
– The standard arithmetic operators ( +, -, /, *) can be
applied to numeric values or attributes with numeric
domain.
– The arithmetic operators can be used in expressions
in the SELECT and the WHERE clauses to compute
numeric values.
– All attributes that can be computed using arithmetic
expressions (such as age from birth date, annual
salary from monthly salary) must be eliminated as
part of a good design practice in databases.
Dr. Ejaz Ahmed 19
SQL Schema and Catalog
• In SQL92, relations and other database objects exist in an
environment.
• Each environment contains one or more catalogs, and each catalog
consists of set of schemas.
• Schema is a named collection of related database objects.
• Objects in a schema can be tables, views, domains, constraints,
translations, and character sets. All have same owner.
Dr. Ejaz Ahmed 20
SELECT
• SELECT Definition
• Selecting Columns
• Selecting Rows
• Sorting
• Aggregation
• Grouping
• Restricting Groups
• Aliasing Table Names
• Nested Queries
• Join
• Set Operations
Dr. Ejaz Ahmed 21
SELECT Definition …
• SQL has only one statement for retrieving information from a
database called the SELECT statement.
• SQL SELECT statement is different from that of Relational Algebra.
• An important distinction between SQL and formal relational model
is that SQL allows duplicate rows. Hence an SQL table is not a set
but a multiset (some times called a bag) of tuples.
Retrieving Information From the
Database
DB
Data
JohnSmith
Mary
Stiles
22Dr. Ejaz Ahmed
SQL
23Dr. Ejaz Ahmed
SQL - Usage
24Dr. Ejaz Ahmed
Dr. Ejaz Ahmed 25
SELECT Definition …
• A SELECT statement can consist up to six clauses.
SELECT [DISTINCT | ALL]
{* | [column_expression [AS
new_name]] [,...] }
FROM table_name [alias] [, ...]
[WHERE condition]
[GROUP BY column_list]
[HAVING condition]
[ORDER By column_list]
• Only SELECT and FROM clauses are mandatory.
• Order of the clauses cannot be changed.
Dr. Ejaz Ahmed 26
SELECT Definition …
• FROM Specifies table(s) to be used.
• WHERE Filters rows.
• GROUP BY Forms groups of rows with same column value.
• HAVING Filters groups subject to some condition.
• SELECT Specifies which columns are to appear in output.
• ORDER BY Specifies the order of the output.
Dr. Ejaz Ahmed 27
Selecting Columns
• Selecting all columns +
• Selecting Specific columns +
• Selecting Computed columns +
• Renaming Columns +
Dr. Ejaz Ahmed 28
Selecting All Columns
Example 1:
SELECT city, year, cars_sold
FROM car_sales;
• Can use * as an abbreviation
for 'all columns':
Example 2:
SELECT *
FROM car_sales;
City Year Cars_sol
d
Dhahran 2001 525
Dhahran 2002 456
Riyadh 2001 700
Riyadh 2002 654
Jeddah 2001 921
Jeddah 2002 752
Khobar 2002
Input Tables
Dr. Ejaz Ahmed 29
Selecting Specific Columns
• Selected columns can be listed
as shown in the following
example. Notice that the year
column was not selected so it
doesn’t appear in the output.
Example:
SELECT city, cars_sold
FROM car_sales;
City Cars_sold
Dhahran 525
Dhahran 456
Riyadh 700
Riyadh 654
Jeddah 921
Jeddah 752
Khobar
Input Tables
Dr. Ejaz Ahmed 30
Selecting Computed Columns
• If the value of a car
is 100,000 then the
total sales per year
for each city is
computed as follows.
Example:
SELECT
city
,year
,cars_sold
,cars_sold * 100000
FROM car_sales;
Dhahran
Dhahran
Riyadh
Riyadh
Jeddah
Jeddah
2001
2002
2001
2002
2001
2002
525
456
700
654
921
752
City Year Cars_Sold
52500000
45600000
70000000
65400000
92100000
75200000
Cars_Sold *100000
Khobar 2002 00
Input Tables
Dr. Ejaz Ahmed 31
Renaming Columns
• The name of the
computed column in
the last slide cab be
changed from
cars_sold*100000 to
sales as follows.
Example:
SELECT
city
,year
,cars_sold As Sold
,cars_sold * 100000
AS sales
FROM car_sales;
Dhahran
Dhahran
Riyadh
Riyadh
Jeddah
Jeddah
2001
2002
2001
2002
2001
2002
525
456
700
654
921
752
City Year Sold
52500000
45600000
70000000
65400000
92100000
75200000
sales
Khobar 2002 00
Input Tables
Dr. Ejaz Ahmed 32
Selecting Rows
• Selecting All Rows +
• Partial match Search +
• Range Search +
• Set Membership Search +
• Pattern matching Search +
• Null Search +
• Removing Duplicate Rows +
Dr. Ejaz Ahmed 33
Selecting All Rows
• A SELECT statement without a
WHERE clause selects all
rows.
Example:
SELECT *
FROM car_sales;
Dhahran
Dhahran
Riyadh
Riyadh
Jeddah
Jeddah
2001
2002
2001
2002
2001
2002
525
456
700
654
921
752
City Year Cars_Sold
Khobar 2002
Input Tables
Dr. Ejaz Ahmed 34
Selecting Rows
• To Select certain rows of a table you need to use the
WHERE clause of the SELECT statement.
• The WHERE clause has a condition which is a logical
expression.
• The Where condition consists of:
– Comparison Operators
– Logical Operators
– Arithmetic Operators
– Other SQL constructs which will be discussed later.
• A record to be selected it must make the WHERE logical
expression true. In other words it must satisfy the where
condition.
Dr. Ejaz Ahmed 35
Partial match Search
• Selecting all the records whose column
values match the column values
specified in the WHERE clause.
Example1:
SELECT *
FROM car_sales
WHERE city = ‘Dhahran’;
Dhahran
Dhahran
2001
2002
525
456
City Year Cars_Sold
Dhahran 2002 456
City Year Cars_Sold
Example2:
SELECT *
FROM car_sales
WHERE city = ‘Dhahran’
AND year > 2001;
Input Tables
Dr. Ejaz Ahmed 36
Range Search
Example:
SELECT *
FROM car_sales
WHERE cars_sold >= 525
AND cars_sold <= 752;
OR
SELECT *
FROM car_sales
WHERE cars_sold
BETWEEN 525 AND 752;
Dhahran
Riyadh
Riyadh
Jeddah
2001
2001
2002
2002
525
700
654
752
City Year Sold
Selecting all the records whose column values is between the
values specified in the WHERE cluause.
 BETWEEN test includes the endpoints of range. NOT BETWEEN list the one not in the range.
Input Tables
Dr. Ejaz Ahmed 37
Set Membership Search …
Example:
SELECT *
FROM car_sales
WHERE city
IN
(‘Dhahran’, ‘Riyadh’);
Selecting all the records whose column value is a member of the
set specified in the WHERE clause.
Dhahran
Dhahran
Riyadh
Riyadh
2001
2002
2001
2002
525
456
700
654
City Year Sold
Input Tables
Dr. Ejaz Ahmed 38
Set Membership Search
Example:
SELECT *
FROM car_sales
WHERE city
NOT IN
(‘Dhahran’, ‘Riyadh’);
Selecting all the records whose column value not a member of the
set specified in the WHERE clause.
Jeddah
Jeddah
2001
2002
921
752
City Year Sold
Khobar 2002
Input Tables
Dr. Ejaz Ahmed 39
Pattern Matching Search …
• SQL has two special pattern matching
symbols:
– %: sequence of zero or more characters;
– _ (underscore): any single character.
• LIKE '%dd%' means a sequence of
characters of any length containing ‘dd'.
Dr. Ejaz Ahmed 40
Pattern matching Search
Example:
SELECT *
FROM car_sales
WHERE
city LIKE ‘J%’
Selecting all the records whose column value match the pattern specified in
the WHERE clause.
Jeddah
Jeddah
2001
2002
921
752
City Year Sold
Example:
SELECT *
FROM car_sales
WHERE
city LIKE ‘%dd%’
Jeddah
Jeddah
2001
2002
921
752
City Year Sold
Input Tables
Dr. Ejaz Ahmed 41
NULL Search
Example 1: Select all cities
where the number of cars
sold is unkown.
SELECT city
FROM car_sales
WHERE cars_sold IS NULL;
City
Khoba
r
Example 2: Select all cities where
the number of cars sold is kown.
SELECT city
FROM car_sales
WHERE cars_sold IS NOT NULL;
City
Dhahran
Riyadh
Jeddah
Dhahran
Riyadh
Jeddah
Input Tables
Dr. Ejaz Ahmed 42
Removing Duplicate Rows
Example1:
SELECT city
FROM car_sales
Example2:
SELECT DISTINCT city
FROM car_sales
Dhahran
Dhahran
Riyadh
Riyadh
Jeddah
Jeddah
City
Dhahran
Riyadh
Jeddah
City
Using DISTINCT in the SELECT clause removes duplicate rows from the output table
Khobar
Khobar
Input Tables
Dr. Ejaz Ahmed 43
Sorting
• The ORDER BY clause specifies an order
for displaying the result of a query.
– SQL allows the user to order the tuples in the result of a query
by the values of one or more attributes; the default order is
ascending or increasing.
– The keyword DESC is specified to sort in a descending order of
values while the keyword ASC can be used to specify ascending
order explicitly.
– The sorting will be applied alphabetically or numerically
depending on the type of the column attribute.
Dr. Ejaz Ahmed 44
Example: Sorting
Example:
The following SELECT statement
sorts the car_sales table in
ascending order of city and
descending order of car_sales
columns
SELECT *
FROM car_sales
ORDER BY city asc, car_sales desc;
Dhahran
Dhahran
Riyadh
Riyadh
Jeddah
Jeddah
2001
2002
2001
2002
2001
2002
525
456
700
654
921
752
City Year Cars_Sold
Khobar 2002
Input Tables
Dr. Ejaz Ahmed 45
Aggregation …
• ISO standard defines five aggregate functions:
– COUNT returns number of values in a specified
column.
– SUM returns sum of values in a specified column.
– AVG returns average of values in a specified
column.
– MIN returns smallest value in a specified column.
– MAX returns largest value in a specified column.
Dr. Ejaz Ahmed 46
Aggregation …
• Each operates on a single column of a table and return single value.
• COUNT, MIN, and MAX apply to numeric and non-numeric fields, but
SUM and AVG may be used on numeric fields only.
• Apart from COUNT(*), each function eliminates nulls first and
operates only on remaining non-null values.
• COUNT(*) counts all rows of a table, regardless of whether nulls or
duplicate values occur.
• Can use DISTINCT before column name to eliminate duplicates.
Dr. Ejaz Ahmed 47
Aggregation …
• DISTINCT has no effect with MIN/MAX, but may have with
SUM/AVG.
• Aggregate functions can be used only in SELECT list and in HAVING
clause.
• If SELECT list includes an aggregate function and there is no
GROUP BY clause, then SELECT list cannot reference a column with
an aggregate function. For example, following is illegal:
SELECT city, COUNT(*)
FROM car_sales;
Dr. Ejaz Ahmed 48
Example : COUNT
• How many rows
are there in the
car_sales table?
SELECT COUNT(*) as Rows
FROM car_sales
Rows
7
 How many cities are
there in the car_sales
table?
SELECT
COUNT(DISTINCT city)
as city
FROM car_sales
city
4
Input Tables
Dr. Ejaz Ahmed 49
Example : SUM
• Find the total number
of all the cars sold from
the car_sales table?
SELECT
SUM(cars_sold) as cars_sold
FROM car_sales
Cars_sold
4008
 Find the number of all the
cars_sold in Dhahran from the
car_sales table?
SELECT
SUM(cars_sold) as Dah_cars
FROM car_sales
WHERE city = ‘Dhahran’
Dah_cars
981
Input Tables
Dr. Ejaz Ahmed 50
Example: MIN, MAX, AVG
• Find the minimum, maximum, and average cars_sold per year and
per city form the car_sales table
SELECT MIN(cars_sold) as Min_sold
, MAX(cars_sold) as Max_sold
, AVG(cars_sold) as Avg_sold
FROM car_sales
WHERE car_sales IS NOT NULL;
Min_sold Max_sold Avg_sold
456 921 668
Input Tables
Dr. Ejaz Ahmed 51
Grouping
• Use GROUP BY clause to get sub-totals.
• SELECT and GROUP BY closely integrated: each item in SELECT
list must be single-valued per group, and SELECT clause may
only contain:
– Column names.
– Aggregate functions.
– Constants.
– An expression involving combinations of the above.
• All column names in SELECT list must appear in GROUP BY clause
unless name is used only in an aggregate function.
• If WHERE is used with GROUP BY, WHERE is applied first, then
groups are formed from remaining rows satisfying predicate.
• ISO considers two nulls to be equal for purposes of GROUP BY.
Dr. Ejaz Ahmed 52
Example: Grouping
• Find the total cars sold in each city from the car_sales table.
SELECT city, SUM(cars_sold) as
cars
FROM car_sales
WHERE cars_sold IS NOT NULL
GROUP BY city
ORDER BY SUM(cars_sold) ;
City Cars
Dhahran 981
Riyadh 1354
Jeddah 1637
Input Tables
Dr. Ejaz Ahmed 53
Example: Basic Construct of Grouping
• Find the total cars sold in each city from the car_sales table.
City Cars
Dhahran 981
Riyadh 1354
Jeddah 1637
Input Tables
Dr. Ejaz Ahmed 54
Restricting Groups
• HAVING clause is designed for use with GROUP BY clause
to restrict groups that appear in final result table.
• Similar to WHERE, but WHERE filters individual rows
whereas HAVING filters groups.
• Column names in HAVING clause must also appear in the
GROUP BY list or be contained within an aggregate
function.
Dr. Ejaz Ahmed 55
Example: Restricting Groups
• Find the cities who sold a total of more than 1000 cars from the
car_sales table.
SELECT city, SUM(cars_sold) as cars
FROM car_sales
WHERE cars_sold IS NOT NULL
GROUP BY city
HAVING SUM(cars_sold) > 1000 ;
City Cars
Riyadh 1354
Jeddah 1637
Input Tables
Dr. Ejaz Ahmed 56
Aliasing Table Names
• A table alias is created by directly placing an alias after the table
name in the FROM clause.
• The advantage of using a table alias when performing JOIN is
readily apparent when we discuss JOIN later.
• For example in the following example we will refer to departments
table as d or dept.
SELECT d.dname
FROM departments d
WHERE d.dno = 1;
SELECT dept.dname
FROM departments dept
WHERE dept.dno = 1;
Dr. Ejaz Ahmed 57
Nested queries
• Some SQL statements can have a
SELECT embedded within them.
• A subselect can be used in WHERE and
HAVING clauses of an outer SELECT,
where it is called a nested query or a
subquery.
• Subselects may also appear in INSERT,
UPDATE, and DELETEs.
Dr. Ejaz Ahmed 58
Example: Nested queries
• From the Lecturer table, select lecturers
whose salary is above average.
• Cannot write 'WHERE salary >
avg(salary)'.
SELECT AVG(salary)
FROM lecturers
SELECT *
FROM lecturers
WHERE salary > (
);
Inner select
Outer select
 The Inner select is done before the outer select.
Input Tables
Dr. Ejaz Ahmed 59
Nested query: Example
• List the names of all Lecturers who are in
the ICS department
SELECT lname
FROM lecturers
WHERE dno IN (
);
SELECT dno
FROM department
WHERE dname = ‘ICS’
Input Tables
Dr. Ejaz Ahmed 60
Nested Query Rules
• ORDER BY clause may not be used in a subquery (although it may
be used in outermost SELECT).
• Subquery SELECT list must consist of a single column name or
expression, except for subqueries that use EXISTS.
• By default, column names refer to table name in FROM clause of
subquery. Can refer to a table in FROM using an alias.
• When subquery is an operand in a comparison, subquery must
appear on right-hand side.
• A subquery may not be used as an operand in an expression.
Dr. Ejaz Ahmed 61
Nested Query: Example
• Find lecturers whose salary higher than
the salary of at least 1 COE lecturer.
SELECT min(salary)
FROM lecturers
WHERE dno = (
)
SELECT *
FROM Lecturers
WHERE salary > (
);
SELECT DNO
FROM department
WHERE dname = ‘COE’
Input Tables
Dr. Ejaz Ahmed 62
Nested Query: Example
• Find lecturers whose salary higher than the salary of every COE lecturer.
SELECT max(salary)
FROM lecturers
WHERE dno = (
)
SELECT *
FROM Lecturers
WHERE salary > (
);
SELECT DNO
FROM department
WHERE dname = ‘COE’
Input Tables
Dr. Ejaz Ahmed 63
Join
• Can use subqueries provided result columns come from same table.
• If result columns come from more than one table must use a join.
• To perform join, include more than one table in FROM clause.
• Use comma as separator and typically include WHERE clause to
specify join column(s).
• Also possible to use an alias for a table named in FROM clause.
• Alias is separated from table name with a space.
• Alias can be used to qualify column names when there is ambiguity.
Dr. Ejaz Ahmed 64
Example: Join (Inner Join)
• The default type of join is inner join, where arow is included in the
result only if matching row exists in the other relation.
• List each lecturer’s name and his department name.
SELECT a.lname,
b.dname
FROM lecturers a,
departments b
WHERE a.dno = b.dno;
Lname dname
Ahmed
Amin
Hani
Ageel
Yousef
Khalid
ICS
COE
ICS
ICS
COE
COE
Input Tables
PK-FK never makes default join, must
specify Join in SQL
Dr. Ejaz Ahmed 65
Example: Join (Inner Join) …
• To obtain correct rows, include only those
rows from both tables that have identical
values in the dno columns: a.dno = b.dno.
• These two columns are the matching
columns for two tables.
• This type of join is also called inner join
and they equivalent to equi-join in
relational algebra.
Dr. Ejaz Ahmed 66
Computing a Join
• Procedure for generating results of a SELECT with a
join are:
1. Form Cartesian product of the tables named in
FROM clause.
2. If there is a WHERE clause, apply the search
condition to each row of the product table, retaining
those rows that satisfy the condition.
3. For each remaining row, determine the value of each
item in the SELECT list to produce a single row in the
result table.
4. If SELECT DISTINCT has been specified, eliminate
any duplicate rows from the result table.
5. If there is an ORDER BY clause, sort the result table
as required.
Dr. Ejaz Ahmed 67
Outer Joins
• With an inner join, if one row of a table is unmatched,
row is omitted from result table.
• The outer join operations retain rows that do not satisfy
the join condition.
• There are three types of OUTER JOIN
– Left Outer Join
– Right Outer Join
– Full Outer Join
• Lets discuss inner join then we will come back to outer
join.
• Query execution (Performance) is much better than
other joins
Dr. Ejaz Ahmed 68
Outer Join …
• Inner join of departments
and lecturers tables will
result in the following
output.
SELECT a.*, b.*
FROM lecturers a,
Departments b
WHERE a.dno = b.dno
Lid Lname dno salary
1
2
3
4
5
6
Ahmed
Amin
Hani
Ageel
Yousef
Khalid
1
2
1
1
2
2
4000
3700
4200
4000
3500
4500
1
2
1
1
2
2
dno
ICS
COE
COE
ICS
ICS
COE
dname
Input Tables
Dr. Ejaz Ahmed 69
Outer Join …
• Result table has two rows where the dno
are the same.
• There are no rows corresponding to NW
or Abdella.
• To include unmatched rows in result table,
use an outer join.
Dr. Ejaz Ahmed 70
Example: Left Outer Join
• If We want to Include
in the output table the
lecturers whose
department is unknow
we rewrite our
previous query as
follows
SELECT a.*, b.*
FROM lecturers a,
Departments b
WHERE a.dno = b.dno(+)
Lid Lname dno salary
1
2
3
5
6
7
Ahmed
Amin
Hani
Ageel
Yousef
Khalid
1
2
1
1
2
2
4000
3700
4200
4000
3500
4500
1
2
1
1
2
2
dno
SE
COE
COE
ICS
SWE
SWE
dname
4 Addella 4300
Input Tables
select d.dname, e.empno, e.ename
from dept d, emp e
where d.deptno=e.deptno(+);
Dr. Ejaz Ahmed 71
Example: Left Outer Join (3-Tables)…
Dr. Ejaz Ahmed 72
Example: Right Outer Join
• If We want to Include
in the output table the
departments with no
lecturers we rewrite
our previous query as
follows
SELECT a.*, b.*
FROM lecturers a,
Departments b
WHERE a.dno (+) = b.dno
Lid Lname dno salary
1
2
3
5
6
7
Ahmed
Amin
Hani
Ageel
Yousef
Khalid
4
3
1
3
2
2
4000
3700
4200
4000
3500
4500
4
3
1
3
2
2
dno
SE
COE
COE
ICS
SWE
SWE
dname
5 NW
Input Tables
Dr. Ejaz Ahmed 73
Example: Full Outer Join
• If We want to Include in
the output table the
departments with no
lecturers and the
lecturers with unknow
departments we rewrite
our previous query as
follows
SELECT a.*, b.*
FROM lecturers a,
Departments b
WHERE a.dno (+) = b.dno
UNION
SELECT a.*, b.*
FROM lecturers a,
Departments b
WHERE a.dno= b.dno (+);
Lid Lname dno salary
1
2
3
5
6
7
Ahmed
Amin
Hani
Ageel
Yousef
Khalid
4
3
1
3
2
2
4000
3700
4200
4000
3500
4500
4
3
1
3
2
2
dno
SE
COE
COE
ICS
SWE
SWE
dname
5 NW
4 Abdella 4300
Input Tables
Dr. Ejaz Ahmed 74
Characteristic of Outer Join
• Left Outer Join:
– Includes those rows of first (left) table unmatched with rows from second
(right) table.
– Columns from second table are filled with NULLs.
• Right outer Join :
– includes those rows of second (right) table that are unmatched with rows
from first (left) table.
– Columns from first table are filled with NULLs.
• Full Outer Join:
– Is the UNION of both left and right outer joins.
Dr. Ejaz Ahmed 75
Examples: Left, Right and Full
Outer Joins
Dr. Ejaz Ahmed 76
Union, Intersect, and Difference
• Can use normal set operations of union, intersection,
and difference to combine results of two or more queries
into a single result table.
• Union of two tables, A and B, is table containing all rows
in either A or B or both.
• Intersection is table containing all rows common to both
A and B.
• Difference is table containing all rows in A but not in B.
• Two tables must be union compatible.
• If ALL specified, result can include duplicate rows
Dr. Ejaz Ahmed 77
Example: Use of UNION
• List all the ICS and COE
faculty salaries.
Remove duplicates
SELECT salary
FROM lecturers
WHERE dno = 1
UNION
SELECT salary
FROM lecturers
WHERE dno = 2;
 List all the ICS and COE faculty
salaries. Include duplicates
SELECT salary
FROM lecturers
WHERE dno = 1
UNION ALL
SELECT salary
FROM lecturers
WHERE dno = 2;
Input Tables
Dr. Ejaz Ahmed 78
Example: Use of UNION …
• List all the ICS and COE
faculty salaries. Remove
duplicates
SELECT salary
FROM lecturers
WHERE dno =
( SELECT dno
FROM departments
WHERE dname= ‘ICS’
)
UNION
SELECT salary
FROM lecturers
WHERE dno =
( SELECT dno
FROM departments
WHERE dname= ‘COE’
)
 List all the ICS and COE faculty
salaries. Include duplicates
SELECT salary
FROM lecturers
WHERE dno =
( SELECT dno
FROM departments
WHERE dname= ‘ICS’
)
UNION ALL
SELECT salary
FROM lecturers
WHERE dno =
( SELECT dno
FROM departments
WHERE dname= ‘COE’
)
Input Tables
Dr. Ejaz Ahmed 79
Example: Use of DIFFERENCE
• List salaries that are taken by ICS and not COE lecturers.
SELECT salary
FROM lecturers
WHERE dno = (
SELECT dno
FROM departments
where dname= ‘ICS’
)
MINUS
SELECT salary
FROM lecturers
WHERE dno = (
SELECT dno
FROM departments
WHERE dname= ‘COE’
)
Input Tables
Dr. Ejaz Ahmed 80
Example: Use of INTESECTION
• List salaries that are taken by both COE and ICS lecturers.
SELECT salary
FROM lecturers
WHERE dno = (
SELECT dno
FROM departments
where dname= ‘ICS’
)
INTERSECTION
SELECT salary
FROM lecturers
WHERE dno = (
SELECT dno
FROM departments
WHERE dname= ‘COE’
)
Produces result tables from both
queries and creates single result
table consisting of those rows that
are common to both result tables.
Input Tables
Dr. Ejaz Ahmed 81
Other SQL Operators
• IN (covered)
• BETWEEN (covered)
• LIKE (covered)
• ANY (SOME)
• ALL
• EXISTS
• NOT EXISTS
Dr. Ejaz Ahmed 82
ANY (SOME) and ALL
• ANY and ALL may be used with subqueries that produce a single
column of numbers.
• If subquery preceded by ALL, condition will only be true if it is
satisfied by all values produced by subquery.
• If subquery preceded by ANY, condition will be true if it is satisfied
by any values produced by subquery.
• If subquery is empty, ALL returns true, ANY returns false.
• ISO standard allows SOME to be used in place of ANY.
Dr. Ejaz Ahmed 83
Example using the SOME
Operator
• Find lecturers whose salary higher than
the salary of at least 1 COE lecturer.
SELECT salary
FROM lecturers
WHERE dno = (
)
SELECT *
FROM Lecturers
WHERE salary > SOME (
);
SELECT DNO
FROM department
WHERE dname = ‘COE’
Input Tables
Dr. Ejaz Ahmed 84
Example Using the ALL
Operator
• Find lecturers whose salary higher than the salary of every COE lecturer.
SELECT salary
FROM lecturers
WHERE dno = (
)
SELECT *
FROM Lecturers
WHERE salary > ALL (
);
SELECT DNO
FROM department
WHERE dname = ‘COE’
Dr. Ejaz Ahmed 85
EXISTS and NOT EXISTS
• EXISTS and NOT EXISTS are for use only with subqueries specially with
correlated subqueries. A correlated subquery is a subquery where some
attributes of the outer select are used in the inner select.
• They produce a simple true/false result.
• EXISTS is true if and only if there exists at least one row in result table
returned by subquery.
• It is false if subquery returns an empty result table.
• NOT EXISTS is the opposite of EXISTS.
• Since EXISTS and NOT EXISTS check only for existence or non-existence
of rows in subquery result table, subquery can contain any number of
columns.
Dr. Ejaz Ahmed 86
--- Example using the EXISTS
Operator
• Find all ICS lecturers.
SELECT *
FROM lecturers a
WHERE EXISTS
(
SELECT 1
FROM department b
WHERE a.dno = b.dno
AND b.dname = ‘ICS‘
);
Input Tables
Dr. Ejaz Ahmed 87
Example using the NOT
EXISTS Operator
• Find all non ICS
lecturers.
SELECT *
FROM lecturers a
WHERE NOT EXISTS
(
SELECT 1
FROM department b
WHERE a.dno = b.dno
AND b.dname = ‘ICS‘
);
Dr. Ejaz Ahmed 88
More SQL Functions
• SUBSTR
• INSTR
• LENGTH
• LEFT, RIGHT
• LPAD, RPAD
• TRIM
• DECODE
• CEIL
• ROWNUM
TO_CHAR
TO_DATE
TO_NUMBER
ADD_MONTHS
FLOOR
SYSDATE
NVL
TRANSLATE
Dr. Ejaz Ahmed 89
SQL Data Definition Statements
(DDL)
• CREATE SCHEMA and DROP SCEHMA +
• CREATE TABLE +
• ALTER TABLE +
• DROP TABLE +
Dr. Ejaz Ahmed 90
CREATE SCHEMA and DROP
SCHEMA
CREATE SCHEMA [name| AUTHORIZATION creator_id ];
Example: CREATE USER COMPANY IDENTIFIED BY password;
DROP SCHEMA name [RESTRICT | CASCADE ];
Example: DROP USER COMPANY CASCADE;
• With RESTRICT (default), schema must be empty or operation fails.
• With CASCADE, operation cascades to drop all objects associated with
schema in the order defined above. If any of these operations fail, DROP
SCHEMA fails.
Dr. Ejaz Ahmed 91
CREATE TABLE
CREATE TABLE table_name
(col_name data_type [NULL | NOT NULL] [,...]);
• Creates a table with one or more columns of the specified
data_type.
• NULL (default) indicates whether column can contain nulls.
• With NOT NULL, system rejects any attempt to insert a null in the
column.
• Primary keys should always be specified as NOT NULL.
• Foreign keys are often (but not always) candidates for NOT NULL.
Dr. Ejaz Ahmed 92
CREATE TABLE – Example 1
CREATE TABLE Employee
(
fname VARCHAR2(15) NOT NULL,
minit CHAR,
lname VARCHAR2(15) NOT NULL,
ssn CHAR(9),
bdate DATE,
address VARCHAR2(50),
sex CHAR,
salary NUMBER(10,2) NOT NULL,
Superssn CHAR(9),
dno NUMBER(3) NOT NULL,
CONSTRAINT employee_ssn_pk PRIMARY KEY(ssn),
CONSTRAINT employee_superssn_fk
FOREIGN KEY(Superssn) REFERENCES employee(ssn),
CONSTRAINT employee_dno_fk
FOREIGN KEY(dno) REFERENCES department(dnumber),
);
Dr. Ejaz Ahmed 93
CREATE TABLE – Example 2
CREATE TABLE department
(
dname VARCHAR2(15) NOT NULL,
dnumber NUMBER(3) NOT NULL,
mgrssn CHAR(9),
mgrStartDateDATE,
CONSTRAINT department_dnumber_pk
PRIMARY KEY(dnumber),
CONSTRAINT department_mgrssn_fk
FOREIGN KEY(mgrssn) REFERENCES employee(ssn)
);
Dr. Ejaz Ahmed 94
DROP TABLE
DROP TABLE tbl_name [RESTRICT | CASCADE]
e.g. DROP TABLE employee;
• Removes named table and all rows within it.
• With RESTRICT, if any other objects depend for their existence on
continued existence of this table, SQL does not allow request.
• With CASCADE, SQL drops all dependent objects (and objects
dependent on these objects).
Dr. Ejaz Ahmed 95
ALTER TABLE
• The ALTER command is a schema modification command.
• It is used to add or drop a column, change a column definition, add or
drop table constraints.
Examples:
ALTER TABLE COMPANY.EMPLOYEE
MODIFY(lname VARCHAR2(30));
ALTER TABLE EMP
ADD Constraints pk_emp primary key (EMPNO);
ALTER TABLE EMP
ADD CONSTRAINTS FK_DEPTNO FOREIGN KEY (DEPTNO)
REFERENCES DEPT(DEPTNO);
Dr. Ejaz Ahmed 96
SQL Data Manipulation
Statements (DML)
• INSERT Statement +
• UPDATE Statement +
• DELETE Statement +
• Note: Use following control commands for above
SQL
• Commit for DO or confirm
• Rollback for UNDO
Dr. Ejaz Ahmed 97
INSERT Statement
• Definition of INSERT Statement +
• Types of INSERT Statement +
• INSERT and Integrity Constraints +
Dr. Ejaz Ahmed 98
Definition of INSERT Statement
• INSERT is used to add a single row to a
table where we specify the relation name
and a list of values for the row.
• There are three types of INSERT
Statement:
– INSERT With Column list +
– INSERT Without Column list +
– INSERT with SELECT Statement +
Dr. Ejaz Ahmed 99
INSERT with Column list
INSERT INTO table_name (column_list) VALUES
(data_value_list);
• Example: INSERT INTO employee(fname, lname, ssn, salary,
dno)
VALUES (‘Majid', ‘Al-Ghamdi', ‘1111111', 4000,
123);
• data_value_list must match column_list as follows:
– Number of items in each list must be the same.
– Must be direct correspondence in position of items in two lists.
– Data type of each item in data_value_list must be compatible
with data type of corresponding column.
– If one of the table columns is omitted from the column_list It
must also be omitted from the data_value_list and make sure it
is nullable.
Dr. Ejaz Ahmed 100
INSERT without Column List
INSERT INTO table_name VALUES (data_value_list);
• Example: INSERT INTO employee
VALUES (‘Adel', NULL, ‘Al-Eid', ‘222222’,
NULL, NULL, NULL, NULL, NULL, 1);
• data_value_list must match the columns
of the table as follows:
– Number of items in the list must be equal to
the number of columns of the table.
– Data type of corresponding items must be
compatible.
Dr. Ejaz Ahmed 101
INSERT … SELECT
• Second form of INSERT allows multiple rows to
be copied from one or more tables to another:
INSERT INTO table_name [ (column_list) ]
SELECT ...
Example:
INSERT INTO Table1 (A1, A2, A3)
SELECT B1, B2, B3 FROM Table2;
Dr. Ejaz Ahmed 102
INSERT and Integrity
Constraints
• A DBMS that fully implement SQL2 should
support and enforce all the integrity constraints
that can be specified in the DDL.
• A DBMS enforcing NOT NULL will reject an
INSERT command in which an attribute
declared to be NOT NULL does not have a
value.
• A DBMS not supporting referential integrity will
allow insertion even if the referential integrity
constraint is violated.
Dr. Ejaz Ahmed 103
UPDATE
• Definition +
• Examples
– Update All Rows +
– Update Specific Rows +
– Update Multiple Columns +
Dr. Ejaz Ahmed 104
UPDATE Definition …
• The UPDATE command is used to modify attribute values of one or
more selected rows.
UPDATE table_name
SET column_name1 = data_value1
[, column_name2 = data_value2...]
[WHERE search_condition]
• table_name can be name of a base table or an updatable view.
• SET clause specifies names of one or more columns that are to be
updated.
Dr. Ejaz Ahmed 105
UPDATE Definition …
• WHERE clause is optional:
– If omitted, named columns are updated for all
rows in table.
– If specified, only those rows that satisfy
search_condition are updated.
• New data_value(s) must be compatible
with data type for corresponding column.
Dr. Ejaz Ahmed 106
Example: UPDATE All Rows
Give all employees a 3% pay increase.
UPDATE staff
SET salary = salary*1.03;
Dr. Ejaz Ahmed 107
Example: UPDATE Specific
Rows
• Give all Employees in Department one a
5% pay increase.
UPDATE employee
SET salary = salary*1.05
WHERE dno = 1;
• WHERE clause finds rows that contain
data for dno = 1. Update is applied only to
these particular rows.
Dr. Ejaz Ahmed 108
Example: UPDATE Multiple
Columns
• Change Adel’s department to 2 and his
Salary to 4,000. Assume Adel’s ssn =
111;
UPDATE employee
SET dno = 2
, salary = 4000
WHERE ssn = ‘111’;
Dr. Ejaz Ahmed 109
DELETE
• DELETE Definition +
• DELETE Example +
Dr. Ejaz Ahmed 110
DELETE Definition
• A DELETE command removes rows from a table and may include a
where-clause.
• Rows are explicitly deleted from only one table at a time. However,
the deletion may propagate to rows in other tables if referential
triggered actions are specified in the referential integrity constraints
of the DDL.
DELETE FROM table_name [WHERE search_condition]
• table_name can be name of a base table or an updatable view.
• The WHERE clause is optional; if omitted, all rows are deleted from
table. But if it is included only those rows that satisfy the
search_condition are deleted.
Dr. Ejaz Ahmed 111
Example: DELETE
• Delete all records from employee.
DELETE FROM employee;
• Delete all employees in department 1.
DELETE FROM employee
WHERE dno = 1;

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)Sabana Maharjan
 
Integrity constraints in dbms
Integrity constraints in dbmsIntegrity constraints in dbms
Integrity constraints in dbmsVignesh Saravanan
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functionsfarwa waqar
 
Sql Basics | Edureka
Sql Basics | EdurekaSql Basics | Edureka
Sql Basics | EdurekaEdureka!
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Trainingbixxman
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries InformationNishant Munjal
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Salman Memon
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands1keydata
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL CommandsShrija Madhu
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In SqlAnurag
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Punjab University
 

Was ist angesagt? (20)

Sql Tutorials
Sql TutorialsSql Tutorials
Sql Tutorials
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Sql and Sql commands
Sql and Sql commandsSql and Sql commands
Sql and Sql commands
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
SQL
SQLSQL
SQL
 
Integrity constraints in dbms
Integrity constraints in dbmsIntegrity constraints in dbms
Integrity constraints in dbms
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Sql Basics | Edureka
Sql Basics | EdurekaSql Basics | Edureka
Sql Basics | Edureka
 
Sql commands
Sql commandsSql commands
Sql commands
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
 

Ähnlich wie SQL Queries

sql ppt.pptx
sql ppt.pptxsql ppt.pptx
sql ppt.pptxArunT58
 
Less07 schema
Less07 schemaLess07 schema
Less07 schemaImran Ali
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusChhom Karath
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343Edgar Alejandro Villegas
 
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptxFayChan8
 
Islamic University Previous Year Question Solution 2018 (ADBMS)
Islamic University Previous Year Question Solution 2018 (ADBMS)Islamic University Previous Year Question Solution 2018 (ADBMS)
Islamic University Previous Year Question Solution 2018 (ADBMS)Rakibul Hasan Pranto
 
Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Vidyasagar Mundroy
 
Structure query language (sql)
Structure query language (sql)Structure query language (sql)
Structure query language (sql)Nalina Kumari
 
chapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfchapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfstudy material
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptxSheethal Aji Mani
 

Ähnlich wie SQL Queries (20)

sql ppt.pptx
sql ppt.pptxsql ppt.pptx
sql ppt.pptx
 
SQL 3.pptx
SQL 3.pptxSQL 3.pptx
SQL 3.pptx
 
Less07 schema
Less07 schemaLess07 schema
Less07 schema
 
sql-commands.pdf
sql-commands.pdfsql-commands.pdf
sql-commands.pdf
 
Sql commands
Sql commandsSql commands
Sql commands
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*Plus
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
 
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx
 
Islamic University Previous Year Question Solution 2018 (ADBMS)
Islamic University Previous Year Question Solution 2018 (ADBMS)Islamic University Previous Year Question Solution 2018 (ADBMS)
Islamic University Previous Year Question Solution 2018 (ADBMS)
 
DBMS UNIT 3
DBMS UNIT 3DBMS UNIT 3
DBMS UNIT 3
 
Module02
Module02Module02
Module02
 
Database part2-
Database part2-Database part2-
Database part2-
 
Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Structure query language (sql)
Structure query language (sql)Structure query language (sql)
Structure query language (sql)
 
Reviewing SQL Concepts
Reviewing SQL ConceptsReviewing SQL Concepts
Reviewing SQL Concepts
 
chapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfchapter-14-sql-commands.pdf
chapter-14-sql-commands.pdf
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptx
 

Mehr von Nilt1234

Lisp tutorial
Lisp tutorialLisp tutorial
Lisp tutorialNilt1234
 
INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISPNilt1234
 
relational algebra (joins)
relational algebra (joins)relational algebra (joins)
relational algebra (joins)Nilt1234
 
relational algebra-(basics)
 relational algebra-(basics) relational algebra-(basics)
relational algebra-(basics)Nilt1234
 
Artificial Intelligence
Artificial IntelligenceArtificial Intelligence
Artificial IntelligenceNilt1234
 
SQL Queries
SQL QueriesSQL Queries
SQL QueriesNilt1234
 
introduction of Database
introduction of Databaseintroduction of Database
introduction of DatabaseNilt1234
 
Database Architecture
Database Architecture Database Architecture
Database Architecture Nilt1234
 
What is Artificial Intelligence
What is Artificial IntelligenceWhat is Artificial Intelligence
What is Artificial IntelligenceNilt1234
 
Entity Relationship Diagaram
Entity Relationship DiagaramEntity Relationship Diagaram
Entity Relationship DiagaramNilt1234
 

Mehr von Nilt1234 (13)

Lisp tutorial
Lisp tutorialLisp tutorial
Lisp tutorial
 
INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISP
 
Lec 09
Lec 09Lec 09
Lec 09
 
relational algebra (joins)
relational algebra (joins)relational algebra (joins)
relational algebra (joins)
 
relational algebra-(basics)
 relational algebra-(basics) relational algebra-(basics)
relational algebra-(basics)
 
Artificial Intelligence
Artificial IntelligenceArtificial Intelligence
Artificial Intelligence
 
Lec 17
Lec  17Lec  17
Lec 17
 
Lec 06
Lec 06Lec 06
Lec 06
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
introduction of Database
introduction of Databaseintroduction of Database
introduction of Database
 
Database Architecture
Database Architecture Database Architecture
Database Architecture
 
What is Artificial Intelligence
What is Artificial IntelligenceWhat is Artificial Intelligence
What is Artificial Intelligence
 
Entity Relationship Diagaram
Entity Relationship DiagaramEntity Relationship Diagaram
Entity Relationship Diagaram
 

Kürzlich hochgeladen

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 

Kürzlich hochgeladen (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 

SQL Queries

  • 2. Dr. Ejaz Ahmed 2 Objectives • Example Tables • Introduction • ISO SQL Data Types • Comparison Operators in SQL • Logical Operators in SQL • Arithmetic Operators in SQL • SQL Schema and Catalog • SQL Data Definition Statements (DDL) • SQL Data Manipulation Statements (DML) • Other SQL Operators
  • 3. Dr. Ejaz Ahmed 3 Example Table … Car_Sales City Year Cars_sol d Dhahran 2001 525 Dhahran 2002 456 Riyadh 2001 700 Riyadh 2002 654 Jeddah 2001 921 Jeddah 2002 752 Khobar 2002
  • 4. Dr. Ejaz Ahmed 4 Example: Tables … 1 2 3 ICS COE SWE dno dname Lid Lname dno salary 1 2 3 4 5 6 7 Ahmed Amin Hani Abdallah Ageel Yousef Khalid 1 2 1 1 2 2 4000 3700 4200 4300 4000 3500 4500 Departments Lecturers
  • 5. Dr. Ejaz Ahmed 5 Objectives of SQL • Ideally, database language should allow user to: – create the database and relation structures; – perform insertion, modification, deletion of data from relations; – perform simple and complex queries. • Must perform these tasks with minimal user effort and command structure and syntax must be easy to learn. • It must be portable. • SQL does not contain flow control commands. These must be implemented using a programming or job-control language, or interactively by the decisions of the user.
  • 6. Dr. Ejaz Ahmed 6 Objectives of SQL … • SQL is relatively easy to learn: – It is a non-procedural language - you specify what information you require, rather than how to get it. – It is essentially free-format. • Can be used by a range of users including DBAs, management, application programmers, and other types of end users. • An ISO standard now exists for SQL, making it both the formal and de facto standard language for relational databases.
  • 7. Dr. Ejaz Ahmed 7 Objectives of SQL … • Consists of standard English words: CREATE TABLE staff( sno VARCHAR(5), lname VARCHAR(15), salary NUMBER(7,2) ); INSERT INTO staff VALUES ('SG16', 'Brown', 8300); SELECT sno, lname, salary FROM staff WHERE salary > 10000;
  • 8. Dr. Ejaz Ahmed 8 History of SQL … • In 1974, D. Chamberlin (IBM San Jose Laboratory) defined language called 'Structured English Query Language' or SEQUEL. • A revised version SEQUEL/2 was defined in 1976 but name was subsequently changed to SQL for legal reasons. • Still pronounced 'see-quel', though official pronunciation is 's-q-l'. • IBM subsequently produced a prototype DBMS called System R, based on SEQUEL/2. • Roots of SQL, however, are in SQUARE (Specifying Queries as Relational Expressions), which predates System R project.
  • 9. Dr. Ejaz Ahmed 9 History of SQL … • In late 70s, ORACLE appeared and was probably first commercial RDBMS based on SQL. • In 1987, ANSI and ISO published an initial standard for SQL. • In 1989, ISO published an addendum that defined an 'Integrity Enhancement Feature'. • In 1992, first major revision to ISO standard occurred, referred to as SQL2 or SQL/92.
  • 10. Dr. Ejaz Ahmed 10 Importance of SQL … • SQL has become part of application architectures such as IBM's Systems Application Architecture (SAA). • It is strategic choice of many large and influential organizations (e.g. X/OPEN). • SQL is Federal Information Processing Standard (FIPS) to which conformance is required for all sales of databases to American Government.
  • 11. Dr. Ejaz Ahmed 11 Importance of SQL … • SQL Access Group trying to define enhancements that will support interoperability across disparate systems. • SQL is used in other standards and even influences development of other standards as a definitional tool. Examples include: – ISO's Information Resource Directory System (IRDS) Standard – Remote Data Access (RDA) Standard.
  • 12. Dr. Ejaz Ahmed 12 Components of SQL • A database language must have support for the components listed below. Most implementations of SQL support various components listed below: – Data Definition Language (DDL) – Interactive Data Manipulation Language (Interactive DML) – Embedded Data Manipulation Language (Embedded DML) – Views – Integrity and transaction control – Authorization & Security (DCL) – Catalog and dictionary facility.
  • 13. Dr. Ejaz Ahmed 13 Basic Guidelines for Writing SQL Statements … • SQL statement consists of reserved words and user-defined words. – Reserved words are a fixed part of SQL and must be spelt exactly as required and cannot be split across lines. – User-defined words are made up by user and represent names of various database objects such as relations, columns, views. • Most components of an SQL statement are case insensitive, except for literal character data. • More readable with indentation and lineation: – Each clause should begin on a new line. – Start of a clause should line up with start of other clauses. – If clause has several parts, should each appear on a separate line and be indented under start of clause.
  • 14. Dr. Ejaz Ahmed 14 Basic Guidelines for Writing SQL Statements … • Use extended form of BNF notation: – Upper case letters represent reserved words. – Lower case letters represent user-defined words. – | indicates a choice among alternatives. – Curly braces indicate a required element. – Square brackets indicate an optional element. – … indicates optional repetition (0 or more). – ALL SQL is case less
  • 15. Dr. Ejaz Ahmed 15 ISO SQL Data Types
  • 16. Dr. Ejaz Ahmed 16 Comparison Operators in SQL • There are six comparison operators in SQL. These operators are used to build conditions that are used in the WHERE clause of a DML statement: Operator Meaning = <> < > <= >= Equal Not Equal Less than Greater than Less than or Eqaul Greater than or Eqaul
  • 17. Dr. Ejaz Ahmed 17 Logical Operators in SQL • There are three logical operators that help us to build compound conditions to be used in the WHERE clause of the SELECT statement. – The AND operator joins two or more conditions, and display a row only if that row’s data satisfies ALL the specified conditions. – The OR operator joins two or more conditions, and display a row only if that row’s data satisfies any of the specified conditions. – The NOT is a unary operator, and is used to negates a condition.
  • 18. Dr. Ejaz Ahmed 18 Arithmetic Operators in SQL • Another feature of SQL allows the use of arithmetic in queries. – The standard arithmetic operators ( +, -, /, *) can be applied to numeric values or attributes with numeric domain. – The arithmetic operators can be used in expressions in the SELECT and the WHERE clauses to compute numeric values. – All attributes that can be computed using arithmetic expressions (such as age from birth date, annual salary from monthly salary) must be eliminated as part of a good design practice in databases.
  • 19. Dr. Ejaz Ahmed 19 SQL Schema and Catalog • In SQL92, relations and other database objects exist in an environment. • Each environment contains one or more catalogs, and each catalog consists of set of schemas. • Schema is a named collection of related database objects. • Objects in a schema can be tables, views, domains, constraints, translations, and character sets. All have same owner.
  • 20. Dr. Ejaz Ahmed 20 SELECT • SELECT Definition • Selecting Columns • Selecting Rows • Sorting • Aggregation • Grouping • Restricting Groups • Aliasing Table Names • Nested Queries • Join • Set Operations
  • 21. Dr. Ejaz Ahmed 21 SELECT Definition … • SQL has only one statement for retrieving information from a database called the SELECT statement. • SQL SELECT statement is different from that of Relational Algebra. • An important distinction between SQL and formal relational model is that SQL allows duplicate rows. Hence an SQL table is not a set but a multiset (some times called a bag) of tuples.
  • 22. Retrieving Information From the Database DB Data JohnSmith Mary Stiles 22Dr. Ejaz Ahmed
  • 24. SQL - Usage 24Dr. Ejaz Ahmed
  • 25. Dr. Ejaz Ahmed 25 SELECT Definition … • A SELECT statement can consist up to six clauses. SELECT [DISTINCT | ALL] {* | [column_expression [AS new_name]] [,...] } FROM table_name [alias] [, ...] [WHERE condition] [GROUP BY column_list] [HAVING condition] [ORDER By column_list] • Only SELECT and FROM clauses are mandatory. • Order of the clauses cannot be changed.
  • 26. Dr. Ejaz Ahmed 26 SELECT Definition … • FROM Specifies table(s) to be used. • WHERE Filters rows. • GROUP BY Forms groups of rows with same column value. • HAVING Filters groups subject to some condition. • SELECT Specifies which columns are to appear in output. • ORDER BY Specifies the order of the output.
  • 27. Dr. Ejaz Ahmed 27 Selecting Columns • Selecting all columns + • Selecting Specific columns + • Selecting Computed columns + • Renaming Columns +
  • 28. Dr. Ejaz Ahmed 28 Selecting All Columns Example 1: SELECT city, year, cars_sold FROM car_sales; • Can use * as an abbreviation for 'all columns': Example 2: SELECT * FROM car_sales; City Year Cars_sol d Dhahran 2001 525 Dhahran 2002 456 Riyadh 2001 700 Riyadh 2002 654 Jeddah 2001 921 Jeddah 2002 752 Khobar 2002 Input Tables
  • 29. Dr. Ejaz Ahmed 29 Selecting Specific Columns • Selected columns can be listed as shown in the following example. Notice that the year column was not selected so it doesn’t appear in the output. Example: SELECT city, cars_sold FROM car_sales; City Cars_sold Dhahran 525 Dhahran 456 Riyadh 700 Riyadh 654 Jeddah 921 Jeddah 752 Khobar Input Tables
  • 30. Dr. Ejaz Ahmed 30 Selecting Computed Columns • If the value of a car is 100,000 then the total sales per year for each city is computed as follows. Example: SELECT city ,year ,cars_sold ,cars_sold * 100000 FROM car_sales; Dhahran Dhahran Riyadh Riyadh Jeddah Jeddah 2001 2002 2001 2002 2001 2002 525 456 700 654 921 752 City Year Cars_Sold 52500000 45600000 70000000 65400000 92100000 75200000 Cars_Sold *100000 Khobar 2002 00 Input Tables
  • 31. Dr. Ejaz Ahmed 31 Renaming Columns • The name of the computed column in the last slide cab be changed from cars_sold*100000 to sales as follows. Example: SELECT city ,year ,cars_sold As Sold ,cars_sold * 100000 AS sales FROM car_sales; Dhahran Dhahran Riyadh Riyadh Jeddah Jeddah 2001 2002 2001 2002 2001 2002 525 456 700 654 921 752 City Year Sold 52500000 45600000 70000000 65400000 92100000 75200000 sales Khobar 2002 00 Input Tables
  • 32. Dr. Ejaz Ahmed 32 Selecting Rows • Selecting All Rows + • Partial match Search + • Range Search + • Set Membership Search + • Pattern matching Search + • Null Search + • Removing Duplicate Rows +
  • 33. Dr. Ejaz Ahmed 33 Selecting All Rows • A SELECT statement without a WHERE clause selects all rows. Example: SELECT * FROM car_sales; Dhahran Dhahran Riyadh Riyadh Jeddah Jeddah 2001 2002 2001 2002 2001 2002 525 456 700 654 921 752 City Year Cars_Sold Khobar 2002 Input Tables
  • 34. Dr. Ejaz Ahmed 34 Selecting Rows • To Select certain rows of a table you need to use the WHERE clause of the SELECT statement. • The WHERE clause has a condition which is a logical expression. • The Where condition consists of: – Comparison Operators – Logical Operators – Arithmetic Operators – Other SQL constructs which will be discussed later. • A record to be selected it must make the WHERE logical expression true. In other words it must satisfy the where condition.
  • 35. Dr. Ejaz Ahmed 35 Partial match Search • Selecting all the records whose column values match the column values specified in the WHERE clause. Example1: SELECT * FROM car_sales WHERE city = ‘Dhahran’; Dhahran Dhahran 2001 2002 525 456 City Year Cars_Sold Dhahran 2002 456 City Year Cars_Sold Example2: SELECT * FROM car_sales WHERE city = ‘Dhahran’ AND year > 2001; Input Tables
  • 36. Dr. Ejaz Ahmed 36 Range Search Example: SELECT * FROM car_sales WHERE cars_sold >= 525 AND cars_sold <= 752; OR SELECT * FROM car_sales WHERE cars_sold BETWEEN 525 AND 752; Dhahran Riyadh Riyadh Jeddah 2001 2001 2002 2002 525 700 654 752 City Year Sold Selecting all the records whose column values is between the values specified in the WHERE cluause.  BETWEEN test includes the endpoints of range. NOT BETWEEN list the one not in the range. Input Tables
  • 37. Dr. Ejaz Ahmed 37 Set Membership Search … Example: SELECT * FROM car_sales WHERE city IN (‘Dhahran’, ‘Riyadh’); Selecting all the records whose column value is a member of the set specified in the WHERE clause. Dhahran Dhahran Riyadh Riyadh 2001 2002 2001 2002 525 456 700 654 City Year Sold Input Tables
  • 38. Dr. Ejaz Ahmed 38 Set Membership Search Example: SELECT * FROM car_sales WHERE city NOT IN (‘Dhahran’, ‘Riyadh’); Selecting all the records whose column value not a member of the set specified in the WHERE clause. Jeddah Jeddah 2001 2002 921 752 City Year Sold Khobar 2002 Input Tables
  • 39. Dr. Ejaz Ahmed 39 Pattern Matching Search … • SQL has two special pattern matching symbols: – %: sequence of zero or more characters; – _ (underscore): any single character. • LIKE '%dd%' means a sequence of characters of any length containing ‘dd'.
  • 40. Dr. Ejaz Ahmed 40 Pattern matching Search Example: SELECT * FROM car_sales WHERE city LIKE ‘J%’ Selecting all the records whose column value match the pattern specified in the WHERE clause. Jeddah Jeddah 2001 2002 921 752 City Year Sold Example: SELECT * FROM car_sales WHERE city LIKE ‘%dd%’ Jeddah Jeddah 2001 2002 921 752 City Year Sold Input Tables
  • 41. Dr. Ejaz Ahmed 41 NULL Search Example 1: Select all cities where the number of cars sold is unkown. SELECT city FROM car_sales WHERE cars_sold IS NULL; City Khoba r Example 2: Select all cities where the number of cars sold is kown. SELECT city FROM car_sales WHERE cars_sold IS NOT NULL; City Dhahran Riyadh Jeddah Dhahran Riyadh Jeddah Input Tables
  • 42. Dr. Ejaz Ahmed 42 Removing Duplicate Rows Example1: SELECT city FROM car_sales Example2: SELECT DISTINCT city FROM car_sales Dhahran Dhahran Riyadh Riyadh Jeddah Jeddah City Dhahran Riyadh Jeddah City Using DISTINCT in the SELECT clause removes duplicate rows from the output table Khobar Khobar Input Tables
  • 43. Dr. Ejaz Ahmed 43 Sorting • The ORDER BY clause specifies an order for displaying the result of a query. – SQL allows the user to order the tuples in the result of a query by the values of one or more attributes; the default order is ascending or increasing. – The keyword DESC is specified to sort in a descending order of values while the keyword ASC can be used to specify ascending order explicitly. – The sorting will be applied alphabetically or numerically depending on the type of the column attribute.
  • 44. Dr. Ejaz Ahmed 44 Example: Sorting Example: The following SELECT statement sorts the car_sales table in ascending order of city and descending order of car_sales columns SELECT * FROM car_sales ORDER BY city asc, car_sales desc; Dhahran Dhahran Riyadh Riyadh Jeddah Jeddah 2001 2002 2001 2002 2001 2002 525 456 700 654 921 752 City Year Cars_Sold Khobar 2002 Input Tables
  • 45. Dr. Ejaz Ahmed 45 Aggregation … • ISO standard defines five aggregate functions: – COUNT returns number of values in a specified column. – SUM returns sum of values in a specified column. – AVG returns average of values in a specified column. – MIN returns smallest value in a specified column. – MAX returns largest value in a specified column.
  • 46. Dr. Ejaz Ahmed 46 Aggregation … • Each operates on a single column of a table and return single value. • COUNT, MIN, and MAX apply to numeric and non-numeric fields, but SUM and AVG may be used on numeric fields only. • Apart from COUNT(*), each function eliminates nulls first and operates only on remaining non-null values. • COUNT(*) counts all rows of a table, regardless of whether nulls or duplicate values occur. • Can use DISTINCT before column name to eliminate duplicates.
  • 47. Dr. Ejaz Ahmed 47 Aggregation … • DISTINCT has no effect with MIN/MAX, but may have with SUM/AVG. • Aggregate functions can be used only in SELECT list and in HAVING clause. • If SELECT list includes an aggregate function and there is no GROUP BY clause, then SELECT list cannot reference a column with an aggregate function. For example, following is illegal: SELECT city, COUNT(*) FROM car_sales;
  • 48. Dr. Ejaz Ahmed 48 Example : COUNT • How many rows are there in the car_sales table? SELECT COUNT(*) as Rows FROM car_sales Rows 7  How many cities are there in the car_sales table? SELECT COUNT(DISTINCT city) as city FROM car_sales city 4 Input Tables
  • 49. Dr. Ejaz Ahmed 49 Example : SUM • Find the total number of all the cars sold from the car_sales table? SELECT SUM(cars_sold) as cars_sold FROM car_sales Cars_sold 4008  Find the number of all the cars_sold in Dhahran from the car_sales table? SELECT SUM(cars_sold) as Dah_cars FROM car_sales WHERE city = ‘Dhahran’ Dah_cars 981 Input Tables
  • 50. Dr. Ejaz Ahmed 50 Example: MIN, MAX, AVG • Find the minimum, maximum, and average cars_sold per year and per city form the car_sales table SELECT MIN(cars_sold) as Min_sold , MAX(cars_sold) as Max_sold , AVG(cars_sold) as Avg_sold FROM car_sales WHERE car_sales IS NOT NULL; Min_sold Max_sold Avg_sold 456 921 668 Input Tables
  • 51. Dr. Ejaz Ahmed 51 Grouping • Use GROUP BY clause to get sub-totals. • SELECT and GROUP BY closely integrated: each item in SELECT list must be single-valued per group, and SELECT clause may only contain: – Column names. – Aggregate functions. – Constants. – An expression involving combinations of the above. • All column names in SELECT list must appear in GROUP BY clause unless name is used only in an aggregate function. • If WHERE is used with GROUP BY, WHERE is applied first, then groups are formed from remaining rows satisfying predicate. • ISO considers two nulls to be equal for purposes of GROUP BY.
  • 52. Dr. Ejaz Ahmed 52 Example: Grouping • Find the total cars sold in each city from the car_sales table. SELECT city, SUM(cars_sold) as cars FROM car_sales WHERE cars_sold IS NOT NULL GROUP BY city ORDER BY SUM(cars_sold) ; City Cars Dhahran 981 Riyadh 1354 Jeddah 1637 Input Tables
  • 53. Dr. Ejaz Ahmed 53 Example: Basic Construct of Grouping • Find the total cars sold in each city from the car_sales table. City Cars Dhahran 981 Riyadh 1354 Jeddah 1637 Input Tables
  • 54. Dr. Ejaz Ahmed 54 Restricting Groups • HAVING clause is designed for use with GROUP BY clause to restrict groups that appear in final result table. • Similar to WHERE, but WHERE filters individual rows whereas HAVING filters groups. • Column names in HAVING clause must also appear in the GROUP BY list or be contained within an aggregate function.
  • 55. Dr. Ejaz Ahmed 55 Example: Restricting Groups • Find the cities who sold a total of more than 1000 cars from the car_sales table. SELECT city, SUM(cars_sold) as cars FROM car_sales WHERE cars_sold IS NOT NULL GROUP BY city HAVING SUM(cars_sold) > 1000 ; City Cars Riyadh 1354 Jeddah 1637 Input Tables
  • 56. Dr. Ejaz Ahmed 56 Aliasing Table Names • A table alias is created by directly placing an alias after the table name in the FROM clause. • The advantage of using a table alias when performing JOIN is readily apparent when we discuss JOIN later. • For example in the following example we will refer to departments table as d or dept. SELECT d.dname FROM departments d WHERE d.dno = 1; SELECT dept.dname FROM departments dept WHERE dept.dno = 1;
  • 57. Dr. Ejaz Ahmed 57 Nested queries • Some SQL statements can have a SELECT embedded within them. • A subselect can be used in WHERE and HAVING clauses of an outer SELECT, where it is called a nested query or a subquery. • Subselects may also appear in INSERT, UPDATE, and DELETEs.
  • 58. Dr. Ejaz Ahmed 58 Example: Nested queries • From the Lecturer table, select lecturers whose salary is above average. • Cannot write 'WHERE salary > avg(salary)'. SELECT AVG(salary) FROM lecturers SELECT * FROM lecturers WHERE salary > ( ); Inner select Outer select  The Inner select is done before the outer select. Input Tables
  • 59. Dr. Ejaz Ahmed 59 Nested query: Example • List the names of all Lecturers who are in the ICS department SELECT lname FROM lecturers WHERE dno IN ( ); SELECT dno FROM department WHERE dname = ‘ICS’ Input Tables
  • 60. Dr. Ejaz Ahmed 60 Nested Query Rules • ORDER BY clause may not be used in a subquery (although it may be used in outermost SELECT). • Subquery SELECT list must consist of a single column name or expression, except for subqueries that use EXISTS. • By default, column names refer to table name in FROM clause of subquery. Can refer to a table in FROM using an alias. • When subquery is an operand in a comparison, subquery must appear on right-hand side. • A subquery may not be used as an operand in an expression.
  • 61. Dr. Ejaz Ahmed 61 Nested Query: Example • Find lecturers whose salary higher than the salary of at least 1 COE lecturer. SELECT min(salary) FROM lecturers WHERE dno = ( ) SELECT * FROM Lecturers WHERE salary > ( ); SELECT DNO FROM department WHERE dname = ‘COE’ Input Tables
  • 62. Dr. Ejaz Ahmed 62 Nested Query: Example • Find lecturers whose salary higher than the salary of every COE lecturer. SELECT max(salary) FROM lecturers WHERE dno = ( ) SELECT * FROM Lecturers WHERE salary > ( ); SELECT DNO FROM department WHERE dname = ‘COE’ Input Tables
  • 63. Dr. Ejaz Ahmed 63 Join • Can use subqueries provided result columns come from same table. • If result columns come from more than one table must use a join. • To perform join, include more than one table in FROM clause. • Use comma as separator and typically include WHERE clause to specify join column(s). • Also possible to use an alias for a table named in FROM clause. • Alias is separated from table name with a space. • Alias can be used to qualify column names when there is ambiguity.
  • 64. Dr. Ejaz Ahmed 64 Example: Join (Inner Join) • The default type of join is inner join, where arow is included in the result only if matching row exists in the other relation. • List each lecturer’s name and his department name. SELECT a.lname, b.dname FROM lecturers a, departments b WHERE a.dno = b.dno; Lname dname Ahmed Amin Hani Ageel Yousef Khalid ICS COE ICS ICS COE COE Input Tables PK-FK never makes default join, must specify Join in SQL
  • 65. Dr. Ejaz Ahmed 65 Example: Join (Inner Join) … • To obtain correct rows, include only those rows from both tables that have identical values in the dno columns: a.dno = b.dno. • These two columns are the matching columns for two tables. • This type of join is also called inner join and they equivalent to equi-join in relational algebra.
  • 66. Dr. Ejaz Ahmed 66 Computing a Join • Procedure for generating results of a SELECT with a join are: 1. Form Cartesian product of the tables named in FROM clause. 2. If there is a WHERE clause, apply the search condition to each row of the product table, retaining those rows that satisfy the condition. 3. For each remaining row, determine the value of each item in the SELECT list to produce a single row in the result table. 4. If SELECT DISTINCT has been specified, eliminate any duplicate rows from the result table. 5. If there is an ORDER BY clause, sort the result table as required.
  • 67. Dr. Ejaz Ahmed 67 Outer Joins • With an inner join, if one row of a table is unmatched, row is omitted from result table. • The outer join operations retain rows that do not satisfy the join condition. • There are three types of OUTER JOIN – Left Outer Join – Right Outer Join – Full Outer Join • Lets discuss inner join then we will come back to outer join. • Query execution (Performance) is much better than other joins
  • 68. Dr. Ejaz Ahmed 68 Outer Join … • Inner join of departments and lecturers tables will result in the following output. SELECT a.*, b.* FROM lecturers a, Departments b WHERE a.dno = b.dno Lid Lname dno salary 1 2 3 4 5 6 Ahmed Amin Hani Ageel Yousef Khalid 1 2 1 1 2 2 4000 3700 4200 4000 3500 4500 1 2 1 1 2 2 dno ICS COE COE ICS ICS COE dname Input Tables
  • 69. Dr. Ejaz Ahmed 69 Outer Join … • Result table has two rows where the dno are the same. • There are no rows corresponding to NW or Abdella. • To include unmatched rows in result table, use an outer join.
  • 70. Dr. Ejaz Ahmed 70 Example: Left Outer Join • If We want to Include in the output table the lecturers whose department is unknow we rewrite our previous query as follows SELECT a.*, b.* FROM lecturers a, Departments b WHERE a.dno = b.dno(+) Lid Lname dno salary 1 2 3 5 6 7 Ahmed Amin Hani Ageel Yousef Khalid 1 2 1 1 2 2 4000 3700 4200 4000 3500 4500 1 2 1 1 2 2 dno SE COE COE ICS SWE SWE dname 4 Addella 4300 Input Tables select d.dname, e.empno, e.ename from dept d, emp e where d.deptno=e.deptno(+);
  • 71. Dr. Ejaz Ahmed 71 Example: Left Outer Join (3-Tables)…
  • 72. Dr. Ejaz Ahmed 72 Example: Right Outer Join • If We want to Include in the output table the departments with no lecturers we rewrite our previous query as follows SELECT a.*, b.* FROM lecturers a, Departments b WHERE a.dno (+) = b.dno Lid Lname dno salary 1 2 3 5 6 7 Ahmed Amin Hani Ageel Yousef Khalid 4 3 1 3 2 2 4000 3700 4200 4000 3500 4500 4 3 1 3 2 2 dno SE COE COE ICS SWE SWE dname 5 NW Input Tables
  • 73. Dr. Ejaz Ahmed 73 Example: Full Outer Join • If We want to Include in the output table the departments with no lecturers and the lecturers with unknow departments we rewrite our previous query as follows SELECT a.*, b.* FROM lecturers a, Departments b WHERE a.dno (+) = b.dno UNION SELECT a.*, b.* FROM lecturers a, Departments b WHERE a.dno= b.dno (+); Lid Lname dno salary 1 2 3 5 6 7 Ahmed Amin Hani Ageel Yousef Khalid 4 3 1 3 2 2 4000 3700 4200 4000 3500 4500 4 3 1 3 2 2 dno SE COE COE ICS SWE SWE dname 5 NW 4 Abdella 4300 Input Tables
  • 74. Dr. Ejaz Ahmed 74 Characteristic of Outer Join • Left Outer Join: – Includes those rows of first (left) table unmatched with rows from second (right) table. – Columns from second table are filled with NULLs. • Right outer Join : – includes those rows of second (right) table that are unmatched with rows from first (left) table. – Columns from first table are filled with NULLs. • Full Outer Join: – Is the UNION of both left and right outer joins.
  • 75. Dr. Ejaz Ahmed 75 Examples: Left, Right and Full Outer Joins
  • 76. Dr. Ejaz Ahmed 76 Union, Intersect, and Difference • Can use normal set operations of union, intersection, and difference to combine results of two or more queries into a single result table. • Union of two tables, A and B, is table containing all rows in either A or B or both. • Intersection is table containing all rows common to both A and B. • Difference is table containing all rows in A but not in B. • Two tables must be union compatible. • If ALL specified, result can include duplicate rows
  • 77. Dr. Ejaz Ahmed 77 Example: Use of UNION • List all the ICS and COE faculty salaries. Remove duplicates SELECT salary FROM lecturers WHERE dno = 1 UNION SELECT salary FROM lecturers WHERE dno = 2;  List all the ICS and COE faculty salaries. Include duplicates SELECT salary FROM lecturers WHERE dno = 1 UNION ALL SELECT salary FROM lecturers WHERE dno = 2; Input Tables
  • 78. Dr. Ejaz Ahmed 78 Example: Use of UNION … • List all the ICS and COE faculty salaries. Remove duplicates SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘ICS’ ) UNION SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘COE’ )  List all the ICS and COE faculty salaries. Include duplicates SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘ICS’ ) UNION ALL SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘COE’ ) Input Tables
  • 79. Dr. Ejaz Ahmed 79 Example: Use of DIFFERENCE • List salaries that are taken by ICS and not COE lecturers. SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments where dname= ‘ICS’ ) MINUS SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘COE’ ) Input Tables
  • 80. Dr. Ejaz Ahmed 80 Example: Use of INTESECTION • List salaries that are taken by both COE and ICS lecturers. SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments where dname= ‘ICS’ ) INTERSECTION SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘COE’ ) Produces result tables from both queries and creates single result table consisting of those rows that are common to both result tables. Input Tables
  • 81. Dr. Ejaz Ahmed 81 Other SQL Operators • IN (covered) • BETWEEN (covered) • LIKE (covered) • ANY (SOME) • ALL • EXISTS • NOT EXISTS
  • 82. Dr. Ejaz Ahmed 82 ANY (SOME) and ALL • ANY and ALL may be used with subqueries that produce a single column of numbers. • If subquery preceded by ALL, condition will only be true if it is satisfied by all values produced by subquery. • If subquery preceded by ANY, condition will be true if it is satisfied by any values produced by subquery. • If subquery is empty, ALL returns true, ANY returns false. • ISO standard allows SOME to be used in place of ANY.
  • 83. Dr. Ejaz Ahmed 83 Example using the SOME Operator • Find lecturers whose salary higher than the salary of at least 1 COE lecturer. SELECT salary FROM lecturers WHERE dno = ( ) SELECT * FROM Lecturers WHERE salary > SOME ( ); SELECT DNO FROM department WHERE dname = ‘COE’ Input Tables
  • 84. Dr. Ejaz Ahmed 84 Example Using the ALL Operator • Find lecturers whose salary higher than the salary of every COE lecturer. SELECT salary FROM lecturers WHERE dno = ( ) SELECT * FROM Lecturers WHERE salary > ALL ( ); SELECT DNO FROM department WHERE dname = ‘COE’
  • 85. Dr. Ejaz Ahmed 85 EXISTS and NOT EXISTS • EXISTS and NOT EXISTS are for use only with subqueries specially with correlated subqueries. A correlated subquery is a subquery where some attributes of the outer select are used in the inner select. • They produce a simple true/false result. • EXISTS is true if and only if there exists at least one row in result table returned by subquery. • It is false if subquery returns an empty result table. • NOT EXISTS is the opposite of EXISTS. • Since EXISTS and NOT EXISTS check only for existence or non-existence of rows in subquery result table, subquery can contain any number of columns.
  • 86. Dr. Ejaz Ahmed 86 --- Example using the EXISTS Operator • Find all ICS lecturers. SELECT * FROM lecturers a WHERE EXISTS ( SELECT 1 FROM department b WHERE a.dno = b.dno AND b.dname = ‘ICS‘ ); Input Tables
  • 87. Dr. Ejaz Ahmed 87 Example using the NOT EXISTS Operator • Find all non ICS lecturers. SELECT * FROM lecturers a WHERE NOT EXISTS ( SELECT 1 FROM department b WHERE a.dno = b.dno AND b.dname = ‘ICS‘ );
  • 88. Dr. Ejaz Ahmed 88 More SQL Functions • SUBSTR • INSTR • LENGTH • LEFT, RIGHT • LPAD, RPAD • TRIM • DECODE • CEIL • ROWNUM TO_CHAR TO_DATE TO_NUMBER ADD_MONTHS FLOOR SYSDATE NVL TRANSLATE
  • 89. Dr. Ejaz Ahmed 89 SQL Data Definition Statements (DDL) • CREATE SCHEMA and DROP SCEHMA + • CREATE TABLE + • ALTER TABLE + • DROP TABLE +
  • 90. Dr. Ejaz Ahmed 90 CREATE SCHEMA and DROP SCHEMA CREATE SCHEMA [name| AUTHORIZATION creator_id ]; Example: CREATE USER COMPANY IDENTIFIED BY password; DROP SCHEMA name [RESTRICT | CASCADE ]; Example: DROP USER COMPANY CASCADE; • With RESTRICT (default), schema must be empty or operation fails. • With CASCADE, operation cascades to drop all objects associated with schema in the order defined above. If any of these operations fail, DROP SCHEMA fails.
  • 91. Dr. Ejaz Ahmed 91 CREATE TABLE CREATE TABLE table_name (col_name data_type [NULL | NOT NULL] [,...]); • Creates a table with one or more columns of the specified data_type. • NULL (default) indicates whether column can contain nulls. • With NOT NULL, system rejects any attempt to insert a null in the column. • Primary keys should always be specified as NOT NULL. • Foreign keys are often (but not always) candidates for NOT NULL.
  • 92. Dr. Ejaz Ahmed 92 CREATE TABLE – Example 1 CREATE TABLE Employee ( fname VARCHAR2(15) NOT NULL, minit CHAR, lname VARCHAR2(15) NOT NULL, ssn CHAR(9), bdate DATE, address VARCHAR2(50), sex CHAR, salary NUMBER(10,2) NOT NULL, Superssn CHAR(9), dno NUMBER(3) NOT NULL, CONSTRAINT employee_ssn_pk PRIMARY KEY(ssn), CONSTRAINT employee_superssn_fk FOREIGN KEY(Superssn) REFERENCES employee(ssn), CONSTRAINT employee_dno_fk FOREIGN KEY(dno) REFERENCES department(dnumber), );
  • 93. Dr. Ejaz Ahmed 93 CREATE TABLE – Example 2 CREATE TABLE department ( dname VARCHAR2(15) NOT NULL, dnumber NUMBER(3) NOT NULL, mgrssn CHAR(9), mgrStartDateDATE, CONSTRAINT department_dnumber_pk PRIMARY KEY(dnumber), CONSTRAINT department_mgrssn_fk FOREIGN KEY(mgrssn) REFERENCES employee(ssn) );
  • 94. Dr. Ejaz Ahmed 94 DROP TABLE DROP TABLE tbl_name [RESTRICT | CASCADE] e.g. DROP TABLE employee; • Removes named table and all rows within it. • With RESTRICT, if any other objects depend for their existence on continued existence of this table, SQL does not allow request. • With CASCADE, SQL drops all dependent objects (and objects dependent on these objects).
  • 95. Dr. Ejaz Ahmed 95 ALTER TABLE • The ALTER command is a schema modification command. • It is used to add or drop a column, change a column definition, add or drop table constraints. Examples: ALTER TABLE COMPANY.EMPLOYEE MODIFY(lname VARCHAR2(30)); ALTER TABLE EMP ADD Constraints pk_emp primary key (EMPNO); ALTER TABLE EMP ADD CONSTRAINTS FK_DEPTNO FOREIGN KEY (DEPTNO) REFERENCES DEPT(DEPTNO);
  • 96. Dr. Ejaz Ahmed 96 SQL Data Manipulation Statements (DML) • INSERT Statement + • UPDATE Statement + • DELETE Statement + • Note: Use following control commands for above SQL • Commit for DO or confirm • Rollback for UNDO
  • 97. Dr. Ejaz Ahmed 97 INSERT Statement • Definition of INSERT Statement + • Types of INSERT Statement + • INSERT and Integrity Constraints +
  • 98. Dr. Ejaz Ahmed 98 Definition of INSERT Statement • INSERT is used to add a single row to a table where we specify the relation name and a list of values for the row. • There are three types of INSERT Statement: – INSERT With Column list + – INSERT Without Column list + – INSERT with SELECT Statement +
  • 99. Dr. Ejaz Ahmed 99 INSERT with Column list INSERT INTO table_name (column_list) VALUES (data_value_list); • Example: INSERT INTO employee(fname, lname, ssn, salary, dno) VALUES (‘Majid', ‘Al-Ghamdi', ‘1111111', 4000, 123); • data_value_list must match column_list as follows: – Number of items in each list must be the same. – Must be direct correspondence in position of items in two lists. – Data type of each item in data_value_list must be compatible with data type of corresponding column. – If one of the table columns is omitted from the column_list It must also be omitted from the data_value_list and make sure it is nullable.
  • 100. Dr. Ejaz Ahmed 100 INSERT without Column List INSERT INTO table_name VALUES (data_value_list); • Example: INSERT INTO employee VALUES (‘Adel', NULL, ‘Al-Eid', ‘222222’, NULL, NULL, NULL, NULL, NULL, 1); • data_value_list must match the columns of the table as follows: – Number of items in the list must be equal to the number of columns of the table. – Data type of corresponding items must be compatible.
  • 101. Dr. Ejaz Ahmed 101 INSERT … SELECT • Second form of INSERT allows multiple rows to be copied from one or more tables to another: INSERT INTO table_name [ (column_list) ] SELECT ... Example: INSERT INTO Table1 (A1, A2, A3) SELECT B1, B2, B3 FROM Table2;
  • 102. Dr. Ejaz Ahmed 102 INSERT and Integrity Constraints • A DBMS that fully implement SQL2 should support and enforce all the integrity constraints that can be specified in the DDL. • A DBMS enforcing NOT NULL will reject an INSERT command in which an attribute declared to be NOT NULL does not have a value. • A DBMS not supporting referential integrity will allow insertion even if the referential integrity constraint is violated.
  • 103. Dr. Ejaz Ahmed 103 UPDATE • Definition + • Examples – Update All Rows + – Update Specific Rows + – Update Multiple Columns +
  • 104. Dr. Ejaz Ahmed 104 UPDATE Definition … • The UPDATE command is used to modify attribute values of one or more selected rows. UPDATE table_name SET column_name1 = data_value1 [, column_name2 = data_value2...] [WHERE search_condition] • table_name can be name of a base table or an updatable view. • SET clause specifies names of one or more columns that are to be updated.
  • 105. Dr. Ejaz Ahmed 105 UPDATE Definition … • WHERE clause is optional: – If omitted, named columns are updated for all rows in table. – If specified, only those rows that satisfy search_condition are updated. • New data_value(s) must be compatible with data type for corresponding column.
  • 106. Dr. Ejaz Ahmed 106 Example: UPDATE All Rows Give all employees a 3% pay increase. UPDATE staff SET salary = salary*1.03;
  • 107. Dr. Ejaz Ahmed 107 Example: UPDATE Specific Rows • Give all Employees in Department one a 5% pay increase. UPDATE employee SET salary = salary*1.05 WHERE dno = 1; • WHERE clause finds rows that contain data for dno = 1. Update is applied only to these particular rows.
  • 108. Dr. Ejaz Ahmed 108 Example: UPDATE Multiple Columns • Change Adel’s department to 2 and his Salary to 4,000. Assume Adel’s ssn = 111; UPDATE employee SET dno = 2 , salary = 4000 WHERE ssn = ‘111’;
  • 109. Dr. Ejaz Ahmed 109 DELETE • DELETE Definition + • DELETE Example +
  • 110. Dr. Ejaz Ahmed 110 DELETE Definition • A DELETE command removes rows from a table and may include a where-clause. • Rows are explicitly deleted from only one table at a time. However, the deletion may propagate to rows in other tables if referential triggered actions are specified in the referential integrity constraints of the DDL. DELETE FROM table_name [WHERE search_condition] • table_name can be name of a base table or an updatable view. • The WHERE clause is optional; if omitted, all rows are deleted from table. But if it is included only those rows that satisfy the search_condition are deleted.
  • 111. Dr. Ejaz Ahmed 111 Example: DELETE • Delete all records from employee. DELETE FROM employee; • Delete all employees in department 1. DELETE FROM employee WHERE dno = 1;