Advanced SQL SMSU Computer Services Short Course.

Slides:



Advertisements
Similar presentations
Advanced SQL (part 1) CS263 Lecture 7.
Advertisements

© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Chapter 4 Joining Multiple Tables
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
SQL Subqueries Objectives of the Lecture : To consider the general nature of subqueries. To consider simple versus correlated subqueries. To consider the.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
1 Creating and Tweaking Data HRP223 – 2010 October 24, 2011 Copyright © Leland Stanford Junior University. All rights reserved. Warning: This.
Introduction to SQL Session 2 Retrieving Data From Multiple Tables.
Introduction to Oracle9i: SQL1 Subqueries. Introduction to Oracle9i: SQL2 Chapter Objectives Determine when it is appropriate to use a subquery Identify.
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
Database Systems More SQL Database Design -- More SQL1.
Concepts of Database Management Sixth Edition
Introduction to Databases Chapter 7: Data Access and Manipulation.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
IFS180 Intro. to Data Management Chapter 9 – Outer Joins.
Decision Structures and Boolean Logic
Analyzing Data For Effective Decision Making Chapter 3.
Chapter 9 Joining Data from Multiple Tables
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
1 ICS 184: Introduction to Data Management Lecture Note 10 SQL as a Query Language (Cont.)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM. 5.1 © Copyright IBM Corporation 2008 DB2 9 Fundamentals.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
Query Developer User Group March 15, Tips and Techniques Cutting and pasting SQL between QM, Excel, and Access Filtering the list of tables in Excel.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
Chapter 4Introduction to Oracle9i: SQL1 Chapter 4 Joining Multiple Tables.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Chapter 12 Subqueries and Merge Statements
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
Thinking in Sets and SQL Query Logical Processing.
Quiz Which of the following is not a mandatory characteristic of a relation? Rows are not ordered (Not required) Each row is a unique There is a.
Chapter 7 Subqueries. Chapter Objectives  Determine when it is appropriate to use a subquery  Identify which clauses can contain subqueries  Distinguish.
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
IFS180 Intro. to Data Management Chapter 10 - Unions.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
More SQL: Complex Queries,
MySQL Subquery Source: Dev.MySql.com
Writing Basic SQL SELECT Statements
Chapter 12 Subqueries and MERGE Oracle 10g: SQL
Aggregating Data Using Group Functions
Subqueries Schedule: Timing Topic 25 minutes Lecture
Database Systems: Design, Implementation, and Management Tenth Edition
Topics The if Statement The if-else Statement Comparing Strings
Using Subqueries to Solve Queries
Aggregating Data Using Group Functions
(SQL) Aggregating Data Using Group Functions
David M. Kroenke and David J
Topics The if Statement The if-else Statement Comparing Strings
JOINS (Joinining multiple tables)
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Aggregating Data Using Group Functions
SQL Fundamentals in Three Hours
Using Subqueries to Solve Queries
Lab 2 HRP223 – 2010 October 18, 2010 Copyright © Leland Stanford Junior University. All rights reserved. Warning: This presentation is protected.
Chapter 8 Advanced SQL.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Using Subqueries to Solve Queries
Database Systems: Design, Implementation, and Management Tenth Edition
Using Subqueries to Solve Queries
Subqueries Schedule: Timing Topic 25 minutes Lecture
JOINS (Joinining multiple tables)
Presentation transcript:

Advanced SQL SMSU Computer Services Short Course

2 Contact Information Greg Snider – MIS Database Analyst Ext – SGS345B Don’t hesitate to or call if you have any questions after you start using QM and SQL.

3 Agenda SQL Limits FETCH FIRST n ROWS ONLY Quantified predicates Named expressions Scalar Subselect

4 Agenda Case Multiple Join Types Common Table Expressions In-line Views/Table Expressions/Nested Table Expressions / Derived Tables

5 SQL Limits SQL statements can now be 65, 535 characters long 256 tables can be referenced in a single SQL statement Approximately 8000 elements in a SELECT list

