SQL SELECT Query: Intermediate

Similar documents
Database Query 1: SQL Basics

Oracle SQL. Course Summary. Duration. Objectives

In-Depth Guide Advanced Database Concepts

Joining Tables in Queries

Oracle Database: SQL and PL/SQL Fundamentals

Relational Database: Additional Operations on Relations; SQL

Using AND in a Query: Step 1: Open Query Design

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals

Introduction to Microsoft Jet SQL

Access Queries (Office 2003)

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

MOC 20461C: Querying Microsoft SQL Server. Course Overview

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

T-SQL STANDARD ELEMENTS

Oracle Database 12c: Introduction to SQL Ed 1.1

Programming with SQL

1 Structured Query Language: Again. 2 Joining Tables

ICAB4136B Use structured query language to create database structures and manipulate data

Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu

Oracle Database 10g: Introduction to SQL

Introduction to Querying & Reporting with SQL Server

A basic create statement for a simple student table would look like the following.

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Information Systems SQL. Nikolaj Popov

Advanced Query for Query Developers

Financial Data Access with SQL, Excel & VBA

Oracle Application Express - Application Migration Workshop

Instant SQL Programming

SQL Server 2008 Core Skills. Gary Young 2011

Essentials of SQL. Essential SQL 11/06/2010. NWeHealth, The University of Manchester

Course 20461C: Querying Microsoft SQL Server Duration: 35 hours

Introducing Microsoft SQL Server 2012 Getting Started with SQL Server Management Studio

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Microsoft Access 3: Understanding and Creating Queries

Querying Microsoft SQL Server

Beginning C# 5.0. Databases. Vidya Vrat Agarwal. Second Edition

Lab # 5. Retreiving Data from Multiple Tables. Eng. Alaa O Shama

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

4. SQL. Contents. Example Database. CUSTOMERS(FName, LName, CAddress, Account) PRODUCTS(Prodname, Category) SUPPLIERS(SName, SAddress, Chain)

QWT Business Intelligence Project Plan

RDBMS Using Oracle. Lecture Week 7 Introduction to Oracle 9i SQL Last Lecture. kamran.munir@gmail.com. Joining Tables

Querying Microsoft SQL Server 2012

Querying Microsoft SQL Server 2012

Chapter 1 Overview of the SQL Procedure

Course ID#: W 35 Hrs. Course Content

Course 10774A: Querying Microsoft SQL Server 2012

Course 10774A: Querying Microsoft SQL Server 2012 Length: 5 Days Published: May 25, 2012 Language(s): English Audience(s): IT Professionals

Querying Microsoft SQL Server 20461C; 5 days

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

Business Intelligence. 11. SSIS, ETL January 2014.

Oracle Database: SQL and PL/SQL Fundamentals NEW

Handling Missing Values in the SQL Procedure

Performing Queries Using PROC SQL (1)

Effective Use of SQL in SAS Programming

Boats bid bname color 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red. Figure 1: Instances of Sailors, Boats and Reserves

3.GETTING STARTED WITH ORACLE8i

MOC QUERYING MICROSOFT SQL SERVER

How to use MySQL Workbench and other development tools

SQL Query Performance Tuning: Tips and Best Practices

Chapter 5. SQL: Queries, Constraints, Triggers

Displaying Data from Multiple Tables

Advance DBMS. Structured Query Language (SQL)

Relational Database Basics Review

Examine the structure of the EMPLOYEES table: EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25)

MySQL for Beginners Ed 3

Structured Query Language (SQL)

Querying Microsoft SQL Server (20461) H8N61S

Talking to Databases: SQL for Designers

Querying Microsoft SQL Server Course M Day(s) 30:00 Hours

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

DBMS / Business Intelligence, SQL Server

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query


Where? Originating Table Employees Departments

WRITING EFFICIENT SQL. By Selene Bainum

David M. Kroenke and David J. Auer Database Processing: Fundamentals, Design and Implementation

SQL. Short introduction

Guide to Performance and Tuning: Query Performance and Sampled Selectivity

SQL Programming. Student Workbook

Oracle Database 11g SQL

Developing Web Applications for Microsoft SQL Server Databases - What you need to know

Example Instances. SQL: Queries, Programming, Triggers. Conceptual Evaluation Strategy. Basic SQL Query. A Note on Range Variables

SQL: Queries, Programming, Triggers

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Oracle Database: Introduction to SQL

SQL: Queries, Programming, Triggers

PSU SQL: Introduction. SQL: Introduction. Relational Databases. Activity 1 Examining Tables and Diagrams

Saskatoon Business College Corporate Training Centre

SQL Server. 1. What is RDBMS?

Ad Hoc Advanced Table of Contents

Building Queries in Microsoft Access 2007

Discovering SQL. Wiley Publishing, Inc. A HANDS-ON GUIDE FOR BEGINNERS. Alex Kriegel WILEY

Oracle Database: Introduction to SQL

Querying Microsoft SQL Server 2012

