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

Structured Query Language: Abhishek Bhardwaj Asst. Prof IT

Uploaded by

Vipul Sapra
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Structured Query Language: Abhishek Bhardwaj Asst. Prof IT

Uploaded by

Vipul Sapra
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 76

SQL

Structured Query Language

Abhishek Bhardwaj Asst. Prof IT


1 Introduction to SQL
What is SQL?
– When a user wants to get some
information from a database file, he can
issue a query.
– A query is a user–request to retrieve data
or information with a certain condition.
– SQL is a query language that allows user to
specify the conditions. (instead of
algorithms)
Abhishek Bhardwaj Asst. Prof IT
Why a query language?
Given some data,
how should users
and computer programs
communicate with it?

we need an interface to the data


Abhishek Bhardwaj Asst. Prof IT
Background
• History
– SEQUEL (Structures English QUery Language) – early
70’s, IBM Research
– SQL (ANSI 1986), SQL1 or SQL86
– SQL2 or SQL92
– SQL3 or SQL99
• Core specification and optional specialized packages

• SQL consists of ~20 basic commands


– A lot of research money for each SQL command…

• Standard language for all commercial DBMS


– Each DBMS has features outside standard
Abhishek Bhardwaj Asst. Prof IT
Terminology
Theoretical foundation: relation

The relational data


model Attribute1 Attribute2 Attribute2

– relation – table column1 … columnn


– tuple – row
<row 2>
– attribute – column

<row n>
Abhishek Bhardwaj Asst. Prof IT
SQL Database Tables
A database most often contains one or more tables. Each table is
identified by a name (e.g. "Customers" or "Orders"). Tables contain
records (rows) with data.
Below is an example of a table called "Persons":
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

Abhishek Bhardwaj Asst. Prof IT


SQL Data Manipulation
Language (DML)
SQL (Structured Query Language) is a syntax for executing
queries. But the SQL language also includes a syntax to
update, insert, and delete records.
These query and update commands together form the Data
Manipulation Language (DML) part of SQL:

•SELECT - extracts data from a database table


•UPDATE - updates data in a database table
•DELETE - deletes data from a database table
•INSERT INTO - inserts new data into a database table

Abhishek Bhardwaj Asst. Prof IT


SQL Data Definition Language
(DDL)
The Data Definition Language (DDL) part of SQL permits
database tables to be created or deleted. We can also define
indexes (keys), specify links between tables, and impose
constraints between database tables.

The most important DDL statements in SQL are: 

•CREATE TABLE - creates a new database table


•ALTER TABLE - alters (changes) a database table
•DROP TABLE - deletes a database table
•CREATE INDEX - creates an index (search key)
•DROP INDEX - deletes an index

Abhishek Bhardwaj Asst. Prof IT


Domain Types(Data types) in SQL
• char(n). Fixed length character string, with user-specified length n.
• varchar2(n). Variable length character strings, with user-specified
maximum length n.
• int. Integer (a finite subset of the integers that is machine-dependent).
• smallint. Small integer (a machine-dependent subset of the integer
domain type).
• number(p,d). Fixed point number, with user-specified precision of p
digits, with d digits to the right of decimal point.
• real, double precision. Floating point and double-precision floating point
numbers, with machine-dependent precision.
• float(n). Floating point number, with user-specified precision of at least n
digits.
• Null values are allowed in all the domain types. Declaring an attribute to
be not null prohibits null values for that attribute.

Abhishek Bhardwaj Asst. Prof IT


Date/Time Types in SQL (Cont.)
• date. Dates, containing a (4 digit) year, month and date
– E.g. date ‘2001-7-27’
• time. Time of day, in hours, minutes and seconds.
– E.g. time ’09:00:30’ time ’09:00:30.75’
• timestamp: date plus time of day
– E.g. timestamp ‘2001-7-27 09:00:30.75’

Abhishek Bhardwaj Asst. Prof IT


Create Table Construct
• An SQL relation is defined using the create table command:
create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
– r is the name of the relation
– each Ai is an attribute name in the schema of relation r
– Di is the data type of values in the domain of attribute Ai
• Example:
create table branch
(branch-name char(15) not null,
branch-city char(30),
assets integer)

Abhishek Bhardwaj Asst. Prof IT


Integrity Constraints in Create Table
• not null
• primary key (A1, ..., An)
• check (P), where P is a predicate

