Fundamental of Database Systems

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Structured Query Language Part I Chapter Three CIS 218.
Concepts of Database Management Sixth Edition
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
Structured Query Language(SQL) XU Yinqing SEEM PHD YEAR 3.
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:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
INLS 623– S QL Instructor: Jason Carter. SQL SELECT DISTINCT SELECT DISTINCT column_name, column_name FROM table_name ;
Sundara Ram Matta Apr 01 st, Sundara Ram Matta Apr 01 st, 2015
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,
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
Concepts of Database Management Seventh Edition
Concepts of Database Management Eighth Edition Chapter 3 The Relational Model 2: SQL.
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Copyright © 2004, Oracle. All rights reserved. Lecture 4: 1-Retrieving Data Using the SQL SELECT Statement 2-Restricting and Sorting Data Lecture 4: 1-Retrieving.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
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.
CHAPTER 9 SQL อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
IS6146 Databases for Management Information Systems Lecture 4: SQL IV – SQL Functions and Procedures 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.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Restricting and Sorting Data
Web Systems & Technologies
Module T03d Software Engineering
CHAPTER 7 DATABASE ACCESS THROUGH WEB
SQL Query Getting to the data ……..
More SQL: Complex Queries,
Rob Gleasure robgleasure.com
MySQL DML Commands By Prof. B.A.Khivsara
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Writing Basic SQL SELECT Statements
Basic select statement
Introduction to Structured Query Language(SQL)
Structured Query Language – The Basics
MySQL Joins MySQL joins are used to combine rows from two or more tables. Different SQL JOINs INNER JOIN: Returns all rows when there is at least one match.
Writing Basic SQL SELECT Statements
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Restricting and Sorting Data
Rob Gleasure robgleasure.com
SQL LANGUAGE and Relational Data Model TUTORIAL
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Structured Query Language
Exam 2 Exam 2 Study Guide is posted on the Course Site
CS4222 Principles of Database System
Lesson Plan Instructional Objective Learning Objective
M1G Introduction to Database Development
Query Functions.
CSC 453 Database Systems Lecture
SQL Tutorial w3schools.
Instructor Information: Mark Jamil
Shelly Cashman: Microsoft Access 2016
Restricting and Sorting Data
Introduction to SQL Server and the Structure Query Language
Presentation transcript:

Fundamental of Database Systems 1401312-3 By Dr Abdullah Alzahrani د. عبدالله الزهراني aahzahrani@uqu.edu.sa SQL Queries

