SQL Select Statement Prof. Yitzchak Rosenthal. Syntax for SELECT statement Clauses must be written in the following order –SELECT –FROM –WHERE –GROUP.

Slides:



Advertisements
Similar presentations
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Advertisements

Chapter 4 Joining Multiple Tables
SQL - Subqueries and Schema Chapter 3.4 V3.0 Napier University Dr Gordon Russell.
CSC271 Database Systems Lecture # 13. Summary: Previous Lecture  Grouping through GROUP BY clause  Restricted groupings  Subqueries  Multi-Table queries.
CSE 1561 A Brief MySQL Primer Stephen Scott. CSE 1562 Introduction Once you’ve designed and implemented your database, you obviously want to add data.
Formal Logic Proof Methods Direct Proof / Natural Deduction Conditional Proof (Implication Introduction) Reductio ad Absurdum Resolution Refutation.
The University of Akron Dept of Business Technology Computer Information Systems The Relational Model: Query-By-Example (QBE) 2440: 180 Database Concepts.
XP Chapter 3 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Analyzing Data For Effective Decision Making.
Introduction to Oracle9i: SQL1 Basic SQL SELECT Statements.
Chapter 14 Getting to First Base: Introduction to Database Concepts.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 5: Subqueries and Set Operations.
A Guide to SQL, Seventh Edition. Objectives Understand, create, and drop views Recognize the benefits of using views Grant and revoke user’s database.
Terms - data,information, file record, table, row, column, transaction, concurrency Concepts - data integrity, data redundancy, Type of databases – single-user,
Inner join, self join and Outer join Sen Zhang. Joining data together is one of the most significant strengths of a relational database. A join is a query.
Microsoft Access 2010 Chapter 7 Using SQL.
Whiteboardmaths.com © 2007 All rights reserved
Access 2007 ® Use Databases How can Access help you to find and use information?
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
Computer Science 101 Web Access to Databases SQL – Extended Form.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
SQL/lesson 2/Slide 1 of 45 Retrieving Result Sets Objectives In this lesson, you will learn to: * Use wildcards * Use the IS NULL and IS NOT NULL keywords.
10/31/2012ISC239 Isabelle Bichindaritz1 SQL Graphical Queries Design Query By Example.
Microsoft Access 2010 Building and Using Queries.
Analyzing Data For Effective Decision Making Chapter 3.
Chapter 9 Joining Data from Multiple Tables
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
Using Special Operators (LIKE and IN)
Chapter 4Introduction to Oracle9i: SQL1 Chapter 4 Joining Multiple Tables.
Intro to SQL Management Studio. Please Be Sure!! Make sure that your access is read only. If it isn’t, you have the potential to change data within your.
Relational Databases.  In week 1 we looked at the concept of a key, the primary key is a column/attribute that uniquely identifies the rest of the data.
1 Chapter 10 Joins and Subqueries. 2 Joins & Subqueries Joins – Methods to combine data from multiple tables – Optimizer information can be limited based.
XP Chapter 3 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Analyzing Data For Effective Decision Making Chapter.
Finding Information A337/A523. What are some of the possible problems with finding information?
O FFICE M ANAGEMENT T OOL - II B BA -V I TH. Abdus Salam2 Week-7 Introduction to Query Introduction to Query Querying from Multiple Tables Querying from.
RDBMS MySQL. MySQL is a Relational Database Management System MySQL allows multiple tables to be related to each other. Similar to a Grandparent to a.
Advanced Relational Algebra & SQL (Part1 )
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
1 Chapter 4: Creating Simple Queries 4.1 Introduction to the Query Task 4.2 Selecting Columns and Filtering Rows 4.3 Creating New Columns with an Expression.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Aliya Farheen October 29,2015.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
Grouping Data Steve Perry
+ Complex SQL Week 9. + Today’s Objectives TOP GROUP BY JOIN Inner vs. Outer Right vs. Left.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Fall Lab 131 CS105 Lab 13 – Logical Operator Precedence and Joining Tables Announcements: MP 3 released Friday, 11/20 Honors project due: Tuesday,
IST 220 – Intro to DB Lab 2 Specifying Criteria in SELECT Statements.
SQL and Query Execution for Aggregation. Example Instances Reserves Sailors Boats.
Aggregator Stage : Definition : Aggregator classifies data rows from a single input link into groups and calculates totals or other aggregate functions.
SQL LANGUAGE TUTORIAL Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
CS 122: Lecture 3 Joins (Part 1) Tarik Booker CS 122 California State University, Los Angeles October 7, 2014.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
IFS180 Intro. to Data Management Chapter 10 - Unions.
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
Group Functions Lab 6.
Building and Using Queries
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Structured Query Language (SQL) William Klingelsmith
The final zeroes are not significant, they don’t have an impact on the size of the number. So these numbers are equal. They have the same value – 4/10.
JOINS (Joinining multiple tables)
Chapter 4 Summary Query.
Access: SQL Participation Project
Getting to First Base: Introduction to Database Concepts
Getting to First Base: Introduction to Database Concepts
Getting to First Base: Introduction to Database Concepts
Joins and other advanced Queries
JOINS (Joinining multiple tables)
New Perspectives on Microsoft
Presentation transcript:

