Instructor: Craig Duckett Lecture 09: Thursday, May 7, 2015 CASE, ORDER BY, GROUP BY, HAVING,...

25
Instructor: Craig Duckett Lecture 09: Thursday, May 7, 2015 CASE, ORDER BY, GROUP BY, HAVING, Subqueries 1

Transcript of Instructor: Craig Duckett Lecture 09: Thursday, May 7, 2015 CASE, ORDER BY, GROUP BY, HAVING,...

1

Instructor: Craig Duckett

Lecture 09: Thursday, May 7, 2015CASE, ORDER BY, GROUP BY, HAVING,

Subqueries

2

• Assignment 2 is due LECTURE 11, Thursday, May 14th, in StudentTracker by MIDNIGHT

• MID-TERM EXAM is LECTURE 10, NEXT Tuesday, May 12th It will cover everything discussed through today's lecture, Lecture 9, including any chapter reading from The DATABASE DESIGN FOR MERE MORTALS and THE LANGUAGE OF SQL books. You’re allowed to use one large index card for crib notes during the mid-term. I’ll post a Mid-Term Study Guide on the BIT275 website sometime on Friday, May 8.

3

Tuesday (LECTURE 8)• Database Design for Mere Mortals: Chapter 6

Thursday (LECTURE 9)• The Language of SQL: Chapters 7, 8

4

• CASE• ORDER BY• GROUP BY• HAVING• Subqueries

SQL: The CASE ExpressionThe CASE expression and its shorthand equivalents, COALESCE() and NULLIF(), let you take actions based on a condition’s truth value (true, false, or unknown). The CASE expression’ important characteristics are:

• If you’ve programmed before, you’ll recognize that CASE provides SQL the equivalent of the if-then-else, case, or switch statements used in procedural languages, except that CASE is an expression, not a statement. *

• CASE is used to evaluate several conditions and return a single value for the first true condition.

• CASE allows you to display an alternative value to the actual value in a column. CASE makes no changes to the underlying data.

* An expression can be evaluated, and as such returns a single value. It is only one possible part of a statement. A statement is a collection of elements such as identifiers, reserved keywords, data types, functions, expressions, operators and comments, to make the smallest possible unit of code. A statement can be executed.

SQL: The CASE Expression

• A common use of CASE is to replace codes or abbreviations with more-readable values.

EXAMPLE: If the column marital status contains the integer codes 1, 2, 3, or 4—meaning single, married, divorced, or widowed—your human readers will prefer to see explanatory text rather than cryptic codes. (Some database designers prefer to use codes, because it’s more efficient to store and manage abbreviated codes than explanatory text.)

• CASE has two formats: simple and searched. The simple CASE expression compares an expression to a set of simple expressions to determine the result. The searched CASE expression evaluates a set of logical (Boolean) expressions to determine the result.

• CASE returns an optional ELSE result as the default value if no test condition is true.

SQL: The CASE ExpressionTo use a simple case expression:

value1, value2, ..., valueN are expressions. result1, result2, ..., resultN are expressions returned when the corresponding value matches the expression comparison_value. All expressions must be of the same type or must be implicitly convertible to the same type.

Each value is compared to comparison_ value in order. First, value1 is compared. If it matches comparison value, then result1 is returned; otherwise, value2 is compared to comparison_value. If value2 matches comparison_value, then result2 is returned, and so on. If no matches occur, default_ result is returned. If ELSE default_result is omitted, ELSE NULL is assumed.

SQL: The CASE ExpressionWe get many questions asking whether it's possible to use an IF clause inside a SELECT statement. Well, not exactly. But you can use CASE to do the exact same thing.

Let's look at what a simple CASE statement in a query looks like:

If the field contains 'CA' then the CASE statement returns 'California'. 'KS' returns 'Kansas' and 'TN' returns 'Tennessee'.

If the value of state does not match any of the WHEN expressions, the expression in the ELSE clause is returned, 'Some Other State'.

The AS StateName aliases the column name to StateName.

This query will return three columns.

The third column, StateName, is constructed using the CASE statement.

