SQL queries ordering and grouping and joins

Slides:



Advertisements
Similar presentations
Chapter 4 Joining Multiple Tables
Advertisements

Chapter 4 Hotel (hotelno, hotelname, city)
1 Assignment 2 Relational Algebra Which tables? What operations? Common attributes? What result (attributes)? Syntax (Standard Notations and Symbols) –Product:
CS 3630 Database Design and Implementation. SQL Query Clause Select and From Select * From booking; select hotel_no, guest_no, room_no from booking; select.
Chapter 5 SQL. Agenda Data Manipulation Language (DML) –SELECT –Union compatible operations –Update database.
Chapter 6 SQL Homework.
Chapter 5 SQL Homework.
Project Phase I Phase II Due Monday, April 15 Groups 1.
Concepts of Database Management Sixth Edition
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
Microsoft Access 2010 Chapter 7 Using SQL.
Computer Science 101 Web Access to Databases SQL – Extended Form.
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Download three SQL script files from wiki page.
SQL – Logical Operators and aggregation Chapter 3.2 V3.0 Napier University Dr Gordon Russell.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Chapter 3 Single-Table Queries
Chapter 5 SQL. Agenda Data Manipulation Language (DML) –SELECT –Union compatible operations –Update database.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Concepts of Database Management Seventh Edition
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
SQL queries subqueries and joining. RHS – SOC 2 SQL query – beyond one table So far, we have only applied queries to a single table It is possible – and.
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Select your database – Your database name is.
SQL - DML. Data Manipulation Language(DML) Are used for managing data: –SELECT retrieve data from the a database –INSERT insert data into a table –UPDATE.
Chapter 5 SQL: Data Manipulation Thomas Connolly, Carolyn Begg, Database System, A Practical Approach to Design Implementation and Management, 4 th Edition,
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
SQL introduction 2013.
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
© Jalal Kawash Database Queries Peeking into Computer Science.
INF 280 Database Systems SQL:Join
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
IST 210 More SQL Todd Bacastow IST 210: Organization of Data.
SQL queries ordering and grouping. RHS – SOC 2 SQL query - ordering In a query producing a large result, it may be beneficial to order the result SQL.
MIS2502: Data Analytics SQL – Getting Information Out of a Database.
QUERY CONSTRUCTION CS1100: Data, Databases, and Queries CS1100Microsoft Access1.
CS 3630 Database Design and Implementation. Base Table and View Base Table Stored on disk View Virtual table Records are not stored on disk Query is stored.
CS 3630 Database Design and Implementation. Where Clause and Aggregate Functions -- List all rooms whose price is greater than the -- average room price.
SQL queries ordering and grouping. SWC – SQL query - ordering In a query producing a large result, it may be beneficial to order the result SQL.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
CS 3630 Database Design and Implementation. Joins -- For each booking, display the booking -- details with the room type and price Select B.*, rtype,
CS 3630 Database Design and Implementation. Joins Retrieve data from two or more tables Join Conditions PK and FK (Natural Join) Other attributes (Theta.
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
CS 3630 Database Design and Implementation
Assignment 2 Relational Algebra Which tables? What operations?
CS3220 Web and Internet Programming More SQL
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
CS 3630 Database Design and Implementation
CS 3630 Database Design and Implementation
Assignment 2.
CS 3630 Database Design and Implementation
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
JOINS (Joinining multiple tables)
CS 3630 Database Design and Implementation
Chapter 4 Summary Query.
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
CS 3630 Database Design and Implementation
Access: SQL Participation Project
CS4222 Principles of Database System
Structured Query Language – The Fundamentals
M1G Introduction to Database Development
Query Functions.
Section 4 - Sorting/Functions
JOINS (Joinining multiple tables)
Presentation transcript:

SQL queries ordering and grouping and joins

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 RHS – SOC

SQL query - ordering SELECT <fieldlist> FROM <tablename> Which fields do I want SELECT <fieldlist> FROM <tablename> WHERE <condition> ORDER BY <fieldname> From what table do I want the fields What conditions must the fields fulfill What order are the results sorted in RHS – SOC

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) RHS – SOC

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; RHS – SOC

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; RHS – SOC

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 RHS – SOC

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; RHS – SOC

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… RHS – SOC

SQL query - functions SELECT COUNT(*) AS Number_of_Rooms, AVG(Price) as Avg_price, Max(Price) FROM room where Hotel_no = 1; RHS – SOC

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 RHS – SOC

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 RHS – SOC

SQL query - grouping Syntax: SELECT <fieldlist> FROM <tablename> GROUP BY <fieldlist> Produces a result for each group, specified in the field list RHS – SOC

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; RHS – SOC

SQL query - grouping In general; only include groups which fulfill some criteria This can be done using the HAVING keyword RHS – SOC

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 ; RHS – SOC

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 RHS – SOC

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  RHS – SOC RHS – SOC 18

SQL query – beyond one table We use a HotelDB database as example Room Guest Booking RHS – SOC RHS – SOC 19

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 RHS – SOC RHS – SOC 20

SQL query – subqueries SELECT room_no, types, price FROM room WHERE hotel_no IN (SELECT hotel_no FROM hotel WHERE address LIKE '%Roskilde%'); Use the IN keyword when more than one result from the subquery 2011 RHS – SOC 21

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 RHS – SOC RHS – SOC 22

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 RHS – SOC RHS – SOC 23

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%'); RHS – SOC

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 RHS – SOC RHS – SOC 25

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… RHS – SOC RHS – SOC 26

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 RHS – SOC RHS – SOC 27

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%'; RHS – SOC RHS – SOC 28

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 RHS – SOC RHS – SOC 29

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 – SOC

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 table1 INNER JOIN table2 ON table1.column_name=table2.column_name; RHS – SOC

Inner Join SELECT 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

LEFT JOIN Return all rows from the left table, and the matched rows from the right table Syntax: SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name=table2.column_name; RHS – SOC

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

RIGHT JOIN Returns all rows from the right table (table2), with the matching rows in the left tab Syntax: SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name=table2.column_namele (table1). RHS – SOC

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

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

FULL OUTER JOIN Syntax: SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name=table2.column_name; RHS – SOC

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