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

SQL Select: Database Systems Lecture 7

The SQL SELECT command is used to query data from one or more database tables. It allows the user to specify which columns to retrieve, from which tables, and apply filters to only return rows that meet certain conditions. Joins allow data from multiple tables to be combined based on matching column values between the tables. The SELECT statement forms the core of most queries against a relational database.

Uploaded by

SowlSnatcha
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

SQL Select: Database Systems Lecture 7

The SQL SELECT command is used to query data from one or more database tables. It allows the user to specify which columns to retrieve, from which tables, and apply filters to only return rows that meet certain conditions. Joins allow data from multiple tables to be combined based on matching column values between the tables. The SELECT statement forms the core of most queries against a relational database.

Uploaded by

SowlSnatcha
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

SQL SELECT

Database Systems Lecture 7


Last Lecture

• Starting SQL
• DROP TABLE
• ALTER TABLE
• INSERT, UPDATE, and DELETE
• Sequences

• For more information


• Connolly and Begg chapters 5 and 6
Today’s hour of fun
• The data dictionary

• SQL SELECT
• WHERE clauses
• SELECT from multiple tables
• JOINs
• Aliases

• For more information


• Connolly and Begg Chapter 5
SQL
• SQL is based on relational algebra.
• An algebra is a system of operations where
each operation creates an item of the same
type.
• This means that every single SQL DML
command takes relations as inputs and gives
relations as outputs.
• These outputs can then be used as inputs in
another operation.
Base Relations
• Base Relations:
Tables as stored on disk in the database.

• Virtual Relations:
Tables generated in the ether, derived by an SQL
operation on base relations and other virtual
relations.

• Views:
Virtual relations whose definition is stored by the
DBMS.
Different Sections of SQL
• The Data Definition Language (DDL):

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
Different Sections of SQL

• Data Manipulation Language (DML):

UPDATE - updates data in a database table


DELETE FROM- deletes data from a database table
INSERT INTO - inserts new data into a database table

SELECT - extracts data from a database table


Different Sections of SQL

• Data Control Language (DCL).

Some examples:
DESCRIBE – list the structure of a table

GRANT - gives user's access privileges to database


REVOKE - withdraw access given with the GRANT command

COMMIT – submit a batch of db alterations as a permanant change


ROLLBACK – rewind a database to a previous state
The Data Dictionary
• Some
The data
DBMSs
dictionary
let youorquery
catalogue
the catalogue
stores
• In Oracle you
Information about
can access
databasethetables
metadata in several
• ways
Information about the columns of tables
• There are ‘system -tables’
Other information users,with metadata
locks, indexes,inand
them
more
• You
This can also DESCRIBE tables
is ‘metadata’
Data Dictionaries
• To find the details of a table use
DESCRIBE <table name>

• Example:
SQL> DESCRIBE Student;
Name Null? Type
------------ -------- ----------
STUID NOT NULL NUMBER(38)
STUNAME NOT NULL VARCHAR2(50)
STUADDRESS VARCHAR2(50)
STUYEAR NUMBER(38)
Oracle Data Dictionary
• To find out what tables and sequences you
have defined use:

SELECT table_name FROM user_tables

• The user_tables table is maintained by Oracle

• It has lots of columns, so don’t use


SELECT * FROM user_tables
SELECT
•• SQL’s
The SQL SELECT is different
command youfrom
willthe relational
use algebra’s
most often
Select:
• Queries a set of tables and returns results as a table
•• Lots of options, we will look at many of them
SELECT in SQL has all the functionality of its equivalent in
Usually more
• relational than one way to do any given query
algebra

• But it is a bit different because SQL differs from the


relational model, adding extra qualifiers…
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
ID FirstLast
Grade
S103 John Smith
S104 Mary Jones ID Code Mark
S105 Jane Brown S103 DBS 72
S106 Mark Jones S103 IAI 58
S107 John Brown S104 PR168
S104 IAI 65
Course S106 PR243
Code Title S107 PR176
S107 PR260
DBS Database Systems S107 IAI 35
PR1Programming 1
PR2Programming 2
IAI Intro to AI
Sample SELECTs
SELECT ID FROM Student

ID
S103
S104
S105
S106
S107
Sample SELECTs
SELECT * FROM Student