6 FETCH FIRST n ROWS ONLY Sets the maximum number of rows to be returned Follows the ORDER BY clause if it is present If the ORDER BY clause is present, then the FETCH FIRST operation is performed on the sorted data

7 FETCH FIRST n ROWS ONLY Example

8 FETCH FIRST n ROWS ONLY Example Results

9 Quantified Predicates Compares a value with a set of values Expression [=, <>,, =] [Some, Any, All] (subselect)

10 Quantified Predicates Expression > ALL (subselect) –The predicate is true if the expression is greater than each individual value returned by the subselect. If the subselect returns no values, the predicate is true. The result is false if the specified relationship is false for at least one value. –The <> All predicate is equivalent to the NOT IN predicate.

11 Quantified Predicates Expression > ANY (subselect –The predicate is true if the expression is greater than at least on of the values returned by the subselect. If the subselect returns no values, the predicate is false. The = ANY quantified operator is equivalent to the IN predicate SOME is synonymous with ANY

12 Named Expressions The AS clause lets you assign a meaningful name to an expression, which makes it easier to refer back to that expression. SELECT YEAR(CURRENT DATE) – BIRTH_DATE) AS AGE The named column cannot be used in a WHERE clause The named column can be used in a ORDER BY clause or GROUP BY clause

13 Named Expressions

14 Named Expressions

15 Scalar Subselect A scalar subselect is a subselect, enclosed in parentheses, placed in the SELECT list that returns a single result row and a single result column. If the result of the subselect is no rows, then the null value is returned. An error is returned if there is more than one row in the result.

16 Scalar Subselect Example

17 Scalar Subselect Example – Results

18 CASE The CASE expression can be used to easily manipulate the data in a column –It can be used to change codes in to meaningful words –It can be used to protect against exceptions such as division by zero

19 CASE Syntax

20 CASE Example 1

21 CASE Example 2

22 CASE Example 3

23 Can I use more than one column in a CASE expression? Yes, any number of WHEN conditions can be used in the CASE expression, and each WHEN can reference a different column or expression. CASE ( WHEN COL7 > 15 THEN COL7 *.0133 WHEN COL3 = 34 THEN COL3 /.0133 WHEN COL8 < 98 THEN 999 ELSE NULL END) AS MULTICALC

24 Where can I use CASE expressions? Anywhere an expression is allowed in a SQL statement SELECT clause WHERE clause HAVING clause Built-in Function IN (list)

25 Can I use a subselect inside a CASE expression?

26 CASE Subselect Results

27 Can I use an IN list in a CASE expression?

28 CASE Example 4

29 CASE Example 4 Results

30 CASE Example 5 (join ORing) SELECT columns FROM T1, T2 WHERE (CASE WHEN T1.ID1 IS NULL THEN T1.ID2 END) = T2.COLX

31 CASE Example 6 (table pivoting) The table looks like this: SALES_DATESALES_PERSONREGIONSALES 01/10/2004WilliamsSouth5 01/11/2004SmithEast6 02/24/2004JonesWest4 03/31/2004WilliamsSouth3

32 CASE Example 6

33 CASE Example 6 – Results

34 Multiple Join types Inner Join Left Outer Join Right Outer Join Left Exception Join Right Exception Join Full Outer Join

35 Inner Join An Inner Join returns only the rows from each table that have matching values in the join columns. Any rows that do not have a match between the tables will not appear in the result table. This is the join you’re used to using. FROM T1 INNER JOIN T2 ON T1.COLA = T2.COL1

36 Left Outer Join A Left Outer Join returns values for all of the rows from the first table (the table on the left) and the values from the second table for the rows that match. Any rows that do not have a match in the second table will return the null value for all columns from the second table. FROM T1 LEFT OUTER JOIN T2 ON T1.COLA = T2.COL1

37 Left Outer Join – Example List students and the classes they are taking, if any.

38 Left Outer Join – Example

