sql queries ordering and grouping and joins. rhs – soc 2 sql query - ordering in a query producing...

39
SQL queries ordering and grouping and joins

Upload: caroline-blair

Post on 04-Jan-2016

225 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

SQL queriesordering and grouping and

joins

Page 2: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 2

SQL query - ordering

• In a query producing a large result, it may be beneficial to order the result

• SQL allows us to order the result by any of the fields in the result

• We use the keyword ORDER BY

Page 3: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 3

SQL query - ordering

SELECT <fieldlist>

FROM <tablename>

WHERE <condition>

ORDER BY <fieldname>

Which fields do I want

From what table do I want the fields

What conditions must the fields fulfill

What order are the results sorted in

Page 4: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 4

HotelDB

HOTEL: (Hotel_No, Name, Address)

ROOM: (Room_No, Hotel_No, Types, Price)

BOOKING: (Hotel_No, Guest_No, Date_From, Date_To, Room_No)

GUEST: (Guest_No, Name, Address)

Page 5: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 5

SQL query - ordering

SELECT * FROM Hotel

ORDER BY Name;

SELECT Guest_No, Date_From, Room_no FROM booking WHERE Hotel_no = 1

ORDER BY Date_From;

SELECT * FROM guest ORDER BY Address;

Page 6: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 6

SQL query - ordering

• We can even specifiy more than one field for ordering – secondary fields used if primary fields are identical

• We can choose between descending and ascending order, using the keywords DESC and ASC, respectively

SELECT Guest_No, Date_From, Room_no FROM booking WHERE Hotel_no = 1 ORDER BY Guest_No DESC, Date_From ASC;

Page 7: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 7

SQL query - functions

• We can even do some (simple) arithmetic in SQL, using a basic set of functions– COUNT– SUM– AVG– MIN– MAX

• These are called aggregate functions

Page 8: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 8

SQL query - functions

• A aggregate function works on the values of a specific field (column)

• The set of values is determined by the search conditions

• How many rooms have Hotel no 1

SELECT count(*) FROM room WHERE Hotel_No = 1;

Page 9: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 9

SQL query - functions

• This query can also be written as

SELECT count(*) AS Number_of_Rooms FROM room WHERE Hotel_No = 1;

• The AS keyword allows us to rename a column in the search result

• Only cosmetic, but useful…

Page 10: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 10

SQL query - functions

SELECT

COUNT(*) AS Number_of_Rooms, AVG(Price) as Avg_price,

Max(Price)

FROM room

where Hotel_no = 1;

Page 11: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 11

Exercise 4 – SQL queries

• Use the Hotel_DB database.• With the data in place, run the below queries on the

database– SELECT * FROM Booking ORDER BY Hotel_no ASC, Room_NO

DESC

– SELECT Name, Address FROM Hotel ORDER BY Hotel_No;– SELECT MAX(Price) AS maxPrice FROM room WHERE Types

= 'D';

• Now formulate queries yourself, in order to retrieve the below data:– Get all bookings from hotel_no 2 (oldest first)– Get a sorted list of name and address of Guests

Page 12: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 12

SQL query - grouping

• The aggregate functions are good for calculating properties for the entire result of the search

• We may sometimes wish to find proper-ties for a certain group within the result

• This can be done using WHERE…

• …but can be cumbersome if the groups are very numerous

Page 13: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 13

SQL query - grouping

• Syntax:

SELECT <fieldlist>

FROM <tablename>

GROUP BY <fieldlist>

• Produces a result for each group, specified in the field list

Page 14: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 14

SQL query - grouping

• ”Find the total number of booking made for each hotel”

SELECT count(*)as bookings , hotel_no

from booking group by hotel_no

order by hotel_no;

Page 15: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 15

SQL query - grouping

• In general; only include groups which fulfill some criteria

• This can be done using the HAVING keyword

Page 16: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 16

SQL query - grouping

• Syntax:SELECT <fieldlist>FROM <tablename>GROUP BY <fieldlist>HAVING <criteria>

SELECT count(*), types, sum(price) FROM room GROUP BY types HAVING sum(price)>3000 ;

Page 17: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 17

SQL query - grouping

• But wait…

• …isn’t HAVING the same as WHERE..?

• Not quite– WHERE is for filtering out specific records– HAVING is for filtering out specific groups

from the final result

• We cannot use an aggregate function in a WHERE clause

Page 18: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 18RHS – SOC 18

SQL query – beyond one table

• So far, we have only applied queries to a single table

• It is possible – and very useful – to make queries applied to several tables

• Can answer more complex questions…

• …but queries also tend to become more complex themselves

Page 19: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 19RHS – SOC 19

SQL query – beyond one table

• We use a HotelDB database as example

Room Guest

Booking

Page 20: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 20RHS – SOC 20

SQL query – subqueries

• Suppose we wish to answer a (complex) question like this:

• Find room_no, room type, price for all hotels in Roskilde

• This question cannot be answered by a single query (as we know it…)

• Information is spread out in multiple tables

Page 21: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 212011 21