Example: Declare branch-name as the primary key for


branch and ensure that the values of assets are non-
negative.
create table branch
(branch-namechar(15),
branch-city char(30)
assets integer,
primary key (branch-name),
check (assets >= 0))

primary key declaration on an attribute automatically


ensures not null in SQL-92 onwards, needs to be
explicitly stated in SQL-89
Abhishek Bhardwaj Asst. Prof IT
Drop and Alter Table Constructs
• The drop table command deletes all information about the
dropped relation from the database.
• The alter table command is used to add attributes to an existing
relation.
alter table r add A D
where A is the name of the attribute to be added to relation r and D
is the domain of A.
– All tuples in the relation are assigned null as the value for the
new attribute.
• The alter table command can also be used to drop attributes of a
relation
alter table r drop A
where A is the name of an attribute of relation r
– Dropping of attributes not supported by many databases

Abhishek Bhardwaj Asst. Prof IT


2 Basic structure of an SQL
query
General SELECT, ALL / DISTINCT, *,
Structure AS, FROM, WHERE

Comparison IN, BETWEEN, LIKE "% _"

Grouping GROUP BY, HAVING,


COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )

Display Order ORDER BY, ASC / DESC

Logical AND, OR, NOT


Operators

Abhishek Bhardwaj Asst. Prof IT


SQL The SELECT Statement
The SELECT statement is used to select data from a table. The
tabular result is stored in a result table (called the result-set).

Syntax
SELECT column_name(s)
FROM table_name

Abhishek Bhardwaj Asst. Prof IT


To select the columns named "LastName" and "FirstName",
use a SELECT statement like this:
SELECT LastName, FirstName FROM Persons
Persons

LastName FirstName Address City


Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

výsledok

LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari

Abhishek Bhardwaj Asst. Prof IT


Select All Columns

To select all columns from the "Persons" table, use a *


symbol instead of column names, like this:
SELECT * FROM Persons

LastName FirstName Address City


Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

Abhishek Bhardwaj Asst. Prof IT


The SELECT DISTINCT Statement
The DISTINCT keyword is used to return only distinct (different)
values.
The SELECT statement returns information from table columns.
But what if we only want to select distinct elements?
With SQL, all we need to do is to add a DISTINCT keyword to the
SELECT statement:
Syntax

SELECT DISTINCT column_name(s)


FROM table_name

Abhishek Bhardwaj Asst. Prof IT


Using the DISTINCT keyword
To select ALL values from the column named "Company" we use
a SELECT statement like this:
SELECT Company FROM Orders
Orders
Company
Sega
Company OrderNumber
W3Schools
Sega 3412
Trio
W3Schools 2312
W3Schools
Trio 4678
W3Schools 6798

Abhishek Bhardwaj Asst. Prof IT


Note that "W3Schools" is listed twice in the result-set.
To select only DIFFERENT values from the column named
"Company" we use a SELECT DISTINCT statement like this:
SELECT DISTINCT Company FROM Orders

Orders
Company
Sega
Company OrderNumber W3Schools
Sega 3412 Trio
W3Schools 2312
Trio 4678
W3Schools 6798

Abhishek Bhardwaj Asst. Prof IT


Using the WHERE Clause
The WHERE clause is used to specify a selection criterion.
The WHERE Clause
To conditionally select data from a table, a WHERE clause can
be added to the SELECT statement.
Syntax

SELECT column FROM table


WHERE column operator value

Abhishek Bhardwaj Asst. Prof IT


With the WHERE clause, the following operators can be
used:

Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern

Note: In some versions of SQL the <> operator may be written as !=

Abhishek Bhardwaj Asst. Prof IT


Using the WHERE Clause
To select only the persons living in the city "Sandnes", we add a
WHERE clause to the SELECT statement:
SELECT * FROM Persons
WHERE City='Sandnes'
LastName FirstName Address City Year
Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980
Pettersen Kari Storgt 20 Stavanger 1960

LastName FirstName Address City Year


Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980

Abhishek Bhardwaj Asst. Prof IT


Using Quotes
Note that we have used single quotes around the conditional
values in the examples.
SQL uses single quotes around text values (most database
systems will also accept double quotes). Numeric values should
not be enclosed in quotes.
For text values:
This is correct:

SELECT * FROM Persons WHERE FirstName='Tove'


This is wrong:

SELECT * FROM Persons WHERE FirstName=Tove