CHAPTER 12. SQL Joins. Exam Objectives

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan

Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008

Transcription:

SQL SELECT Query: Intermediate IT 4153 Advanced Database J.G. Zheng Spring 2012

Overview SQL Select Expression Alias revisit Aggregate functions - complete Table join - complete Sub-query in where Limiting results: TOP, DISTINCT All examples can be used with the Northwind database 2

1. Expression Expression is a combination of symbols and operators that returns a single value An expression can be a single constant, variable, column, or scalar function 10 3.14 'John Doe' '10/10/2010' CompanyName GetDate() columns, numbers, literals, functions connected by operators 10*3+3 'John' + 'Doe' Address + ', ' + City + ', ' + ZipCode Quantity * SalePrice 1.2 * ListPrice 3

SQL Operators Comparison operators >, <, >=, <=, <>,!=, = LIKE, IN, BETWEEN AND, IS (NULL) Logical operators AND, OR, NOT Arithmetic operators +, -, *, /, % Concantenation + T-SQL Reference http://msdn.microsoft.com/en-us/library/ms174986.aspx 4

Expressions used as Columns Expressions can be used as derived columns Examples A text constant which will be the same for every record SELECT CompanyName, 'Supplier' as Type FROM Suppliers; SELECT ProductName, UnitPrice*1.2 AS 'New Price' FROM Products; String concatenation SELECT FirstName+' '+LastName FROM Employees; SELECT UPPER(ProductName) FROM Products; SELECT GETDATE(); A system function not related to any table. 5

Expressions used for Comparison Expressions can be used in the WHERE clause Examples SELECT * from Products WHERE UnitsInStock-ReorderLevel<0; SELECT * FROM Products WHERE UnitsInStock + UnitsOnOrder < ReorderLevel; SELECT ProductName, UnitPrice * 1.1 AS Discount FROM Products WHERE UnitPrice * 1.1 >= 20 Comparison between columns 6

2. Alias Column alias: representing derived and constant columns SELECT CategoryID, AVG(UnitPrice) Price FROM Products GROUP BY CategoryID ORDER BY Price; SELECT ProductName, UnitPrice * 0.9 Discount FROM Products WHERE UnitPrice * 0.9 > 20; Column alias can be used in ORDER BY Column alias can NOT be used in WHERE or HAVING clause (SQL Server) Table alias: commonly used in table joins and sub-queries SELECT ProductName, CategoryName FROM Products AS p, Categories c Where p.categoryid = c.categoryid AS is optional. If an alias is assigned, it must be used instead of the original table name 7

Alias Symbol Column alias: use [ ] or ' ' SELECT ProductName, UnitPrice * 0.9 AS 'Discount Price' FROM Products ORDER BY 'Discount Price'; SELECT ProductName, UnitPrice * 0.9 AS [Discount Price] FROM Products ORDER BY [Discount Price]; Table alias: use [ ] SELECT ProductName, CategoryName FROM Products AS [table p], Categories c Where [table p].categoryid = c.categoryid 8

3. Aggregate Functions Using aggregate functions for row calculation MIN (minimum of all or selected values) MAX (maximum of all or selected values) COUNT (number of all or selected rows) AVG (average of all or selected values) SUM (sum of all or selected values) 2.1 Calculation for all or selected rows SELECT COUNT(ProductID) AS NumberOfProducts FROM Products; SELECT AVG(UnitPrice) AS 'Average Price for Category 1' FROM Products WHERE CategoryId = 1; This criterion limits the records to be averaged. 9

Expression in Aggregation Expressions can be used with aggregate functions Example What is the total payment for each line item? SELECT SUM(UnitPrice * Quantity) AS LineItemTotal FROM [Order Details]; 10

Grouping GROUP BY: aggregation with groups To get aggregation results for different groups of records Example What is the average unit price of products in each category? SELECT CategoryID, AVG(UnitPrice) FROM Products GROUP BY CategoryID; 11

Limitations of GROUP BY Columns or expressions (except the aggregate function) can be in the SELECT clause only if they are in the GROUP BY clause. Good! Country is in the GROUP BY clause SELECT Country, Region, COUNT(CustomerId) FROM Customers GROUP BY Country WRONG! Region is not in the GROUP BY clause 12

Sorting Aggregation Result You can sort by the aggregation results Example: what is the average unit price of products in each category? Sort by the average unit price SELECT CategoryID, AVG(UnitPrice) FROM Products GROUP BY CategoryID ORDER BY AVG(UnitPrice) Using aggregate function SELECT CategoryID, AVG(UnitPrice) AS Price FROM Products GROUP BY CategoryID Using alias. ORDER BY Price SELECT CategoryID, AVG(UnitPrice) AS Price FROM Products GROUP BY CategoryID ORDER BY 2 Using column index 13