ID FirstLast
S103 John Smith
S104 Mary Jones
S105 Jane Brown
S106 Mark Jones
S107 John Brown
DISTINCT and ALL
• Sometimes you end up SELECT Last
with duplicate
ALL Lastentries
FROM Student Smith
Jones
• Using DISTINCT removes duplicates Brown
Jones
Brown
• Using ALL retains them - this is the default
SELECT DISTINCT Last
FROM Student Last
Smith
Jones
Brown
WHERE Clauses
• Usually you don’t want all
• Example
the rowsconditions:
• Mark < 40
• First
• A WHERE clause restricts the rows that =are
‘John’
returned
• First <> ‘John’
• First = Last
• It takes the form of a condition - only those rows
• (First = ‘John’)
that satisfy the condition are returned
AND
(Last = ‘Smith’)
• (Mark < 40) OR
(Mark > 70)
WHERE Examples
SELECT DISTINCT
* FROM Grade
ID
WHERE
FROM Mark
Grade>= 60
WHERE Mark >= 60

ID Code Mark
S103 DBS 72 ID
S104 PR168 S103
S104 IAI 65 S104
S107 PR176 S107
S107 PR260
WHERE Example
Givenanthe
•• Write SQLtable
query to find a list of the ID numbers and
marks in IAI of students who have passed (scored 40 or
higher)
Grade IAI
ID Code Mark
S103 DBS 72
S103 IAI 58
S104 PR168
S104 IAI 65
S106 PR243 ID Mark
S107 PR176
S103 58
S107 PR260
S104 65
S107 IAI 35
One Solution
We only want the ID and Mark, not the Code
Single quotes around the string

SELECT ID, Mark FROM Grade


WHERE (Code = ‘IAI’) AND
(Mark >= 40)

We’re only interested in IAI

We’re looking for entries with pass marks


SELECT from Multiple Tables

• Often you need


If the tables to columns
have combine with
information from
the same
two
name orambiguity
more tables
results

•• You can get the effect of a product by using


You resolve this by referencing columns with
the table name
SELECT * FROM Table1, Table2...

TableName.Column
SELECT from Multiple Tables
Student
SELECT
ID FirstLast
First, Last, Mark
S103 John Smith
FROM Student, Grade S104 Mary Jones
WHERE S105 Jane Grade
Brown
S106 Mark ID Jones
Code Mark
(Student.ID = S107 John Brown
S103 DBS 72
Grade.ID) AND S103 IAI 58
(Mark >= 40) S104 PR168
S104 IAI 65
S106 PR243
S107 PR176
S107 PR260
S107 IAI 35
SELECT from Multiple Tables
SELECT ... FROM Student, Grade WHERE...

ID FirstLast ID Code Mark


S103 John Smith S103 DBS 72
Are matched S103 John Smith S103 IAI 58 All of the
with the first S103 John Smith S104 PR168 entries from
entry from S103 John Smith S104 IAI 65 the Grade
the Student S103 John Smith S106 PR243 table
table... S103 John Smith S107 PR176
S103 John Smith S107 PR260
S103 John Smith S107 IAI 35
And then S104 Mary Jones S103 DBS 72
with the S104 Mary Jones S103 IAI 58
second… S104 Mary Jones S104 PR168
S104 Mary Jones S104 IAI 65
and so on S104 Mary Jones S106 PR243
SELECT from Multiple Tables
SELECT ... FROM Student, Grade
WHERE (Student.ID = Grade.ID) AND ...

ID FirstLast ID Code Mark


S103 John Smith S103 DBS 72
S103 John Smith S103 IAI 58
S104 Mary Jones S104 PR168
S104 Mary Jones S104 IAI 65
S106 Mark Jones S106 PR243
S107 John Brown S107 PR176
S107 John Brown S107 PR260
S107 John Brown S107 IAI 35

Student.ID Grade.ID
SELECT from Multiple Tables
SELECT ... FROM Student, Grade
WHERE (Student.ID = Grade.ID) AND (Mark >= 40)

ID FirstLast ID Code Mark


S103 John Smith S103 DBS 72
S103 John Smith S103 IAI 58
S104 Mary Jones S104 PR168
S104 Mary Jones S104 IAI 65
S106 Mark Jones S106 PR243
S107 John Brown S107 PR176
S107 John Brown S107 PR260
SELECT from Multiple Tables
SELECT First, Last, Mark FROM Student, Grade
WHERE (Student.ID = Grade.ID) AND (Mark >= 40)