Abhishek Bhardwaj Asst. Prof IT
The LIKE Condition
The LIKE condition is used to specify a search for a pattern in
a column.
Syntax
SELECT column FROM table
WHERE column LIKE pattern

A "%" sign can be used to define wildcards (missing letters


in the pattern) both before and after the pattern.

Abhishek Bhardwaj Asst. Prof IT


Using LIKE
The following SQL statement will return persons with first names
that start with an 'O':
SELECT * FROM Persons
WHERE FirstName LIKE 'O%'

The following SQL statement will return persons with first names
that end with an 'a':
SELECT * FROM Persons
WHERE FirstName LIKE '%a'
Abhishek Bhardwaj Asst. Prof IT
Using LIKE 2
The following SQL statement will return persons with first names
that contain the pattern 'la':
SELECT * FROM Persons
WHERE FirstName LIKE '%la%'

Abhishek Bhardwaj Asst. Prof IT


II Comparison

expr IN ( value1, value2, value3)


expr BETWEEN value1 AND value2
expr LIKE "%_"

id name dob sex class mtest hcode dcode remission


9801 Peter 06/04/86 M 1A 70 R SSP .F.
9802 Mary 01/10/86 F 1A 92 Y HHM .F.
9803 Johnny 03/16/86 M 1A 91 G SSP .T.
9804 Wendy 07/09/86 F 1B 84 B YMT .F.
9805 Tobe 10/17/86 M 1B 88 R YMT .F.
: : : : : : : : :

Abhishek Bhardwaj Asst. Prof IT


SQL The INSERT INTO
Statement

Abhishek Bhardwaj Asst. Prof IT


The INSERT INTO Statement
The INSERT INTO statement is used to insert new rows into
a table.
Syntax
INSERT INTO table_name
VALUES (value1, value2,....)

You can also specify the columns for which you want to insert
data:
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)
Abhishek Bhardwaj Asst. Prof IT
Insert a New Row
LastName FirstName Address City

Pettersen Kari Storgt 20 Stavanger

And this SQL statement:


INSERT INTO Persons
VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes')

LastName FirstName Address City

Pettersen Kari Storgt 20 Stavanger

Hetland Camilla Hagabakka 24 Sandnes

Abhishek Bhardwaj Asst. Prof IT


Insert Data in Specified Columns
LastName FirstName Address City

Pettersen Kari Storgt 20 Stavanger

Hetland Camilla Hagabakka 24 Sandnes

And This SQL statement:


INSERT INTO Persons (LastName, Address)
VALUES ('Rasmussen', 'Storgt 67')

LastName FirstName Address City


Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes
Rasmussen Storgt 67

Abhishek Bhardwaj Asst. Prof IT


SQL The UPDATE Statement

Abhishek Bhardwaj Asst. Prof IT


The Update Statement
The UPDATE statement is used to modify the data in a table.
Syntax

UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value

Abhishek Bhardwaj Asst. Prof IT


Update one Column in a Row
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67

We want to add a first name to the person with a last name of


"Rasmussen":
UPDATE Person SET FirstName = 'Nina'
WHERE LastName = 'Rasmussen'
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Storgt 67

Abhishek Bhardwaj Asst. Prof IT


Update several Columns in a
Row
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67

We want to change the address and add the name of the city:
UPDATE Person
SET Address = 'Stien 12', City = 'Stavanger'
WHERE LastName = 'Rasmussen'

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Bhardwaj Asst.Stien
Abhishek Prof 12
IT Stavanger
SQL The Delete Statement

Abhishek Bhardwaj Asst. Prof IT


The Delete Statement
The DELETE statement is used to delete rows in a table.
Syntax

DELETE FROM table_name


WHERE column_name = some_value

Abhishek Bhardwaj Asst. Prof IT


Delete a Row
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger

"Nina Rasmussen" is going to be deleted:


DELETE FROM Person WHERE LastName = 'Rasmussen'

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger

Abhishek Bhardwaj Asst. Prof IT


Delete All Rows
It is possible to delete all rows in a table without deleting the
table. This means that the table structure, attributes, and indexes
will be intact:
DELETE FROM table_name
Or
DELETE * FROM table_name

Abhishek Bhardwaj Asst. Prof IT


III Grouping
SELECT ...... FROM ...... WHERE condition ;
GROUP BY groupexpr [HAVING requirement]

Group functions:
COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )

