Professional Documents
Culture Documents
3 Select Joins
3 Select Joins
JOINS
Database Management System
SQL SELECT Overview
SELECT
[DISTINCT | ALL] <column-list>
FROM <table-names>
[WHERE <condition>]
[ORDER BY <column-list>]
[GROUP BY <column-list>]
[HAVING <condition>]
• ([]- optional, | - or)
Example Tables
Student Grade
ID First Last ID Code Mark
S103 John Smith S103 DBS 72
S104 Mary Jones S103 IAI 58
S105 Jane Brown S104 PR1 68
S106 Mark Jones S104 IAI 65
S107 John Brown S106 PR2 43
S107 PR1 76
Course
S107 PR2 60
Code Title S107 IAI 35
DBS Database Systems
PR1 Programming 1
PR2 Programming 2
IAI Intro to AI
DISTINCT and ALL
• Sometimes you end up with SELECT ALL Last Last
duplicate entries Smith
FROM Student
• Using DISTINCT removes Jones
Brown
duplicates Jones
• Using ALL retains them - Brown
this is the default
SELECT DISTINCT Last
Last
FROM Student
Smith
Jones
Brown
WHERE Clauses
• Usually you don’t want all
• Example conditions:
the rows
• Mark < 40
• A WHERE clause restricts the
rows that are returned • First = ‘John’
• It takes the form of a • First <> ‘John’
condition - only those rows • First = Last
that satisfy the condition are • (First = ‘John’) AND
returned (Last = ‘Smith’)
• (Mark < 40) OR (Mark
> 70)
WHERE Examples
SELECT * FROM Grade SELECT DISTINCT ID
WHERE Mark >= 60 FROM Grade
WHERE Mark >= 60
ID Code Mark
S103 DBS 72 ID
S104 PR1 68 S103
S104 IAI 65 S104
S107 PR1 76 S107
S107 PR2 60
WHERE Example
• Given the table • Write an SQL query to find a list
of the ID numbers and marks in
IAI of students who have passed
Grade (scored 40 or higher) IAI
ID Code Mark
S103 DBS 72
S103 IAI 58
S104 PR1 68
S104 IAI 65 ID Mark
S106 PR2 43 S103 58
S107 PR1 76 S104 65
S107 PR2 60
S107 IAI 35
One Solution
Student.ID Grade.ID
SELECT from Multiple Tables
SELECT ... FROM Student, Grade
WHERE (Student.ID = Grade.ID) AND (Mark >= 40)
Example:
SELECT *
FROM Student FULL OUTER JOIN Enrolment
ON Student.ID = Enrolment.ID
Missing Information
JOINs vs WHERE Clauses
• JOINs (so far) are not • Yes, because
needed • They often lead to concise
• You can have the same queries
effect by selecting from • NATURAL JOINs are very
multiple tables with an common
appropriate WHERE clause
• No, because
• So should you use JOINs or
not? • Support for JOINs varies a
fair bit among SQL dialects