SQL Select Statement Prof. Yitzchak Rosenthal

Syntax for SELECT statement Clauses must be written in the following order –SELECT –FROM –WHERE –GROUP BY –HAVING –ORDER BY

Order that the DBMS processes a SELECT statement –Step 1: FROM –Step 2: WHERE –Step 3: GROUP BY –Step 4: HAVING –Step 5: SELECT (this must be "writtten" first) –Step 6: ORDER BY At each step the DBMS keeps track of the "interim result set" which is then further refined by the next step Keep reading for more info...

Step 1: FROM clause –This step is processed slightly differently depending on whether the SQL 92 syntax is used or the pre-SQL 92 syntax is used –SQL 92 Syntax (i.e. JOIN/ON in FROM clause) generate cartesian product (ie "cross join") of (1) the first table and (2) the table in the first JOIN clause filter out records from cartesian product that don't match the first ON clause generate cartesian product of (1) the results so far and (2) the table in the next JOIN clause filter out records from cartesian product that don't match the associated "ON" clause keep proceeding in this way until all tables are joined –Older Syntax (i.e. no JOIN/ON in FROM clause) generate cartesian product (ie "cross join") of all the tables (the filtering will hapen later when the "WHERE" clause is processed)

Step 2: WHERE clause –Filter out records from the "interim result set" generated in Step 1 by filtering out (i.e. "throwing out") records that don't match the conditions in the WHERE clause Each record in the interim result set is looked at separately and the results of the WHERE clause is calculated. If the result of the WHERE clause for that row is TRUE then the row is kept. If the result of the WHERE clause for that row is FALSE then the row is "thrown away".

Step 3: GROUP BY –Create separate groups of rows that match in all of the values listed in the GROUP BY list. There may be a single group for all records in the interim result set or there may be many groups. There is ALWAYS at least one group.

Step 4: HAVING –Filter out all groups that don't match the conditions in the HAVING clause

Step 5: SELECT –Figure out what values will actually be included in the final result set by processing the SELECT clause

Step 6: ORDER BY –Sort the result set in the order specified in the ORDER BY clause

WHERE vs HAVING

WHERE vs. HAVING Similarities: –The WHERE and HAVING clauses are both used to exclude records from the result set. Differences –WHERE clause The WHERE clause is processed before the groups are created Therefore, the WHERE clause can refer to any value in the original tables –HAVING clause The HAVING clause is processed after the groups are created Therefore, the HAVING clause can only refer to aggregate information for the group (including fields that are part of the GROUP BY clause). The HAVING clause CANNOT refer to individual columns from a table that are not also part of the group.

Example

Example: Table The example on the following slides will use the following table: Table: Invoices VendorIdPaymentTotalInvoiceTotal

Example of HAVING clause without a WHERE clause

HAVING clause but NO WHERE clause In the following SELECT statement: –There is a HAVING clause but no WHERE clause –The GROUP BY clause works to group several rows from the original table together to get aggregate information about the group. –The HAVING clause eliminates some of the resulting rows of aggregate information. SELECT vendorId, avg(PaymentTotal) as avgPaymentTotal FROM invoices GROUP BY vendorId HAVING avg(PaymentTotal) <=10 ORDER BY avgPaymentTotal

Processing the select without WHERE Table: Invoices VendorIdPaymentTotalInvoiceTotal avgPaymentTotal group2 Step 1: Create the groups based on the GROUP BY Step 2: Generate the aggregate information (e.g. avg) for each group. group1 Interim result set

Processing the select without WHERE Table: Invoices VendorIdPaymentTotalInvoiceTotal avgPaymentTotal group1 group2 Step 3: Remove records from the result set based on the HAVING clause Final Results

Adding a WHERE clause to the example

Same select statement with WHERE We will now examine what happens when we add a WHERE clause to the same SELECT statement we used above. SELECT vendorId, avg(PaymentTotal) as avgPaymentTotal FROM invoices WHERE invoiceTotal < 1000 GROUP BY vendorId HAVING avg(PaymentTotal) <=10 ORDER BY avgPaymentTotal

Processing the select with where TablenName: Invoices VendorIdPaymentTotalInvoiceTotal Step 1: Process WHERE clause to eliminate some rows from consideration

Processing the select with where TablenName: Invoices VendorIdPaymentTotalInvoiceTotal Step 2: Process the GROUP BY to create groups from the remaining rows. avgPaymentTotal group1 group2 Interim result set

Processing the select with where TablenName: Invoices VendorIdPaymentTotalInvoiceTotal Step 3: Process the HAVING clause to possibly remove some rows from the result set (in this example no rows need to be removed) avgPaymentTotal group1 group2 Final results