– groupexpr specifies the related rows to be grouped


as one entry. Usually it is a column.
– WHERE condition specifies the condition of
individual rows before the rows are group.
HAVING requirement specifies the condition
involving the whole group.
Abhishek Bhardwaj Asst. Prof IT
III Grouping
eg. 11 List the number of students of each class.

Abhishek Bhardwaj Asst. Prof IT


Group By Class
class
1A

1A 1A
1A
COUNT( )

1B
1B
1B
1B 1B
COUNT( )
1B
1B
1C

1C 1C
1C
COUNT( )

Student
Abhishek Bhardwaj Asst. Prof IT
III Grouping
eg. 11 List the number of students of each class.
SELECT class, COUNT(*) FROM student
GROUP BY class
class cnt
Result 1A 10
1B 9
1C 9
2A 8
2B 8
2C 6
Abhishek Bhardwaj Asst. Prof IT
III Grouping
eg. 12 List the average Math test score of each class.

Abhishek Bhardwaj Asst. Prof IT


Group By Class
class
1A

1A 1A
1A
AVG( )
1B
1B

1B
1B
AVG( )
1B
1B
1B
1C

1C 1C AVG( )
1C
Student
Abhishek Bhardwaj Asst. Prof IT
III Grouping
eg. 12 List the average Math test score of each class.

SELECT class, AVG(mtest) FROM student


GROUP BY class
class avg_mtest
Result 1A 85.90
1B 70.33
1C 37.89
2A 89.38
2B 53.13
2C 32.67
Abhishek Bhardwaj Asst. Prof IT
III Grouping
eg. 13 List the number of girls of each district.

SELECT dcode, COUNT(*) FROM student


WHERE sex="F" GROUP BY dcode

Result dcode cnt


HHM 6
KWC 1
MKK 1
SSP 5
TST 4
YMT 8 IT
Abhishek Bhardwaj Asst. Prof
III Grouping
eg. 14 List the max. and min. test score of Form 1
students of each district.
SELECT MAX(mtest), MIN(mtest), dcode ;
FROM student ;
WHERE class LIKE "1_" GROUP BY dcode
max_mtest min_mtest dcode
Result 92 36 HHM
91 19 MKK
91 31 SSP
92 36 TST
75 75 TSW
Abhishek Bhardwaj Asst. Prof IT
88 38 YMT
III Grouping
eg. 15 List the average Math test score of the boys in
each class. The list should not contain
class with less than 3 boys.
SELECT AVG(mtest), class FROM student ;
WHERE sex="M" GROUP BY class ;
HAVING COUNT(*) >= 3
Result avg_mtest class
86.00 1A
77.75 1B
35.60 1C
86.50 2A
56.50
Abhishek Bhardwaj Asst.2B
Prof IT
IV Display Order
SELECT ...... FROM ...... WHERE ......
GROUP BY .....
ORDER BY colname ASC / DESC

Abhishek Bhardwaj Asst. Prof IT


IV Display Order
eg. 16 List the boys of class 1A, order by their names.

SELECT name, id FROM student


WHERE sex="M" AND class="1A" ORDER BY
name
name id Result name id
Peter 9801 Aaron 9812
Johnny 9803 ORDER BY Bobby 9811
Luke 9810 Johnny 9803
dcode
Bobby 9811 Luke 9810
Aaron 9812 Peter 9801
Ron 9813 Ron 9813

Abhishek Bhardwaj Asst. Prof IT


IV Display Order
eg. 17 List the 2A students by their residential
district.
SELECT name, id, class, dcode FROM student
WHERE class="2A" ORDER BY dcode
name id class dcode
Result Jimmy 9712 2A HHM
Tim 9713 2A HHM
Samual 9714 2A SHT
Rosa 9703 2A SSP
Helen 9702 2A TST
Joseph 9715 2A TSW
Paula 9701 2A YMT
Susan 9704 2A YMT
Abhishek Bhardwaj Asst. Prof IT
IV Display Order
eg. 18 List the number of students of each district
(in desc. order).
SELECT COUNT(*) AS cnt, dcode FROM
student
GROUP BYcnt
dcode docode
ORDER BY cnt DESC
Result 11 YMT
10 HHM
10 SSP
9 MKK
5 TST
2 TSW
1 KWC
1 MMK
1 Bhardwaj
Abhishek SHTAsst. Prof IT
IV Display Order
eg. 19 List the boys of each house order by the
classes. (2-level ordering)

