SQL – Logical Operators and aggregation Chapter 3.2 V3.0 Napier University Dr Gordon Russell.

Slides:



Advertisements
Similar presentations
Sorting Rows. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Construct a query to sort a results set in ascending.
Advertisements

1 Quick recap of the SQL & the GUI way in Management Studio The Adwentureworks database from the book A script to create tables & insert data for the Amazon.
SQL - Subqueries and Schema Chapter 3.4 V3.0 Napier University Dr Gordon Russell.
SQL – Simple Queries Chapter 3.1 V3.0 Napier University Dr Gordon Russell.
SQL – JOINs and VIEWs Chapter 3.3 V3.0 Napier University Dr Gordon Russell.
CSC271 Database Systems Lecture # 11.
SQL CSET 3300.
CS411 Database Systems Kazuhiro Minami 06: SQL. Join Expressions.
Chapter 11 Group Functions
© 2002 by Prentice Hall 1 David M. Kroenke Database Processing Eighth Edition Chapter 9 Structured Query Language.
Introduction to Oracle9i: SQL1 SQL Group Functions.
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #3.
Structured Query Language Part I Chapter Three CIS 218.
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 Operations Aggregate Functions Having Clause Database Access Layer A2 Teacher Up skilling LECTURE 5.
Logical Operators Operator AND OR NOT Meaning Returns TRUE if both component conditions are TRUE Returns TRUE if either component condition is TRUE Returns.
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Download three SQL script files from wiki page.
Slide 1 Chapter 2 Introduction to Structured Query Language (SQL) ‏
Chapter 6 Group Functions. Chapter Objectives  Differentiate between single-row and multiple-row functions  Use the SUM and AVG functions for numeric.
Chapter 3 Single-Table Queries
SQL Unit 5 Aggregation, GROUP BY, and HAVING Kirk Scott 1.
INLS 623– S QL Instructor: Jason Carter. SQL SELECT DISTINCT SELECT DISTINCT column_name, column_name FROM table_name ;
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Instructor: Jinze Liu Fall Basic Components (2) Relational Database Web-Interface Done before mid-term Must-Have Components (2) Security: access.
DATABASE TRANSACTION. Transaction It is a logical unit of work that must succeed or fail in its entirety. A transaction is an atomic operation which may.
Structured Query Language. Group Functions What are group functions ? Group Functions Group functions operate on sets of rows to give one result per group.
Information Resource Engineering SQL4. Recap - Ordering Output  Usually, the order of rows returned in a query result is undefined.  The ORDER BY clause.
SQL queries ordering and grouping and joins
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Select your database – Your database name is.
SQL-5 (Group By.. Having). Group By  Need: To apply the aggregate functions to subgroups of tuples in a relation, where the subgroups are based on some.
Copyright © Curt Hill Queries in SQL More options.
Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
1 CSCE Database Systems Anxiao (Andrew) Jiang The Database Language SQL.
SQL Aggregation Oracle and ANSI Standard SQL Lecture 9.
CS 405G: Introduction to Database Systems Instructor: Jinze Liu Fall 2009.
SCUHolliday - coen 1787–1 Schedule Today: u Subqueries, Grouping and Aggregation. u Read Sections Next u Modifications, Schemas, Views. u Read.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Agenda for Class - 03/04/2014 Answer questions about HW#5 and HW#6 Review query syntax. Discuss group functions and summary output with the GROUP BY statement.
MIS2502: Data Analytics SQL – Getting Information Out of a Database.
Sorting data and Other selection Techniques Ordering data results Allows us to view our data in a more meaningful way. Rather than just a list of raw.
Aggregating Data Using Group Functions. What Are Group Functions? Group functions operate on sets of rows to give one result per group.
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.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Structured Query Language SQL-II IST 210 Organization of Data IST2101.
Database Design lecture 3_2 Slide 1 Database Design Lecture 3_2 Data Manipulation in SQL Simple SQL queries References: Text Chapter 8 Oracle SQL Manual.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Relational Databases Today we will look at: Different ways of searching a database Creating queries Aggregate Queries More complex queries involving different.
CS 440 Database Management Systems
CS3220 Web and Internet Programming More SQL
CS580 Advanced Database Topics
The Database Exercises Fall, 2009.
CS 440 Database Management Systems
MENAMPILKAN DATA DARI SATU TABEL (Chap 2)
GROUP BY & Subset Data Analysis
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
SQL – Entire Select.
Chapter 4 Summary Query.
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Access: SQL Participation Project
Structured Query Language
Access: Queries III Participation Project
Section 4 - Sorting/Functions
Presentation transcript:

SQL – Logical Operators and aggregation Chapter 3.2 V3.0 Napier University Dr Gordon Russell

Logical Operators Combining rules in a single WHERE clause would be useful AND and OR allow us to do this NOT also allows us to modify rule behaviour When these are combined together, problems in rule ordering can occur. This is solved using parentheses.

AND AND combines rules together so that they ALL must be true. Lets revisit the CAR table: REGNOMAKECOLOURPRICEOWNER F611 AAAFORDRED12000Jim Smith J111 BBBSKODABLUE11000Jim Smith A155 BDEMERCEDESBLUE22000Bob Smith K555 GHTFIATGREEN6000Bob Jones SC04 BFESMARTBLUE13000