The CASE statement is enclosed by the keywords CASE and END. The CASE statement evaluates the state field.

SQL: The CASE ExpressionAnother simple case expression example:

SQL: The CASE Expression

condition1, condition2, ..., conditionN are search conditions. (Search conditions have one or more logical expressions, with multiple expressions linked by AND or OR.

result1, result2, ..., resultN are expressions returned when the corresponding condition evaluates to true. All expressions must be of the same type or must be implicitly convertible to the same type.

Each condition is evaluated in order. First, condition1 is evaluated. If it’s true, result1 is returned; otherwise, condition2 is evaluated. If condition2 is true, result2 is returned, and so on. If no conditions are true, default_result is returned. If ELSE default_result is omitted, ELSE NULL is assumed.

To use a searched CASE expression:

SQL: The CASE Expression

This CASE statement will run through each WHEN clause until it finds a true one. If they all evaluate to false it will return the ELSE clause. In both cases if there is no ELSE clause it will return a NULL.

In this second example, each boolean expression is independent of each other statement. I can actually compare different columns (e.g., state and city). Remember that it searches through the WHEN clauses from top to bottom so order them carefully.

In the searched case expression, CASE is evaluating a series of boolean expressions. It returns the first expression that evaluates to true.

SQL: The CASE ExpressionAnother example of a searched case expression.

Difference between ORDER BY and GROUP BYThe difference is exactly what the name implies: an ORDER BY sorts and a GROUP BY performs a grouping operation usually based on an aggregate of some sort. So what does this mean, exactly?

ORDER BY is used to order the rows resulted from a SELECT statement. ORDER BY allows you to sort the result set according to different criteria, such as sort by name from a-z, then sort by price highest to lowest: ORDER BY name, price DESC

GROUP BY is used to group rows in a SELECT, usually when aggregating rows (e.g. using SUM, or COUNT, or AVG for a set of rows with the same values for some fields). GROUP BY allows you to take your result set, group it into logical groups and then run aggregate queries on the groups.

For example, you could select all employees, group them by their workplace location and calculate the average salary. This would give you the average salary of an employee at a given workplace location in your database.

ORDER BY

ORDER BY

GROUP BY

GROUP BY with ORDER BY

SQL: Filtering Groups with HAVINGThe HAVING clause sets conditions on the GROUP BY clause similar to the way that WHEREinteracts with SELECT.

The HAVING clause’s important characteristics are:

• The HAVING clause comes after the GROUP BY clause and before the ORDER BY clause.• Just as WHERE limits the number of rows displayed by SELECT, HAVING limits the number of

groups displayed by GROUP BY.• The WHERE search condition is applied before grouping occurs, and the HAVING search

condition is applied after.• HAVING syntax is similar to the WHERE syntax, except that HAVING can contain aggregate

functions.• A HAVING clause can reference any of the items that appear in the SELECT list.

The sequence in which the WHERE, GROUP BY, and HAVING clauses are applied is:1. The WHERE clause filters the rows that result from the operations specified in the FROM and

JOIN clauses.2. The GROUP BY clause groups the output of the WHERE clause.3. The HAVING clause filters rows from the grouped result.

SQL: Filtering Groups with HAVINGList the number of books of each type for each publisher, for publishers with more than one title of a type.

SQL: Filtering Groups with HAVINGList the number of titles and average revenue for the types with average revenue more than $1 million.

SQL: Filtering Groups with HAVINGList the number of books of each type for each publisher, for publishers with more than one title of a type.

SQL: SubqueriesA Subquery or Inner query or Nested query is a query within another SQL query, and embedded within the WHERE clause.

A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.

Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.

There are a few rules that subqueries must follow:

• Subqueries must be enclosed within parentheses ( )• A subquery can have only one column in the SELECT clause, unless multiple columns are in the

main query for the subquery to compare its selected columns.• An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY.

The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.

SQL: Subqueries

Example

TO BE CONTINUED…WE WILL BE DEDICATING

MORE TIME TO THIS TOPIC NEXT THURSDAY

(MID-TERM ON TUESDAY)

24

BIT 275 ICE 9

25

ICE 09

XXXXX