SELECT name, class, hcode FROM student


WHERE sex="M" ORDER BY hcode, class

Abhishek Bhardwaj Asst. Prof IT


IV Display Order
Result
name hcode class
Bobby B 1A
Blue
House Teddy B 1B Order
Joseph B 2A by
Zion B 2B class
Order
Leslie B 2C
by Johnny G 1A
hcode Luke G 1A
Kevin G 1C
Green
House George G 1C
: : :
:
: Abhishek Bhardwaj Asst. Prof IT
V Output

INTO TABLE tablename the output table is saved as a


database file in the disk.

INTO CURSOR temp the output is stored in the


working memory temporarily.

TO FILE filename [ADDITIVE] output to a text file.


(additive = append)

TO PRINTER send to printer.

TO SCREEN display on screen.

Abhishek Bhardwaj Asst. Prof IT


V
eg. 20
Output
List the students in desc. order of their names
and save the result as a database file name.dbf.
SELECT * FROM student ;
ORDER BY name DESC INTO TABLE
name.dbf id name dob sex class mtest hcode dcode remission
9707 Zion 07/29/85 M 2B 51 B MKK .F.
Result 9709 Yvonne 08/24/85 F 2C 10 R TST .F.
9804 Wendy 07/09/86 F 1B 84 B YMT .F.
9819 Vincent 03/15/85 M 1C 29 Y MKK .F.
9805 Tobe 10/17/86 M 1B 88 R YMT .F.
9713 Tim 06/19/85 M 2A 91 R HHM .T.
9816 Teddy 01/30/86 M 1B 64 B SSP .F.
: : : : : : : : :
Abhishek Bhardwaj Asst. Prof IT
V
eg. 21
Output
Print the Red House members by their classes,
sex and name.
SELECT class, name, sex FROM student ;
WHERE hcode="R" ;
ORDER BY class, sex DESC, name TO
PRINTER class name sex
Result 1A Aaron M
1A Peter M
1A Ron M
1B Tobe M
1B Janet F
1B Kitty F
1B Mimi F
:Abhishek: Bhardwaj Asst.:Prof IT
4 Multiple Tables:
• SQL provides a convenient operation to
retrieve information from multiple tables.

• This operation is called join.

• The join operation will combine the tables into


one large table with all possible combinations
(Math: Cartesian Product), and then it will
filter the rows of this combined table to yield
useful information.

Abhishek Bhardwaj Asst. Prof IT


4 Multiple Tables:

field1 field2
A 1
field1 field2
A 2
A 1
A 3
B 2
B 1
3
B 2
B 3

Abhishek Bhardwaj Asst. Prof IT


4 The Situation:
Music Lesson
Each student should learn a musical instrument.
Two database files: student.dbf & music.dbf
The common field: student id

field type width contents


id numeric 4 student id number
type character 10 type of the music instrument

SELECT A
USE student
SELECT B
USE music
Abhishek Bhardwaj Asst. Prof IT
4 Natural Join
A Natural Join is a join operation that joins two
tables by their common column. This operation
is similar to the setting relation of two tables.

SELECT a.comcol, a.col1, b.col2, expr1, expr2 ;


FROM table1 a, table2 b ;
WHERE a.comcol = b.comcol

Abhishek Bhardwaj Asst. Prof IT


4
eg. 25
Natural Join
Make a list of students and the instruments
they learn. (Natural Join)
id name class id type

Same id 9801
9801

Join
Student Music

id name class type

9801
Abhishek Bhardwaj Asst. Prof IT
Product
4
eg. 25
Natural Join
Make a list of students and the instruments
they learn. (Natural Join)
SELECT s.class, s.name, s.id, m.type ;
FROM student s, music m ;
WHERE s.id=m.id ORDER BY class, name
class name id type
Result 1A Aaron 9812 Piano
1A Bobby 9811 Flute
1A Gigi 9824 Recorder
1A Jill 9820 Piano
1A Johnny 9803 Violin
1A Luke 9810 Piano
1A Mary 9802 Flute
: : : :
Abhishek Bhardwaj Asst. Prof IT
4 Outer Join
An Outer Join is a join operation that includes
rows that have a match, plus rows that do not
have a match in the other table.

Abhishek Bhardwaj Asst. Prof IT


4 Outer Join
eg. 27 List the students who have not yet chosen an
instrument. (No match)

