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

More SQL Select: Database Systems Lecture 8

The document discusses more SQL select concepts including: 1) Aliases that allow renaming columns or tables to make names more meaningful or resolve ambiguous names. 2) Self joins that allow a table to be joined with itself using aliases to find employees who work in the same department as "Po". 3) Subqueries that allow a select statement to be nested inside another query to filter results, such as finding employees in the same department as "Po". 4) IN, EXISTS, and other operators that allow comparing values to the results of a subquery.

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)
50 views

More SQL Select: Database Systems Lecture 8

The document discusses more SQL select concepts including: 1) Aliases that allow renaming columns or tables to make names more meaningful or resolve ambiguous names. 2) Self joins that allow a table to be joined with itself using aliases to find employees who work in the same department as "Po". 3) Subqueries that allow a select statement to be nested inside another query to filter results, such as finding employees in the same department as "Po". 4) IN, EXISTS, and other operators that allow comparing values to the results of a subquery.

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/ 45

More SQL Select

Database Systems Lecture 8


Last Lecture on DBS…
• The data dictionary

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

• For more information


• Connolly and Begg Chapter 5

More SQL SELECT


Today’s Red-hot Action

• Aliases & Self-joins


• Subqueries
• IN, EXISTS, ANY, ALL
• Order By

• For more information


• Connoly and Begg Chapter 5

More SQL SELECT


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.

More SQL SELECT


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
More SQL SELECT
Business Alias Example

SELECT
Result: E.ID AS empID,
empID 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

More SQL SELECT


Aliases and ‘Self-Joins’
Employee
Aliases can be used to
Name Dept
copy a table, so that a
it can be combined Dipsy Marketing
with itself: La La Sales
Tinky W Sales
Po Marketing
Who works with Po? Sun Marketing

SELECT A.Name FROM Employee A, Employee B


WHERE A.Dept=B.Dept AND B.Name=‘Po’

More SQL SELECT


Aliases and Self-Joins

Employee Employee

A B
Name Dept Name Dept
Dipsy Marketing Dipsy Marketing
La La Sales La La Sales
Tinky Sales Tinky Sales
Po Marketing Po Marketing
Sun Marketing Sun Marketing

More SQL SELECT


Aliases and Self-Joins
SELECT … FROM Employee A, Employee B …

A.Name A.Dept B.Name B.Dept


Dipsy Marketing Dipsy Marketing
La La Sales Dipsy Marketing
Tinky Sales Dipsy Marketing
Po Marketing Dipsy Marketing
Sun Marketing Dipsy Marketing
Dipsy Marketing La La Sales
La La Sales La La Sales
Tinky Sales La La Sales
Po Marketing La La Sales
MoreSun
SQL SELECTMarketing La La Sales
Aliases and Self-Joins
SELECT … FROM Employee A, Employee B
WHERE A.Dept = B.Dept
A.Name A.Dept B.Name B.Dept
Dipsy Marketing Dipsy Marketing
Po Marketing Dipsy Marketing
Sun Marketing Dipsy Marketing
La La Sales La La Sales
Tinky Sales La La Sales
La La Sales Tinky Sales
Tinky Sales Tinky Sales
Dipsy Marketing Po Marketing
Po Marketing Po Marketing
MoreSun
SQL SELECTMarketing Po Marketing
Aliases and Self-Joins
SELECT … FROM Employee A, Employee B
WHERE A.Dept = B.Dept AND B.Name = ‘Po’
A.Name A.Dept B.Name B.Dept
Dipsy Marketing Po Marketing
Po Marketing Po Marketing
Sun Marketing Po Marketing

More SQL SELECT


Aliases and Self-Joins
SELECT A.Name FROM Employee A, Employee B
WHERE A.Dept = B.Dept AND B.Name = ‘Po’

A.Name
Dipsy
Po
Sun

The result is the names of all employees who work in the


same department as Po.

More SQL SELECT


Subqueries
• A SELECT statement can•E.g. Get the
be nested names
inside
another query to form aof
subquery
people who are in
Po’s department:
• The results of the subquery are passed back to
the containing query SELECT Name
FROM Employee
WHERE Dept =
(SELECT Dept
FROM Employee
WHERE Name=‘Po’)

More SQL SELECT


Subquery Order
First the
•SELECT subquery is evaluated, returning the
Name
value
FROM ‘Marketing’
Employee
This result
• WHERE Dept is= passed to the main query
(SELECT Dept
SELECT Name
FROM Employee
FROM Employee
WHERE
WHERE Dept =
Name=‘Po’)
‘Marketing’

More SQL SELECT


Subquery Results
• Often
Optionsa subquery will return a set of values
rather than atosingle
• IN - checks see if avalue
value is in the set
• EXISTS - checks to see if the set is empty or not
• ALL/ANY - checks to see if a relationship holds for
• You can’t directly compare a single value to a
every/one member of the set
set

More SQL SELECT


(NOT) IN clause
• Using IN we can see if a given value is in a set of
SELECT <columns>
values
FROM <tables>
WHERE <value>
• NOT IN checks to see if a given value is not in the
IN <set>
set