Filtering Aggregation Result Use HAVING clause to filter aggregation result (after aggregation) What is the average unit price of products in each category? Only return those with an average price greater than 10. Important: aggregate functions cannot be used in WHERE clause! SELECT CategoryID, AVG(UnitPrice) FROM Products GROUP BY CategoryID Having AVG(UnitPrice) > 10; Use WHERE clause to filter records to be aggregated (before aggregation) What is the average unit price of products whose unit price is greater than 10? SELECT CategoryID, AVG(UnitPrice) FROM Products WHERE UnitPrice > 10 GROUP BY CategoryID; This is wrong: SELECT CategoryID, AVG(UnitPrice) FROM Products WHERE AVG(UnitPrice) > 10 GROUP BY CategoryID 14

4. Table Join How do rows match from different tables? Cross Join: no need to match. Inner Join: use the foreign key constraint as the matching criteria Inner join (equal join) Only include records that have matching records (based on PK/FK pair) from two tables (either direction) Records that do not have matching ones in the other table are not included in the results. Outer join (usually needed when minimum cardinality is optional on a table) Left join: include all qualified records from the left table in the join condition even if they do not have matching records in the right table. Right join: include all qualified records from the right table in the join condition even if they do not have matching records in the left table. Full join: include all qualified records from both tables in the join condition 15

Table Join Effect - Cross Join Product Category A 1 B 2 FK Join Category Name 1 Canned 2 Drink 3 Fresh Product Category A A A B B Canned Drink Fresh Canned Drink B Fresh Cross Join: no row matching Product A B Category Canned Drink Inner Join: row matching based on foreign key 16

Table Join Effect - Outer Join Product CategoryId A 1 B 2 C CategoryId Name 1 Canned 2 Drink 3 Fresh Product A B Category Canned Drink Inner join Product A B C Category Canned Drink (Null) Left Join Product A B C (Null) Category Canned Drink (Null) Fresh Full Join Product A B (Null) Category Canned Drink Fresh Right Join 17

Equal Join Syntax What is the category name for each product? SELECT ProductName, CategoryName FROM Products, Categories Where Products.CategoryID = Categories.CategoryID AND Discontinued = 0; VS. SELECT ProductName, CategoryName FROM Products INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID WHERE Discontinued = 0; 1. Joining/matching criteria: very important, don t forget! 2. Table.Cloumn format is used to avoid ambiguity. 18

Outer Join Example Get customers and their orders; also include customers who have never placed an order SELECT CompanyName, OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY OrderID Execution result The first two rows will not be included for an inner join. 19

5. Sub-Query Use the output of a SELECT query (sub-query, or inner query) as an input for another SELECT query SELECT * FROM Products WHERE CategoryId = (SELECT CategoryId FROM Categories WHERE CategoryName = 'Seafood'); SELECT * FROM Products WHERE CategoryId IN (SELECT CategoryId FROM Categories WHERE CategoryName IN ('Seafood','Beverages','Produce')); The sub query returns a single value (scalar value); use = The sub query returns a list of values; use IN 20

Sub-Query and Table Join In the previous cases these statements can also be re-written as table joins SELECT * FROM Products, Categories WHERE Products.CategoryId = Categories.CategoryId AND CategoryName = 'Seafood'; SELECT * FROM Products, Categories WHERE Products.CategoryId = Categories.CategoryId AND CategoryName IN ('Seafood','Beverages','Produce'); 21

Sub-Queries for Comparison Sub-queries can be used with other comparison operators >, <, >=, <=, etc. SELECT * FROM Products The sub query returns a single value (scalar value) WHERE UnitPrice > (SELECT AVG(UnitPrice) FROM Products); In these cases, there is no equivalent table join format 22

TOP Use the keyword TOP to limit the number of rows returned (SQL Server) Example Only returns 10 records. SELECT TOP 10 * FROM Customers; SELECT TOP 5 PERCENT * FROM Customers; WITH TIES Only returns 5% of the total records in the original results. Include records whose value is tied with the last record SELECT TOP 9 with ties * from Products order by UnitPrice Returns 10 records as the last two are the same price. 23

Uniqueness Use the keyword DISTINCT to eliminate duplicate rows in the results In Oracle, "unique" also works Example SELECT DISTINCT Country from Customers ORDER BY country; SELECT Count(DISTINCT Country) FROM Customers Without DISTINCT, it returns 91 rows; with DISTINCT, it returns only 21 rows. DISTINCT can be used with aggregate functions. Without DISTINCT, the result is 91; with DISTINCT, the result is 21. SELECT * FROM Suppliers WHERE SupplierId IN (SELECT DISTINCT SupplierId from Products WHERE CategoryId = 1) 24

Summary Key concepts Expression Alias Aggregate function Join, cross join, inner join, outer join, left join, right join, full join Sub-query Key skills Write SQL SELECT statement to retrieve desired data Know the result of a given SQL SELECT statement 25

More SQL Query Resources W3Schools SQL Tutorial http://www.w3schools.com/sql/ SQL Course http://sqlcourse2.com/ A gentle introduction to SQL http://sqlzoo.net/ Other http://www.youtube.com/watch?v=rpp28u_k9lk http://www.1keydata.com/sql 26