FirstLast Mark
John Smith 72
John Smith 58
Mary Jones 68
Mary Jones 65
Mark Jones 43
John Brown 76
John Brown 60
SELECT from Multiple Tables

When* selecting
•SELECT FROM from multiple tables you
almost always
Student, Grade, use a WHERE clause to find
Course
entries with common values
WHERE
Student.ID = Grade.ID
AND
• You have joined tables by listing them with
Course.Code =
commas.
Grade.Code
SELECT from Multiple Tables
Student Grade Course

ID FirstLast ID Code Mark Code Title


S103 John Smith S103 DBS 72 DBS Database Systems
S103 John Smith S103 IAI 58 IAI Intro to AI
S104 Mary Jones S104 PR168 PR1Programming 1
S104 Mary Jones S104 IAI 65 IAI Intro to AI
S106 Mark Jones S106 PR243 PR2Programming 2
S107 John Brown S107 PR176 PR1Programming 1
S107 John Brown S107 PR260 PR2Programming 2
S107 John Brown S107 IAI 35 IAI Intro to AI

Student.ID = Grade.ID Course.Code = Grade.Code


JOINs
• JOINs can be used to combine A tables
CROSS JOIN B
• returns all pairs of
• There are many types of JOIN rows from A and B
• CROSS JOIN
• INNER JOIN
A NATURAL JOIN B
• NATURAL JOIN • returns pairs of rows
• OUTER JOIN with common values
A INNER JOIN B
• OUTER JOINs are linked with NULLs - more later
• returns pairs of rows
satisfying a condition
CROSS JOIN
Student SELECT * FROM
ID Name Student CROSS JOIN
123 John Enrolment
124 Mary
125 Mark ID Name ID Code
126 Jane 123 John123 DBS
124 Mary123 DBS
Enrolment 125 Mark123 DBS
ID Code 126 Jane123 DBS
123 John124 PRG
123 DBS 124 Mary124 PRG
124 PRG 125 Mark124 PRG
124 DBS 126 Jane124 PRG
126 PRG 123 John124 DBS
124 Mary124 DBS
NATURAL JOIN
Student SELECT * FROM
ID Name Student NATURAL JOIN
123 John Enrolment
124 Mary
125 Mark
126 Jane ID Name ID Code

Enrolment 123 John 123 DBS


124 Mary 124 PRG
ID Code 124 Mary 124 DBS
123 DBS 126 Jane 126 PRG
124 PRG
124 DBS
126 PRG
Equivalencies…
SELECT * FROM SELECT * FROM
A CROSS JOIN B A NATURAL JOIN B
• is the same as •is the same as
SELECT * FROM A, B SELECT * FROM
A, B
WHERE A.col1 = B.col1
AND A.col2 = B.col2
AND...
INNER JOIN
Can also
• INNER use specify
JOINs
a condition
SELECT * FROM which the
pairs of rows
A INNER JOINsatisfy
B
USING
SELECT * FROM
(col1, col2,…)
A INNER JOIN B
ON <condition>
• Chooses rows where the given columns are
equal
INNER JOIN
Student SELECT * FROM
ID Name Student INNER JOIN
123 John Enrolment USING (ID)
124 Mary
125 Mark
126 Jane
ID Name ID Code
Enrolment
123 John 123 DBS
ID Code
124 Mary 124 PRG
123 DBS 124 Mary 124 DBS
124 PRG 126 Jane 126 PRG
124 DBS
126 PRG
INNER JOIN
Buyer * FROM
SELECT
BuyerBudget
Name INNER JOIN Property ON
Price100,000
Smith <= Budget
Jones 150,000
Green 80,000

Property Name Budget Address Price

Address Price Smith 100,000 15 High St 85,000


Jones 150,000 15 High St 85,000
15 High St 85,000 Jones 150,000 12 Queen St 125,000
12 Queen St 125,000
87 Oak Row 175,000
INNER JOIN
SELECT * FROM SELECT * FROM
A INNER JOIN B A INNER JOIN B
ON <condition> USING(col1, col2,...)
• is the same as •is the same as

SELECT * FROM A, B SELECT * FROM A, B