id name class id type

9801
No match

Student Music

Abhishek Bhardwaj Asst. Prof IT


4 Outer Join
eg. 27 List the students who have not yet chosen an
instrument. (No match)
SELECT class, name, id FROM student ;
WHERE id NOT IN ( SELECT id FROM
music ) ;
ORDER BY class, name
class name id
Result 1A Mandy 9821
1B Kenny 9814
1B Tobe 9805
1C Edmond 9818
1C George 9817
: : :
Abhishek Bhardwaj Asst. Prof IT
4 Outer Join
eg. 28 Make a checking list of students and the
instruments they learn. The list should also
contain the students without an instrument.
(Outer Join)

Abhishek Bhardwaj Asst. Prof IT


4 Outer Join
eg. 28

Natural Join

Outer Join

No Match
Abhishek Bhardwaj Asst. Prof IT
4
class name id type
Outer Join
class name id type
1A Aaron 9812 Piano
1A Bobby 9811 Flute 1A Aaron 9812 Piano
1A Gigi 9824 Recorder 1A Bobby 9811 Flute
1A Jill 9820 Piano 1A Gigi 9824 Recorder
1A Johnny 9803 Violin 1A Jill 9820 Piano
1A Luke 9810 Piano 1A Johnny 9803 Violin
1A Mary 9802 Flute 1A Luke 9810 Piano
: : : : 1A Mandy 9821
Natural Join 1A Mary 9802 Flute
1A Peter 9801 Piano
class name id
1A Mandy 9821
1A Ron 9813 Guitar empty
1B Eddy 9815 Piano
1B Kenny 9814
1B Tobe 9805 1B Janet 9822 Guitar
1C Edmond 9818 1B Kenny 9814
1C George 9817 1B Kitty 9806 Recorder
: : : : : : :
No Match
Abhishek Bhardwaj Asst. Prof IT Outer Join
Joined Relations
 Join operations take two relations and return as a result another
relation.
 These additional operations are typically used as subquery
expressions in the from clause
 Join condition – defines which tuples in the two relations match,
and what attributes are present in the result of the join.
 Join type – defines how tuples in each relation that do not match
any tuple in the other relation (based on the join condition) are
treated.

Join Types Join Conditions


inner join natural
left outer join on <predicate>
right outer join using (A1, A2, ..., An)
full outer join

Database System Concepts 4.72 ©Silberschatz, Korth and Sudarshan


Joined Relations – Datasets for Examples
 Relation loan

loan-number branch-name amount

L-170 Downtown 3000


L-230 Redwood 4000
L-260 Perryridge 1700
 Relation borrower

customer-name loan-number

Jones L-170
Smith L-230
Hayes L-155
 Note: borrower information missing for L-260 and loan
information missing for L-155

Database System Concepts 4.73 ©Silberschatz, Korth and Sudarshan


Joined Relations – Examples
 loan inner join borrower on
loan.loan-number = borrower.loan-number
loan-number branch-name amount customer-name loan-number

L-170 Downtown 3000 Jones L-170


L-230 Redwood 4000 Smith L-230

 loan left outer join borrower on


loan.loan-number = borrower.loan-number

loan-number branch-name amount customer-name loan-number

L-170 Downtown 3000 Jones L-170


L-230 Redwood 4000 Smith L-230
L-260 Perryridge 1700 null null

Database System Concepts 4.74 ©Silberschatz, Korth and Sudarshan


Joined Relations – Examples

 loan natural inner join borrower

loan-number branch-name amount customer-name

L-170 Downtown 3000 Jones


L-230 Redwood 4000 Smith

 loan natural right outer join borrower

loan-number branch-name amount customer-name

L-170 Downtown 3000 Jones


L-230 Redwood 4000 Smith
L-155 null null Hayes

Database System Concepts 4.75 ©Silberschatz, Korth and Sudarshan


Joined Relations – Examples
 loan full outer join borrower using (loan-number)

loan-number branch-name amount customer-name

L-170 Downtown 3000 Jones


L-230 Redwood 4000 Smith
L-260 Perryridge 1700 null
L-155 null null Hayes

 Find all customers who have either an account or a loan (but


not both) at the bank.

select customer-name
from (depositor natural full outer join borrower)
where account-number is null or loan-number is null

Database System Concepts 4.76 ©Silberschatz, Korth and Sudarshan

You might also like