SQL query – subqueries

SELECT room_no, types, priceFROM room WHERE hotel_no IN

(SELECT hotel_no FROM hotelWHERE address LIKE '%Roskilde%');

• Use the IN keyword when more than one result from the subquery

Page 22: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 22RHS – SOC 22

SQL query – subqueries

• Result from inner query (the subquery) is used as input to outer query

• The inner query produces a result table – just as any other query – which is then used by the outer query

• Very convenient – but some complications– Name clash– Multiple results

Page 23: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 23RHS – SOC 23

SQL query – subqueries

• When we query more than one table, field names from different tables might be identical – a name clash

• We can qualify a field name by prefixing it with the table name– Room.hotel_no– Hotel.hotel_no

Page 24: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 24

SQL query – subqueries

SELECT room_no, types, price, Hotel.name

FROM room, hotel

WHERE Room.hotel_no IN

(SELECT hotel_no

FROM hotel

WHERE address LIKE '%Roskilde%');

Page 25: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 25RHS – SOC 25

SQL query – joining

• Another approach to multi-table queries is to use join

• To ”join” tables is to make a kind of ”multiplication” of the tables

• Simple case: Join without any conditions:

SELECT *

FROM Room, Hotel

Page 26: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 26RHS – SOC 26

SQL query – joining

• If the previous query is run against the HotelDB database

• How many rows

• All combinations of Hotel records and Room records

• All fields from both tables are included

• This is rarely what we want…

Page 27: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 27RHS – SOC 27

SQL query – joining

• In almost all cases, we wish to pick out those rows where certain fields match

• Example: Find the room_no, type and price of the room, and the name of the Hotel, for each Hotel from Roskilde

Page 28: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 28RHS – SOC 28

SQL query – joining

SELECT Room_No, types, name, price

FROM room r, hotel h

WHERE h.hotel_no = r.hotel_no

AND address LIKE '%Roskilde%';

Page 29: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RHS – SOC 29RHS – SOC 29

SQL query – joining

• This is a quite common ”pattern” for multi-table queries– Tables representing relations only contain

identifiers (keys in other tables)– ”Real data” is contained in tables representing

entities (identifiers are keys)– Obtaining ”real data” for relations requires use

of join, with matching of key fields

Page 30: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

Different SQL JOINs• INNER JOIN:

– Returns all rows when there is at least one match in BOTH tables

• LEFT JOIN: – Return all rows from the left table, and the matched rows

from the right table• RIGHT JOIN:

– Return all rows from the right table, and the matched rows from the left table

• FULL JOIN: – Return all rows when there is a match in ONE of the tables

RHS – SOC30

Page 31: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

Inner Join

• Selects all rows from both tables as long as there is a match between the columns in both tables.

• Syntax:

SELECT column_name(s)FROM table1INNER JOIN table2ON table1.column_name=table2.column_name;

RHS – SOC 31

Page 32: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

Inner JoinSELECT Room_No, types, name, price

FROM room

INNER JOIN hotel

ON room.hotel_no =hotel.hotel_no

Returns all rows when there is matching Hotel_No in BOTH tables

RHS – SOC 32

Page 33: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

LEFT JOIN• Return all rows from the left table, and the matched rows

from the right table• Syntax:

SELECT column_name(s)FROM table1LEFT JOIN table2ON table1.column_name=table2.column_name;

RHS – SOC 33

Page 34: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

LEFT JOIN

• List all Guests and their Bookings if they have any:

SELECT Guest.Guest_No, Guest.Name, Booking.Date_From, Booking.Date_To

FROM Guest

LEFT JOIN Booking

ON Guest.Guest_No = Booking.Guest_No

ORDER BY Guest.Guest_No;

RHS – SOC 34

Page 35: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RIGHT JOIN • Returns all rows from the right table (table2), with the

matching rows in the left tab• Syntax:

SELECT column_name(s)FROM table1RIGHT JOIN table2ON table1.column_name=table2.column_namele (table1).

RHS – SOC 35

Page 36: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

RIGHT JOIN

• List all Hotel and the Rooms in the Hotels

SELECT Room.Room_No, Hotel.Hotel_No, Hotel.Name

FROM Room

RIGHT JOIN Hotel

ON Room.Hotel_No=Hotel.Hotel_No

ORDER BY Hotel.Hotel_No;RHS – SOC 36

Page 37: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

FULL OUTER JOIN

• Returns all rows from the left table (table1) and from the right table (table2).

• The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.

RHS – SOC 37

Page 38: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

FULL OUTER JOIN

• Syntax:

SELECT column_name(s)FROM table1FULL OUTER JOIN table2ON table1.column_name=table2.column_name;

RHS – SOC 38

Page 39: SQL queries ordering and grouping and joins. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result

FULL OUTER JOIN

SELECT Guest.Guest_No, Guest.Name, Booking.Date_From, Booking.Date_To

FROM Guest

FULL OUTER JOIN Booking

ON Guest.Guest_No = Booking.Guest_No

ORDER BY Guest.Guest_No;

RHS – SOC 39