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

07 SQL2 Select

The SQL SELECT statement is used to retrieve data from one or more tables in a database. It allows the user to choose which rows and columns to retrieve and allows joins across multiple tables. Some key functions of SELECT include retrieving all data or specific columns from one or more tables, performing calculations on the retrieved data, joining multiple tables to link related data, grouping data to perform aggregate functions, and combining the results of multiple queries using UNION.

Uploaded by

danelozano23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

07 SQL2 Select

The SQL SELECT statement is used to retrieve data from one or more tables in a database. It allows the user to choose which rows and columns to retrieve and allows joins across multiple tables. Some key functions of SELECT include retrieving all data or specific columns from one or more tables, performing calculations on the retrieved data, joining multiple tables to link related data, grouping data to perform aggregate functions, and combining the results of multiple queries using UNION.

Uploaded by

danelozano23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Master in Information Technology

ICT - 209
Database Applications

MySQL 2
SELECT

1
Getting Data From a Database with MySQL
• The SQL SELECT statement is used to retrieve data from one or more
tables in a database
• It allows you to choose which row and which columns you would like
to retrieve and allows joins across several tables.

http://dev.mysql.com/doc/refman/5.0/en/select.html

2
Example Tables for This Lecture
• Books Borrowers
Name Number Name Number Dept
Book1 1 Anne 1 Maths
Book2 2 Bill 2 Maths
Book3 3 Claire 3 French
Book4 4 Duncan 4 French
Book5 5 Edward 5 French

• Loans
BookNumber PersonNumber
1 2
3 4

3
SELECT From One Table

• SELECT * FROM Borrowers


Shows whole table

• SELECT Name FROM Borrowers


Lists Borrowers names only

SELECT Number, Dept FROM Borrowers WHERE Name=“Anne”


Get Anne’s number and department

4
SELECT and Calculations
• There are many functions that you can include in a SELECT statement
• Some simple ones are:

• SELECT MAX(Number) FROM Borrowers


Shows largest borrower number (Min is also available)

• SELECT Number+1 FROM Borrowers


Adds 1 to each borrower number and reports it

or even

• SELECT sin(45)
Calculates the sine of 45 – no need to reference a table at all

5
Joining Tables
• SELECT borrowers.Name, books.Name FROM borrowers, books

• Pairs every borrower with every book


• Not an awful lot of use
• Needs to be expanded to be useful …

6
Looking up a Foreign Key
• Let’s say we want to know who has borrowed Book1
• The Loans table has this information, but not in a form that is immediately
accessible:
BookNumber PersonNumber
1 2
3 4
• SELECT Number FROM Books WHERE Name=“Book1”
Tells us that book1 has the ID number 1

• SELECT PersonNumber FROM Loans WHERE BookNumber=1


Tells us that person 2 has the book

• SELECT Name FROM Borrowers WHERE Number=2


Tells us that person number 2 is Bill, so Bill has Book1

7
Put it all Together
• SELECT Borrowers.Name FROM Borrowers, Books, Loans
WHERE Books.name="Book1" AND Books.Number=loans.booknumber
AND Borrowers.number=loans.personnumber

• Returns Bill.

• Note the use of AND. You can also use OR and NOT. Other useful logic:
– >, <, <=, >=, =, != (or <>)
– When comparing NULL, use IS NULL or IS NOT NULL
– You can search for partial strings using LIKE:

SELECT Name FROM Borrowers WHERE Name LIKE "%e"

The % character is a wild card, so above looks for anything ending in e

– SELECT Name FROM Borrowers WHERE Name LIKE “_e"

The _ is a single character wild card, so above looks for names with two characters
ending in e

8
Comparison Examples
• SELECT * FROM table WHERE x BETWEEN 1 and 3

• SELECT * FROM table WHERE x IN (‘A’,’B’,’C’)

• SELECT * FROM table WHERE x NOT IN (‘A’,’B’,’C’)

• Use brackets to enforce operator order:


• WHERE (a=1) AND (b=2 OR b=3) != WHERE (a=1 AND b=2) OR (b=3)

• Note: Commands and Names (such as table or field names) are not
case sensitive:
– Select = SELECT
– Table = table
• String literals may be case sensitive, depending on the collation.
– _ci at the end of the collation name means case insensitive
– Force a case sensitive search with
SELECT * FROM table WHERE BINARY name="John"
9
How to Construct a SELECT
• Decide what columns you want in your results table:

• SELECT col1, col2 …