Reference الكتاب المرجع Fundamentals of Database Systems, 5th ed., by Elmasri and Navathe, Pearson International Edition, 2007. http://dev.mysql.com/doc/ Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Outlines: SQL queries: Attribute Data Types Nulls 3-valued logic Select Ordering JOIN Aggregate functions Grouping Sub-queries Some of the materials and examples are taken from: http://www.w3schools.com/ and the reference book Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Attribute Data Types: Numeric: Character-string: includes integer numbers of various sizes (INTEGER or INT, and SMALLINT) and floating-point (real) numbers of various precision (FLOAT or REAL, and DOUBLE PRECISION). Formatted numbers can be declared by using DECIMAL(i,j)—or DEC(i,j) or NUMERIC(i,j)—where i, the precision, is the total number of decimal digits and j, the scale, is the number of digits after the decimal point. The default for scale is zero, and the default for precision is implementation- defined Character-string: either fixed length {CHAR(n) or CHARACTER(n)}, where n is the number of characters or varying length {VARCHAR(n) or CHAR VARYING(n) or CHARACTER VARYING(n)}, where n is the maximum number of characters. When specifying a literal string value, it is placed between single quotation marks (apostrophes), and it is case sensitive (a distinction is made between uppercase and lowercase). Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Attribute Data Types: Boolean: DATE TIME has the traditional values of TRUE or FALSE. In SQL, because of the presence of NULL values, a three-valued logic is used, so a third possible value for a Boolean data type is UNKNOWN. DATE data type has ten positions, and its components are YEAR, MONTH, and DAY in the form YYYY-MM-DD. Only valid dates and times should be allowed by the SQL implementation. This implies that months should be between 1 and 12 and dates must be between 1 and 31 TIME The TIME data type has at least eight positions, with the components HOUR,MINUTE, and SECOND in the form HH:MM:SS. Only valid dates and times should be allowed by the SQL implementation. Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Nulls: An important concept is that of NULL values, which are used to represent the values of attributes that may be unknown, do not exist, or may not apply to a tuple. A special value, called NULL, is used in these cases. For example, Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Three-Valued Logic (3-Valued ) SQL has various rules for dealing with NULL values. NULL is used to represent a missing value, but that it usually has one of three different interpretations value unknown(exists but is not known), value not available(exists but is purposely withheld), value not applicable(the attribute is undefined for this tuple). Consider the following examples to illustrate each of the meanings of NULL. Unknown value. A person’s date of birth is not known, so it is represented by NULL in the database. Unavailable or withheld value. A person has a home phone but does not want it to be listed, so it is withheld and represented as NULL in the database. Not applicable attribute. An attribute LastCollegeDegree would be NULL for a person who has no college degrees because it does not apply to that person. It is often not possible to determine which of the meanings is intended; for example, a NULL for the home phone of a person can have any of the three meanings. Hence, SQL does not distinguish between the different meanings of NULL. Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries SELECT is used to retrieve rows selected from one or more tables, and can include UNION statements and subqueries. The basic form of the SELECT statement, sometimes called a mapping or a select-from-where block, is formed of the three clauses SELECT, FROM, and WHERE and has the following form: SELECT <attribute list> FROM <table list> WHERE <condition> ; Where: <attribute list> is a list of attribute names whose values are to be retrieved by the query. <table list> is a list of the relation names required to process the query. <condition> is a conditional (Boolean) expression that identifies the tuples to be retrieved by the query. Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Customers" table: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 05023 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries SELECT Column Example SELECT * Example The following SQL statement selects the "CustomerName" and "City" columns from the "Customers" table: Example #1 SELECT CustomerName,City FROM Customers; SELECT * Example The following SQL statement selects all the columns from the "Customers" table: Example #2 SELECT * FROM Customers; Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Example #1 Results Example #2 Results CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 05023 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden Example #2 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries SELECT with WHERE Clause The WHERE clause is used to extract only those records that fulfil a specified criterion. SELECT with WHERE Clause (Text Fields) The following SQL statement selects all the customers from the country "Mexico", in the "Customers" table: Example #3 SELECT * FROM Customers WHERE Country='Mexico'; SELECT with WHERE Clause (Numeric Fields) SQL requires single quotes around text values (most database systems will also allow double quotes). However, numeric fields should not be enclosed in quotes: Example #4 SELECT * FROM Customers WHERE CustomerID=1; Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Example #3 Results Example #4 Results CustomerID CustomerName ContactName Address City PostalCode Country 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 05023 Example #4 Results CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries The AND & OR operators in SELECT with WHERE Clause The AND & OR operators are used to filter records based on more than one condition The AND operator displays a record if both the first condition AND the second condition are true. The OR operator displays a record if either the first condition OR the second condition is true. The following SQL statement selects all customers from the country "Germany" AND the city "Berlin", in the "Customers" table: Example #5 SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; The following SQL statement selects all customers from the city "Berlin" OR "'London", in the "Customers" table: Example #6 SELECT * FROM Customers WHERE City='Berlin‘ OR City='London'; Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Example #5 Results Example #6 Results CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany Example #6 Results CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa 9/20/2016 Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Operators with WHERE Clause examples <> not equal operator The following SQL statement selects all the customers from the any country EXCEPT "Mexico", in the "Customers" table: Example #W.1 SELECT * FROM Customers WHERE Country <> 'Mexico'; BETWEEN operator The following SQL statement selects all the customers whose ID numbers BETWEEN 3 and 4, in the "Customers" table: Example #W.2 SELECT * FROM Customers WHERE CustomerID BETWEEN 3 and 4; IN operator The following SQL statement selects all the customers whose ID numbers IN the set (“Mexico”, “Sweden”), in the "Customers" table: Example #W.3 SELECT * FROM Customers WHERE Country IN (“Mexico”, “Sweden”); Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Customers" table: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 05023 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Example #W.1 Results Example #W.2 Results CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden Example #W.2 Results CustomerID CustomerName ContactName Address City PostalCode Country 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK Example #W.3 Results CustomerID CustomerName ContactName Address City PostalCode Country 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 05023 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Operators with WHERE Clause examples LIKE operator Tip: The "%" sign is used to define wildcards (missing letters) both before and after the pattern. Example #W.4.1 The following SQL statement selects all customers with a PostalCode starting with the letters “WA” , in the "Customers" table: SELECT * FROM Customers WHERE PostalCode LIKE “WA%”; Example #W.4.2 The following SQL statement selects all customers with a ContactName ending with the letters “ardy” , in the "Customers" table: SELECT * FROM Customers WHERE ContactName LIKE “%ardy” ; Example #W.4.3 The following SQL statement selects all customers with a CustomerName containing “Moreno” , in the "Customers" table: SELECT * FROM Customers WHERECustomerName LIKE “%Moreno%” ; Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Example #W.4.1 Results Example #W.4.2 Results CustomerID CustomerName ContactName Address City PostalCode Country 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK Example #W.4.2 Results CustomerID CustomerName ContactName Address City PostalCode Country 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK Example #W.4.3 Results CustomerID CustomerName ContactName Address City PostalCode Country 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Ordering of Query Results SQL allows the user to order the tuples in the result of a query by the values of one or more of the attributes that appear in the query result, by using the ORDER BY clause. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword. General form when using ORDER BY SELECT column_name, column_name FROM table_name ORDER BY column_name ASC|DESC, column_name ASC|DESC; The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" column: Example #7 SELECT * FROM Customers ORDER BY Country; The following SQL statement selects all customers from the "Customers" table, sorted DESCENDING by the "Country" column: Example #8 SELECT * FROM Customers ORDER BY Country DESC; Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Example #7 Results Example #8 Results CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 5023 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK Example #8 Results CustomerID CustomerName ContactName Address City PostalCode Country 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 5023 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries JOIN An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN returns all rows from multiple tables where the join condition is met. The types of the different SQL JOINs you can use: 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 Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa 9/20/2016 Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of JOINS Common attribute Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Natural JOIN Examples of JOINS Example #9 select first_name,email,order_id, order_date, amount from customers c join orders on c.customer_id = orders.customer_id where c.customer_id = 3 Here, we’re joining the two tables using the join keyword, and specifying what key to use when joining the tables in the on customers.customer_id = orders.customer_id line following the join statement. Here is the result of the above SQL query, which includes two orders placed by Thomas Jefferson (customer_id = 3): Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of JOINS Example #9 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Inner JOIN Examples of JOINS Example #10 select first_name, last_name, order_date, amount from customers c inner join orders o on c.customer_id = o.customer_id Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of JOINS Example #10 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries LEFT JOIN Examples of JOINS Example #11 select first_name, last_name, order_date, amount from customers c left join orders o on c.customer_id = o.customer_id Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of JOINS Example #11 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries RIGHT JOIN Examples of JOINS Example #12 select first_name, last_name, order_date, amount from customers c right join orders o on c.customer_id = o.customer_id Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of JOINS Example #12 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries SQL Aggregate Functions SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions: AVG() - Returns the average value COUNT() - Returns the number of rows MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of SQL Aggregate Functions Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries SQL Aggregate Functions AVG() General form: Example #13 SELECT AVG(column_name) FROM table_name Example #13 The following SQL statement gets the average value of the “Amount" column from the “Orders" table: SELECT AVG(Amount) AS PriceAverage FROM Orders; Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of SQL Aggregate Functions Example #13 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries SQL Aggregate Functions COUNT() General form: SELECT COUNT(column_name) FROM table_name The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column SELECT COUNT(DISTINCT column_name) FROM table_name; SELECT COUNT(*) FROM table_name; The COUNT(*) function returns the number of records in a table Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries SQL Aggregate Functions COUNT() Example #14 Example #15 The following SQL statement counts the number of orders for "CustomerID"=3 from the "Orders" table: SELECT COUNT(Customer_ID) AS OrdersFromCustomerID3 FROM Orders WHERE Customer_ID=3; Example #15 The following SQL statement counts the total number of orders in the "Orders" table: SELECT COUNT(*) AS NumberOfOrders FROM Orders; Example #16 The following SQL statement counts the number of unique customers in the "Orders" table SELECT COUNT(DISTINCT Customer_ID) AS NumberOfCustomers FROM Orders; Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of SQL Aggregate Functions IMPORTANT NOTE: The DISTINCT keyword can be used to return only distinct (different) values. Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of SQL Aggregate Functions Example #14 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of SQL Aggregate Functions Example #15 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries SQL Aggregate Functions MAX() MIN() SUM() General form: SELECT MAX(column_name) FROM table_name; MIN() SELECT MIN(column_name) FROM table_name; SUM() SELECT SUM(column_name) FROM table_name; Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries SQL Aggregate Functions MAX() MIN() SUM() Example #17 The following SQL statement gets the Largest value of the “amount" column from the " orders" table: SELECT MAX(amount) AS LargestOrderPrice FROM orders; MIN() Example #18 The following SQL statement gets the smallest value of the “amount" column from the " orders" table: SELECT MIN(amount) AS SmallestOrderPrice FROM orders; SUM() Example #19 The following SQL statement gets the total value of the “amount" column from the " orders" table: SELECT SUM(amount) AS Total FROM orders; Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of SQL Aggregate Functions Example #17 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of SQL Aggregate Functions Example #19 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Grouping The GROUP BY statement is used in conjunction with the aggregate functions to group the resultset by one or more columns. To subgroups tuples in a relation, where the subgroups are based on some attribute values. For example, we may want to find the average salary of employees in each department or the number of employees who work on each department . Each group (partition) will consist of the tuples that have the same value of some attribute(s), called the grouping attribute(s). The GROUP BY clause specifies the grouping attributes, which should also appear in the SELECT clause, so that the value resulting from applying each aggregate function to a group of tuples appears along with the value of the grouping attribute(s). General form SELECT [column_names], aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name ORDER BY column_name; Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of Grouping Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Required Action (Query): Examples of Grouping Example #20 Required Action (Query): From orders table, retrieve the customer ID for each customer, and the sum amount of their orders. SELECT customer_id,SUM(amount) AS Total FROM orders group by customer_id; Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Orders table Examples of Grouping Example #20 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Sub-queries A subquery is a SELECT statement within another statement. Here is an example of a subquery: SELECT * FROM table1 WHERE column1 = (SELECT column1 FROM table1 ); In this example, SELECT * FROM t1 ... is the outer query (or outer statement), and (SELECT column1 FROM t2) is the subquery The main advantages of subqueries are: They allow structured queries so that it is possible to isolate each part of a statement. They provide alternative ways to perform operations that would otherwise require complex joins and unions. Subqueries more readable than complex joins or unions. Example #21 The following SQL statement selects the " customer_id " and " amount " records that have an above average amount : SELECT customer_id, amount FROM orders WHERE amount>(SELECT AVG(amount) FROM orders); Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of Sub-queries Outer Query Sub-Query Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

SQL Queries Examples of Sub-queries Example #21 Results Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa Fundamental of Database Systems 1401312-3 9/20/2016

End SQL Queries Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa 9/20/2016 Fundamental of Database Systems 1401312-3 9/20/2016