SELECT regno from car where colour = ‘ BLUE ’ WHERE regno LIKE ‘ %5 ’ REGNO J111 BBB A155 BDE SC04 BFE REGNO A155 BDE K555 GHT

SELECT regno from car WHERE colour = ‘ BLUE ’ and regno LIKE ‘ %5% ’ ; REGNO A155 BDE

Multiple AND rules You can have as many rules as you like ANDed together. For example: SELECT regno FROM car WHERE colour = ‘ BLUE ’ AND regno like ‘ %5% ’ AND owner like ‘ Bob % ’ ;

OR OR is like ‘ either ’. So long as one of the rules is true then the filter is true. Looks for cars which are EITHER red or blue … SELECT regno,colour from CAR WHERE colour = ‘ RED ’ OR colour = ‘ BLUE ’ REGNOCOLOUR F611 AAARED J111 BBBBLUE A155 BDEBLUE SC04 BFEBLUE

NOT NOT inverts the rule it is put in front of: WHERE colour = ‘ RED ’ This could be inverted as: –WHERE colour != ‘ RED ’ –WHERE NOT colour = ‘ RED ’ NOT is not really useful in this example, but comes into its own in more complex rulesets.

Precedence Precedence is the order in which the rules are evaluated and combined together. It is NOT in the order they are written. Rules are combined together firstly at AND, then OR, and finally at NOT. Consider : Car has a 5 in reg and is either red or blue. SELECT regno,colour from car WHERE colour = ‘ RED ’ -- Line 1 OR colour = ‘ BLUE ’ -- Line 2 AND regno LIKE ‘ %5% ’ -- Line 3

Brackets Rewrite as: SELECT regno,colour from car WHERE (colour = ‘ RED ’ OR colour = ‘ BLUE ’ ) AND regno LIKE ‘ %5% ’ Might be clearer as: SELECT regno,colour from car WHERE ( colour = ‘ RED ’ OR colour = ‘ BLUE ’ ) AND regno LIKE ‘ %5% ’

DISTINCT Find all the colours used in cars. SELECT colour from car; COLOUR RED BLUE GREEN BLUE

DISTINCT SELECT DISTINCT colour from car; COLOUR RED BLUE GREEN

ORDER BY It would be nice to be able to order the output using a sort. SELECT make from car; MAKE FORD SKODA MERCEDES FIAT SMART

ASCending order Sort by alphabetical or numeric order: ASC ORDER BY … ASC is the default. SELECT make from car ORDER BY make; MAKE FORD FIAT MERCEDES SKODA SMART

DESCending order Sort by reverse alphabetical or numeric order: DESC ORDER BY … DESC must be selected. SELECT make from car ORDER BY make DESC; MAKE SMART SKODA MERCEDES FIAT FORD

Multi Column Sort ORDER BY can take multiple columns. SELECT make,colour FROM car ORDER BY colour,make; MAKECOLOUR SKODABLUE SMARTBLUE MERCEDESBLUE FIATGREEN FORDRED

IN When you have a list of OR, all on the same attribute, then IN could be a simpler way: Rather Than: SELECT regno,make FROM car WHERE make = ‘ SKODA ’ or make = ‘ SMART ’ Have SELECT regno,make FROM car WHERE make in ( ‘ SKODA ’, ’ SMART ’ );

Aggregate Functions Aggregate functions allow you to write queries to produce statistics on the data in the database. These functions are sometimes also called SET functions. These include: –AVG (calculate the average) –SUM –MAX –MIN –COUNT

AVERAGE SELECT price FROM car; SELECT avg(price) FROM car; PRICE AVG(PRICE) 12800

SUM Add up all the values in a column SELECT sum(price) FROM car; SUM(PRICE) 64000

MAX What is the maximum value in a column SELECT max(price) FROM car; MIN(PRICE) 22000

MIN What is the minimum value in a column SELECT min(price) FROM car; MIN(PRICE) 22000

COUNT How many rows make up a column SELECT count(price) FROM car; COUNT(PRICE) 5 Count(*) is similar, but also counts when price is NULL. SELECT count(*) FROM car;

COUNT DISTINCT Sometimes you do not want to count how many rows are in a column, but how many different values could be found in that column. There is a special variant of count which does this: SELECT count(colour) from car; SELECT count(DISTINCT colour) from car; COUNT(PRICE) 5 3

GROUP BY Aggregation functions so far have only been shown in queries with only the single aggregation function on the select line. You can combine functions and non-functions on the select line. To do this you need GROUP BY. Question: What is the most expensive car for each colour. Intuitively the following seems right, but will not execute! SELECT colour,max(price) FROM car;

SELECT colour,price FROM car; SELECT colour,max(price) FROM car GROUP BY colour; COLOURPRICE RED12000 BLUE11000 BLUE22000 GREEN6000 BLUE13000 COLOURPRICE RED12000 BLUE22000 GREEN6000

HAVING WHILE allows rules for each row. HAVING allows rules for each group of a GROUP BY. Consider the problem “ Who has more than 1 car ”. We would like to say: SELECT owner from car where count(owner) > 1 Aggregate functions are not allowed in WHERE. They are allowed in HAVING.

SELECT owner,count(regno) FROM car GROUP BY owner HAVING count(regno) > 1 OR SELECT owner FROM car GROUP BY owner HAVING count(regno) > 1 count(*) works just as well in this case.