• The set can be given explicitly or from a subquery


SELECT <columns>
FROM <tables>
WHERE <value>
NOT IN <set>
More SQL SELECT
(NOT) IN
SELECT *
Employee FROM Employee
Name Department Manager WHERE Department IN
John Marketing Chris (‘Marketing’,
Mary Marketing Chris ‘Sales’)
Chris Marketing Jane Name Department Manager
Peter Sales Jane
Jane Management null John Marketing Chris
Mary Marketing Chris
Chris Marketing Jane
Peter Sales Jane

More SQL SELECT


(NOT) IN

Employee
Name Department Manager SELECT *
John Marketing Chris FROM Employee
Mary Marketing Chris WHERE Name NOT IN
Chris Marketing Jane (SELECT Manager
Peter Sales Jane FROM Employee)
Jane Management null

More SQL SELECT


(NOT) IN
• First the subquery • This gives
SELECT Manager
SELECT *
FROM Employee
FROM Employee
• is evaluated giving WHERE Name NOT
IN
Manager (‘Chris’,‘Jane’, null)
Chris
Chris Name Department Manager
Jane John Marketing Chris
Jane
Mary Marketing Chris
null
Peter Sales Jane
More SQL SELECT
(NOT) EXISTS
• Using EXISTS we see if there is at least one
SELECT <columns>
element in a set FROM <tables>
WHERE EXISTS <set>
• NOT EXISTS is true if the set is empty

SELECT <columns>
• The set is always given by a subquery
FROM <tables>
WHERE NOT EXISTS
<set>

More SQL SELECT


(NOT) EXISTS

Employee SELECT *
FROM Employee AS E1
Name Department Manager
WHERE EXISTS
John Marketing Chris ( SELECT * FROM
Mary Marketing Chris
Employee AS E2
Chris Marketing Jane
WHERE E1.Name =
Peter Sales Jane
Jane Management null E2.Manager)

Name Department Manager


Chris Marketing Jane
Jane Management null
More SQL SELECT
(NOT) EXISTS
E1
Name Department Manager
SELECT *
John Marketing Chris
Mary Marketing Chris
FROM Employee AS E1
Chris Marketing Jane WHERE EXISTS
Peter Sales Jane ( SELECT * FROM
Jane Management null Employee AS E2
WHERE E1.Name =
E2 E2.Manager)
Name Department Manager
Name Department Manager
John Marketing Chris
Mary Marketing Chris Chris Marketing Jane
Chris Marketing Jane Jane Management null
Peter Sales Jane
More SQL SELECT
Jane Management null
(NOT) EXISTS
• Find employees who are managers
Employee
Dept Name ID Name Dept
1 Simon 1 Carol 2
4 Dave 2 Grace 1
Manager 3 Simon 1
Select * 4 Dave 2
From Employee E
Where Exists ( Select * From Manager M
Where E.Name = M.Name And
E.Dept = M.Dept )
• Where condition is satisfied if subquery returns at least
one tuple (result set is not empty)
More SQL SELECT
Student Registration Module
STUID SNAME STUID MODID MODID LECID

 
01 Jones 01 OOS OOS tjb
02 Chan 01 IHF IIT tjb
03 Hunt
02 OOS DBS bai
04 Jones
04 DBS IHF geb

Task: Use ‘In’ or ‘Not In’ and ‘Exists’ or ‘Not Exists’ to


find the students who have not registered for any modules
Select * From Student Where SID Not In (Select SID From Registration)
Select * From Student S Where Not Exists
(Select STUID From Registration R Where S.STUID = R.STUID)
More SQL SELECT
In or Exists
••IN makes
EXISTS anda Not
value comparison
EXISTS test the existence or non
•The attribute
existence of thereturned
of tuples outer queryby athat is used in the
subquery
subquery must be listed between Where and IN or
• Nothing
betweenneeds
WHERE to be
andlisted
NOTbetween
IN WHERE and
• EXISTS
Only oneor WHEREofand
attribute the NOT
outerEXISTS
query can be tested
• against
EXISTS the
and outcome
NOT EXISTS of the subquery
allow multiple attributes of the
outer query to be used in the subquery

More SQL SELECT


ANY and ALL
• ANY and ALL compare a• single
val =value
ANY to a setis
(set)
of values true if there is at
least one member of
the setoperators
• They are used with comparison equal to like
the
=, >, <, <>, >=, <= value

• val = ALL (set) is


true if all members of
the set are equal to
the value

More SQL SELECT


ALL
Find the names of the
employee(s) who earn the
highest salary:
Name Salary
Mary 20,000 SELECT Name
John 15,000 FROM Employee
Jane 25,000
WHERE Salary >=
Paul 30,000
ALL (
SELECT Salary
FROM Employee)

More SQL SELECT


ANY
Find the names of
employee(s) who earn more
than someone else:
Name Salary
Mary 20,000 SELECT Name
John 15,000 FROM Employee
Jane 25,000
WHERE Salary >
Paul 30,000
ANY (
SELECT Salary
FROM Employee)

More SQL SELECT