WHERE <condition> WHERE A.col1 = B.col1
AND A.col2 = B.col2
AND ...
JOINs vs WHERE Clauses
• Yes,
JOINsbecause
(so far) are not needed
• Theycan
You leadhave
to better,
the same
conciser
effectqueries
by selecting from
• multiple
NATURALtables
JOINswith
are an appropriate
very common WHERE clause
• So should you use JOINs or not?

• No, because
• Support for JOINs varies a fair bit among SQL
dialects – it can be inconsistent.
Writing Queries
• Most
WhenDBMSs
writinghave
queries
query optimisers
• These are
There takeoften
a users
manyquery
waysandto figure
write the
out query
how to
• efficiently
You shouldexecute it
worry about being correct, clear, and
• concise
A simpleinquery
that order
is easier to optimise
• Don’t look
We’ll worryat about
some being
ways to
clever
improve
or efficient
efficiency later
Multiple Joins Example
Work
Act Direct
Actor Director
Name Sex Name Age
Al Francis
Al M Uma Quentin Francis 67
Uma F Jon Quentin Quentin 43
Jon M Jon Steven Steven 60
Samuel M Samuel Quentin Woody 71
Robert M Robert Francis
Harvey M Harvey Quentin
Scarlet F Harvey Francis
Multiple Join Query
• What is the sex of the actors who have
worked with directors under the age of 65?
Work
Act Direct
Actor Director
Name Sex Name Age
Al Francis
Al M Uma Quentin Francis 67
Uma F Jon Quentin Quentin 43
Jon M Jon Steven Steven 60
Samuel M Samuel Quentin Woody 71
Robert M Robert Francis
Harvey M Harvey Quentin
Scarlet F Harvey Francis
Solution
• What is the sex of the actors who have
worked with directors under the age of 65?

SELECT Act.Name, Act.Sex FROM Direct


INNER JOIN Work
ON (Direct.name = Work.director)
INNER JOIN Act
ON (Work.actor = Act.name)
WHERE Direct.age < 65
Thinking with brackets
• This looks like an intimidating query at first
sight, but it can be built up step by step:

SELECT Act.Name, Act.Sex FROM


(
( Direct
Direct
INNER
INNER
JOIN
JOIN
Work
Work
ON ON
(Direct.name
(Direct.name= Work.director)
= Work.director)) )
...INNER JOIN Act
...
ON (Work.actor = Act.name)
)
WHERE Direct.age < 65
Aliases
• Two
Aliases
forms:
rename columns or tables to
• Column
Make names
alias more meaningful
• Make names
SELECT columnshorter and easier to type
• Resolve ambiguous names
AS newName...

• Table alias
SELECT ...
FROM table
AS newName
SQL says ‘AS’ is optional, but
Oracle doesn’t even accept it.
Business Alias Example
Employees
ID Name SELECT
123 Tinky Winky E.ID AS empID,
124 Dipsy
E.Name, W.Dept
125 La La
126 Po FROM
Employee E
WorksIn
WorksIn W
ID Dept
WHERE
124 Marketing E.ID = W.ID
125 Sales
125 Marketing
Business Alias Example

SELECT
result: E.ID AS empID,
ID Name Dept
E.Name, W.Dept
FROM
124 Dipsy Marketing Employee E
125 La La Sales
125 La La Marketing WorksIn W
WHERE
E.ID = W.ID
This Lecture in Exams
Track CD
cID Num Title Time aID cID Title Price
1 1 Violent 2391 1 Mix 9.99
1 2 Every Girl 4101 2 Compilation 12.99
2 3 Breather 2171
1 4 Part of Me 2791 Artist
2 1 Star 3621
2 2 Teaboy 4172 aID Name
1 Stellar
2 Cloudboy
This Lecture in Exams
• Find a list of all the CD titles. (1 mark)

• Find a list of the titles of tracks that are more than 300
seconds long.
(2 marks)

• Find a list of the names of those artists who have a track on


the CD with the title “Compilation”.
(4 marks)
Next Lecture
• More SQL SELECT
• ‘Self-joins’
• Subqueries
• IN, EXISTS, ANY, ALL
• For more information
• Connolly and Begg Chapter 5
The Assignment
• Worth 25% of your final mark
• Two components:
• A written worksheet
• A set of SQL programs
• Due Monday 1st December
• Available but not all parts covered in
lectures yet

You might also like