• Then list all the tables involved in the selection (some won’t actually
provide a field in the select list, but are involved anyway

• SELECT col1, col2 FROM table1, table2, table3

• Then follow the path from what you want to look up to the answer,
building x=y statements joined by AND (or OR).

• SELECT col1, col2 FROM table1, table2, table3 WHERE


table1.col1=“target” AND table2.col1=table1.col1 …

• This is known as performing a Natural Join

10
More General Joins
• If we want to list all the people who have a book, and the books they
have:

• SELECT Borrowers.Name, Books.name FROM Borrowers, Books, Loans


WHERE Books.Number=loans.booknumber AND
Borrowers.number=loans.personnumber

• Note that
• SELECT * FROM Borrowers, Books, Loans WHERE
Books.Number=loans.booknumber AND
Borrowers.number=loans.personnumber

• Is an Equijoin, and lists all the columns from all tables that meet the
selection criteria, including them once for each table they appear in.
This is not very useful, but shows that everything matches up.

11
Inner and Outer Joins
• We have just seen an inner join. Only rows that meet the criteria
completely are returned.

• Now we look at outer joins – where more data is returned about one or
more of the fields.

• Lets say we want to list all of the people in the borrowers database,
regardless of whether or not they have a book out. If they do have a
book, we want to list that too, otherwise we will just return NULL for
people with no current book

• For this, we need the JOIN command:

http://dev.mysql.com/doc/refman/5.0/en/join.html

12
Join Syntax
• SELECT Borrowers.name, Books.name FROM Borrowers LEFT OUTER JOIN
(Books, Loans) ON (Books.Number=loans.booknumber AND
Borrowers.number=loans.personnumber)

• Note the syntax SELECT cols FROM table LEFT OUTER JOIN
(table,table) ON (conditions)

• You can use similar syntax for an inner join:


• SELECT Borrowers.name, Books.name FROM Borrowers INNER JOIN
(Books, Loans) ON (Books.Number=loans.booknumber AND
Borrowers.number=loans.personnumber)

• Is the same as the example on slide 10


13
A Contrived Example
• Who has the book with the lowest ID number?

• SELECT Borrowers.Name FROM Borrowers, Books, Loans


WHERE Books.number = (SELECT MIN(number) FROM Books) AND
Books.Number=loans.booknumber
AND Borrowers.number=loans.personnumber

• The Answer, as we would expect, is Anne


• Note the use of brackets to enclose the sub-SELECT and use of the
function MIN()

14
Groups
• We may want to summarise the data in the database, and there are
some statistical functions available.
• We have already seen MAX and MIN and there are others:
– AVG
– COUNT

• For example, how many people are there from each department?

• SELECT Dept, COUNT(Dept) FROM Borrowers GROUP BY Dept

15
How Many Books Does Each Department Have?
• We could show the list and count them ourselves:

• SELECT Borrowers.Dept FROM Borrowers, Books, Loans


WHERE Books.Number=loans.booknumber
AND Borrowers.number=loans.personnumber

• But SQL can do it for us:

• SELECT Dept, COUNT(Dept) FROM Borrowers, Books, Loans


WHERE Books.Number=loans.booknumber
AND Borrowers.number=loans.personnumber GROUP BY Dept

• You can select from the resultant table using HAVING


• SELECT Dept, COUNT(Dept) FROM Borrowers, Books, Loans
WHERE Books.Number=loans.booknumber
AND Borrowers.number=loans.personnumber GROUP BY Dept HAVING
COUNT(Dept) > 2

16
Another Example
• SELECT Dept, COUNT(Dept) FROM Borrowers, Books, Loans
WHERE Books.Number=loans.booknumber
AND Borrowers.number=loans.personnumber GROUP BY Dept HAVING
COUNT(Dept) = (SELECT MAX(COUNT(Dept)))

• Selects the department with the most books out and reports how many
they have

17
Union
• Allows you to make more than one selection at the same time and put
the results together
• A bit like using OR, but more flexible:

• SELECT Name FROM Borrowers WHERE Name="Anne" OR Name="Claire“

• Is the same as

• SELECT Name FROM Borrowers WHERE Name="Anne“


UNION
SELECT Name FROM Borrowers WHERE Name="Claire“

• Which might seem pointless…

18
Union
• But it is useful when selecting
across more than one table
Staff
• SELECT Name FROM Borrowers
UNION Name Number Role
SELECT Name FROM Staff Anne 1 Manager

• Selects the names of all borrowers Fred 2 Engineer


and all staff George 3 Engineer
Harry 4 Engineer
• Note that there is an Anne in both
tables. UNION will only list Anne
once. To see duplicate rows, use

• UNION ALL

19
Selection Manipulation
• Here are a few things you can do to the selected list:

• Sort the results by one or more field

• ORDER BY field, field, … [DESC]

• Force a query to contain unique entries only:

• SELECT DISTINCT …

• Select a given number of entries starting at a given offset

• SELECT * FROM table LIMIT(offset,count)

20
More on Sub Queries
• We can use a sub query, as we have already seen, but what happens
when the sub query produces more than 1 row?

• SELECT * FROM staff WHERE Name = ANY (SELECT Name FROM Borrowers)

• Selects staff whose name appears in both Staff and Borrowers tables

SELECT * FROM borrowers WHERE Number > ALL (SELECT Number FROM staff)

• Selects those borrowers who have a higher number than ALL of the
staff

21
Aliases
• You can give an alias to a table or column to make it easier to refer to
later in a query or to make it easier to read in the output:

• SELECT AVG(Number) FROM books


shows
AVG(Number)
3

• SELECT AVG(Number) Average FROM books


shows
Average
3

22
Aliases
• SELECT Role, COUNT(Role) FROM staff GROUP BY role
HAVING COUNT(role) > 1

Can be re-written as

• SELECT Role, COUNT(Role) count FROM staff GROUP BY role


HAVING count > 1

• Where count is an alias for COUNT(Role)

• You can also do this sort of thing:

• SELECT * FROM Books a, Borrowers b WHERE a.Number = b.Number

• We have made aliases for the tables to make reference to them easier

23

You might also like