Word Searches
WordGiven
• EG: Searches
a database of my books

•• Commonly used for searching product catalogues


Searching for “crypt” would return
etc.
•“Cryptonomicon” by Neil Stephenson
• “Applied Cryptography” by Bruce Schneier
• Want to be able to search by keyword

• Want to be able to use word stemming for flexible


searching

More SQL SELECT


Word Searches
• To do a word search we canItems keep
• A table of items to be searcheditmID itmTitle
• A table of keywords
Keywords
• A linking table saying which keywords belong to
which items keyID keyWord

ItemKey
itmID keyID

More SQL SELECT


Word Searches

To search we can use queries like


SELECT * FROM Items
WHERE itmID IN (
SELECT itmID FROM ItemKey
WHERE keyID IN (
SELECT keyID FROM Keywords
WHERE keyWord LIKE 'crypt%‘))

More SQL SELECT


Word Searches
• Sometimes
SELECT * FROM Items
you need to search for a set of
WHERE itmID IN (
words
SELECT itmID FROM ItemKey
• To
WHERE findINentries
keyID ( with all words you can link conditions
SELECT keyID FROM Keywords
with AND
WHERE keyWord LIKE
• To find entries with any of the words use OR
'word1%'))
AND
itmID IN (
SELECT itmID FROM ItemKey
WHERE keyID IN (
SELECT keyID FROM Keywords
WHERE keyWord LIKE
'word2%'))

More SQL SELECT


ORDER BY
The ORDER
•SELECT BY clause sorts the results of a
<columns>
query
FROM <tables>
WHERE
• You <condition>
can sort in ascending (default) or descending
ORDER
order BY <cols>
• Multiple columns can be given
[ASCENDING |
• You cannot order by a column which isn’t in the
DESCENDING|
result
ASC | DESC ]

More SQL SELECT


ORDER BY Example

SELECT * FROM Grades


ORDER BY Mark
Grades
Name Code Mark Name Code Mark
Pingu DBS56 Bungle PR2 35
Pingu IAI 72 Bungle PR1 43
Zippy DBS60 Pikachu IAI 54
Bungle PR1 43 Pingu DBS56
Bungle PR2 35 Zippy DBS60
Pikachu IAI 54 Pingu IAI 72

More SQL SELECT


ORDER BY Example

SELECT * FROM Grades


ORDER BY Code ASC,Mark DESC
Grades
Name Code Mark Name Code Mark
Pingu DBS56 Zippy DBS 60
Pingu IAI 72
Pingu DBS 56
Zippy DBS60
Bungle PR1 43 Pingu IAI 72
Bungle PR2 35 Pikachu IAI 54
Pikachu IAI 54 Bungle PR1 43
Bungle PR2 35

More SQL SELECT


Why is ORDER BY odd?
• It is part of SQL but not part of the relational
model that underpins it. Why?

• Because as we know a database table is a


relation, and a relation is a set.

• Sets have no order. Just elements.

• The result of an Order by is not a relation.


This breaks the algebra.

More SQL SELECT


LIMIT
• Limit is also outside the remit of relational algebra
but, like group by, incredibly useful.

• The LIMIT clause can be used to constrain the


number of rows returned by the SELECT
statement.

• LIMIT takes one or two numeric arguments, which


must both be non-negative integer constants
(except when using prepared statements):

LIMIT offset, row_count


More SQL SELECT
web forum example: topics

More SQL SELECT


web forum example: topics

SELECT * FROM forum_topics


WHERE parent_board = ‘Aston Villa’
ORDER BY created_date Which board?
LIMIT 0,50
Sort chronologically

First page of posts

SELECT * FROM forum_topics


WHERE parent_board = ‘Aston Villa’
ORDER BY created_date
LIMIT 50,50 Allows a second page
of forum topics to be
More SQL SELECT generated off the cuff.
web forum example: posts

More SQL SELECT


web forum example: posts

SELECT * FROM forum_posts P

INNER JOIN forum_post_text T The text of a post is often kept in


ON (P.post_id = T.post_id) a separate table to improve
processing efficiency because
WHERE parent_topic_id = 337 the data is so large, so we JOIN.
ORDER BY posted_date DESC
LIMIT 0,20
Again sort results by
date, but this time
with the latest first

First page of 20 posts

More SQL SELECT


Perhaps RM is missing
something?
• These ordering functions seem so useful why has SQL
had to add them on top of the RM

• in the real world that perhaps the relational model is


missing a trick?

• Set theory also allows orderings but this has never


been included in the RM.

• Scope for improvement perhaps. RM is the best data


model there is, but not all she wrote.

More SQL SELECT


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

More SQL SELECT


This Lecture in Exams

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


the CD with the title “Compilation”.
(4 marks)

Note, this is one of the questions from last time, but there are
alternative solutions using subqueries, try solving this with a
query where you never list more than one table for a single
SELECT statement

More SQL SELECT


Next Lecture
• Yet more SQL
• Aggregate functions
• GROUP BY and HAVING
• UNION etc.
• For more information
• Connoly and Begg Chapter 5

More SQL SELECT

You might also like