39 Left Outer Join – Results

40 Right Outer Join A Right Outer Join return values for all of the rows from the second table (the table on the right) and the values from the first table for the rows that match. Any rows that do not have a match in the first table will return the null value for all columns from the first table. FROM T1 RIGHT OUTER JOIN T2 ON T1.COLA = T2.COL1

41 Left Exception Join A Left Exception Join returns only the rows from the left table that do not have a match in the right table. Columns in the result table that come from the right table have the null value. FROM T1 LEFT EXCEPTION JOIN T2 ON T1.COLA = T2.COL1

42 Left Exception Join – Example List students who are not taking classes

43 Left Exception Join – Example

44 Left Exception Join – Results

45 Right Exception Join A Right Exception Join returns only the rows from the right table that do not have a match in the left table. Columns in the result table that come from the left table have the null value. FROM T1 RIGHT EXCEPTION JOIN T2 ON T1.COLA = T2.COL1

46 Full Outer Join The Full Outer Join includes the inner join (the rows that match) and the rows from both the left and right tables that do not match. The Full Outer Join is not included in this version of SQL, but it can be simulated. You simulate a Full Outer Join by using a Left Outer Join union’ed with a Right Exception Join

47 Full Outer Join – Example

48 Full Outer Join – Results

49 Full Outer Join - Results

50 How to know which join to use? If the request contains one of the key condition phrases: “whether or not”, “regardless of”, “no matter what”, “if any”. If any of these phrases fit in the generic information request of “get all information from this table—condition phrase—other information is present in the other table”, then a left outer join will be necessary.

51 Where to code the predicates The predicates applying to the left table in LEFT JOINs should be coded in a WHERE clause just like normal. Predicates on the right table in a LEFT JOIN must be in a table expression. Predicates for a FULL OUTER JOIN, since it is simulated with a UNION, can be placed in the proper place using the above rules

52 Joins and Predicates - Example List all students in a specific department whether or not they are taking classes this semester. If they are, list the course code and number.

53 Joins and Predicates – Example

54 Joins and Predicates – Example Results

55 Joins and Predicates – Example

56 Joins and Predicates – Example Results

57 Joins and Predicates – Example

58 Joins and Predicates – Example Results

59 Combining Joins Joins can be combined almost any way you want. FROM T1 LEFT OUTER JOIN T2 RIGHT OUTER JOIN T3 LEFT EXCEPTION JOIN T4 FROM T1 LEFT OUTER JOIN ((T2 RIGHT OUTER JOIN T3) LEFT EXCEPTION JOIN T4))

60 Common Table Expressions A table you create just for use in a complex query Can be referenced in a SQL statement just like any other table It only exists for the time it takes to run the SQL statement WITH table name AS select-stmt

61 Common Table Expression – Example

62 Common Table Expression – Example Results

63 In-line Views/Nested Table Expressions/Derived Tables All the terms refer to the same thing A nested table expression is a temporary view where the definition is nested (defined directly) in the FROM clause of a query. The SELECT statement must be enclosed in parenthesis.

64 Nested Table Expression – Example

65 Nested Table Expression – Example Results

66 Differences between Common and Nested Table Expressions A common table expression can only be defined at the beginning of a query, but once defined, can be used in any FROM clause in the query. A nested table expression can be placed in any FROM clause in the query, but must be defined each time it is used.

67 Table expressions – Example 1

68 Table expressions – Example 1 – Results

69 Table Expressions – Example 2 - Table Pivoting

70 Table Expressions – Example 2 - Results

71 Retrieving detail and summary in same result row SELECT SALES.*, SUMMARY.* FROM SALES, (SELECT REGION, SUM(SALES) AS TOT_SALES, MAX(SALES) AS MAX_SALES, AVG(SALES AS AVG_SALES FROM SALES GROUP BY REGION) AS SUMMARY WHERE SALES.REGION = SUMMARY.REGION

72 What can be in table expressions Anything that you can put in a regular SELECT statement can be used.