Title: SQL SELECT
1SQL SELECT
- Database Systems Lecture 7
2Last Lecture
- Starting SQL
- DROP TABLE
- ALTER TABLE
- INSERT, UPDATE, and DELETE
- Sequences
- For more information
- Connolly and Begg chapters 5 and 6
3Todays hour of fun
- The data dictionary
- SQL SELECT
- WHERE clauses
- SELECT from multiple tables
- JOINs
- Aliases
- For more information
- Connolly and Begg Chapter 5
4SQL
- 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.
5Base 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.
6Different 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
7Different 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
8Different 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
9The Data Dictionary
- The data dictionary or catalogue stores
- Information about database tables
- Information about the columns of tables
- Other information - users, locks, indexes, and
more - This is metadata
- Some DBMSs let you query the catalogue
- In Oracle you can access the metadata in several
ways - There are system tables with metadata in them
- You can also DESCRIBE tables
10Data Dictionaries
- To find the details of a table use
- DESCRIBE lttable namegt
- Example
- SQLgt DESCRIBE Student
- Name Null? Type
- ------------ -------- ----------
- STUID NOT NULL NUMBER(38)
- STUNAME NOT NULL VARCHAR2(50)
- STUADDRESS VARCHAR2(50)
- STUYEAR NUMBER(38)
11Oracle 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 dont use
- SELECT FROM user_tables
12SELECT
- The SQL command you will use most often
- Queries a set of tables and returns results as a
table - Lots of options, we will look at many of them
- Usually more than one way to do any given query
- SQLs SELECT is different from the relational
algebras Select - SELECT in SQL has all the functionality of its
equivalent in relational algebra - But it is a bit different because SQL differs
from the relational model, adding extra
qualifiers
13SQL SELECT Overview
- SELECT
- DISTINCT ALL ltcolumn-listgt
- FROM lttable-namesgt
- WHERE ltconditiongt
- ORDER BY ltcolumn-listgt
- GROUP BY ltcolumn-listgt
- HAVING ltconditiongt
- (- optional, - or)
14Example Tables
15Sample SELECTs
16Sample SELECTs
17DISTINCT and ALL
- Sometimes you end up with duplicate entries
- Using DISTINCT removes duplicates
- Using ALL retains them - this is the default
- SELECT ALL Last
- FROM Student
SELECT DISTINCT Last FROM Student
18WHERE Clauses
- Usually you dont want all the rows
- A WHERE clause restricts the rows that are
returned - It takes the form of a condition - only those
rows that satisfy the condition are returned
- Example conditions
- Mark lt 40
- First John
- First ltgt John
- First Last
- (First John) AND
- (Last Smith)
- (Mark lt 40) OR (Mark gt 70)
19WHERE Examples
- SELECT FROM Grade
- WHERE Mark gt 60
- SELECT DISTINCT ID
- FROM Grade
- WHERE Mark gt 60
20WHERE Example
- Write an SQL query to find a list of the ID
numbers and marks in IAI of students who have
passed (scored 40 or higher) IAI
ID Mark S103 58 S104 65
21One Solution
SELECT ID, Mark FROM Grade WHERE (Code IAI)
AND (Mark gt 40)
22SELECT from Multiple Tables
- Often you need to combine information from two or
more tables - You can get the effect of a product by using
- SELECT FROM Table1, Table2...
- If the tables have columns with the same name
ambiguity results - You resolve this by referencing columns with the
table name - TableName.Column
23SELECT from Multiple Tables
- SELECT
- First, Last, Mark
- FROM Student, Grade
- WHERE
- (Student.ID
- Grade.ID) AND
- (Mark gt 40)
24SELECT from Multiple Tables
SELECT ... FROM Student, Grade WHERE...
ID First Last ID Code Mark S103 John Smith S103 D
BS 72 S103 John Smith S103 IAI 58 S103 John Smith
S104 PR1 68 S103 John Smith S104 IAI 65 S103 John
Smith S106 PR2 43 S103 John Smith S107 PR1 76 S103
John Smith S107 PR2 60 S103 John Smith S107 IAI 3
5 S104 Mary Jones S103 DBS 72 S104 Mary Jones
S103 IAI 58 S104 Mary Jones S104 PR1 68 S104 Ma
ry Jones S104 IAI 65 S104 Mary Jones
S106 PR2 43
25SELECT from Multiple Tables
SELECT ... FROM Student, Grade WHERE
(Student.ID Grade.ID) AND ...
26SELECT from Multiple Tables
SELECT ... FROM Student, Grade WHERE
(Student.ID Grade.ID) AND (Mark gt 40)
ID First Last ID Code Mark S103 John Smith S103 D
BS 72 S103 John Smith S103 IAI 58 S104 Mary
Jones S104 PR1 68 S104 Mary Jones
S104 IAI 65 S106 Mark Jones S106 PR2 43 S107 Jo
hn Brown S107 PR1 76 S107 John Brown S107 PR2 60
27SELECT from Multiple Tables
SELECT First, Last, Mark FROM Student, Grade
WHERE (Student.ID Grade.ID) AND (Mark gt 40)
First Last Mark John Smith 72 John Smith 58 Mary
Jones 68 Mary Jones 65 Mark Jones
43 John Brown 76 John Brown 60
28SELECT from Multiple Tables
- When selecting from multiple tables you almost
always use a WHERE clause to find entries with
common values - You have joined tables by listing them with
commas.
- SELECT FROM
- Student, Grade, Course
- WHERE
- Student.ID Grade.ID
- AND
- Course.Code
- Grade.Code
29SELECT from Multiple Tables
Grade
Student
Course
Student.ID Grade.ID
Course.Code Grade.Code
30JOINs
- JOINs can be used to combine tables
- There are many types of JOIN
- CROSS JOIN
- INNER JOIN
- NATURAL JOIN
- OUTER JOIN
- OUTER JOINs are linked with NULLs - more later
- A CROSS JOIN B
- returns all pairs of rows from A and B
- A NATURAL JOIN B
- returns pairs of rows with common values
- A INNER JOIN B
- returns pairs of rows satisfying a condition
31CROSS JOIN
- SELECT FROM
- Student CROSS JOIN
- Enrolment
32NATURAL JOIN
- SELECT FROM
- Student NATURAL JOIN Enrolment
33Equivalencies
- SELECT FROM
- A CROSS JOIN B
- is the same as
- SELECT FROM A, B
- SELECT FROM
- A NATURAL JOIN B
- is the same as
- SELECT FROM
- A, B
- WHERE A.col1 B.col1
- AND A.col2 B.col2
- AND...
34INNER JOIN
- INNER JOINs specify a condition which the pairs
of rows satisfy - SELECT FROM
- A INNER JOIN B
- ON ltconditiongt
- Can also use
- SELECT FROM
- A INNER JOIN B
- USING
- (col1, col2,)
- Chooses rows where the given columns are equal
35INNER JOIN
- SELECT FROM
- Student INNER JOIN Enrolment USING (ID)
36INNER JOIN
- SELECT FROM
- Buyer INNER JOIN Property ON
- Price lt Budget
37INNER JOIN
- SELECT FROM
- A INNER JOIN B
- ON ltconditiongt
- is the same as
- SELECT FROM A, B
- WHERE ltconditiongt
- SELECT FROM
- A INNER JOIN B
- USING(col1, col2,...)
- is the same as
- SELECT FROM A, B
- WHERE A.col1 B.col1
- AND A.col2 B.col2
- AND ...
38JOINs vs WHERE Clauses
- JOINs (so far) are not needed
- You can have the same effect by selecting from
multiple tables with an appropriate WHERE clause - So should you use JOINs or not?
- Yes, because
- They lead to better, conciser queries
- NATURAL JOINs are very common
- No, because
- Support for JOINs varies a fair bit among SQL
dialects it can be inconsistent.
39Writing Queries
- When writing queries
- There are often many ways to write the query
- You should worry about being correct, clear, and
concise in that order - Dont worry about being clever or efficient
- Most DBMSs have query optimisers
- These take a users query and figure out how to
efficiently execute it - A simple query is easier to optimise
- Well look at some ways to improve efficiency
later
40Multiple Joins Example
41Multiple Join Query
- What is the sex of the actors who have worked
with directors under the age of 65?
42Solution
- 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 lt 65
43Thinking 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 ( ... )
WHERE Direct.age lt 65
SELECT Act.Name, Act.Sex FROM ( ( Direct
INNER JOIN Work ON (Direct.name
Work.director) ) ... ) WHERE Direct.age lt 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 lt 65
44Aliases
- Aliases rename columns or tables to
- Make names more meaningful
- Make names shorter and easier to type
- Resolve ambiguous names
- Two forms
- Column alias
- SELECT column
- AS newName...
- Table alias
- SELECT ...
- FROM table
- AS newName
45Business Alias Example
Employees
- SELECT
- E.ID AS empID,
- E.Name, W.Dept
- FROM
- Employee E
- WorksIn W
- WHERE
- E.ID W.ID
46Business Alias Example
- SELECT
- E.ID AS empID,
- E.Name, W.Dept
- FROM
- Employee E
- WorksIn W
- WHERE
- E.ID W.ID
result
ID Name Dept 124 Dipsy
Marketing 125 La La Sales 125 La La
Marketing
47This Lecture in Exams
48This 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)
49Next Lecture
- More SQL SELECT
- Self-joins
- Subqueries
- IN, EXISTS, ANY, ALL
- For more information
- Connolly and Begg Chapter 5
50The 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