Showing posts with label sql302. Show all posts
Showing posts with label sql302. Show all posts

Sunday, September 9, 2012

CASE expressions

There are times when you want to pick one of several alternatives for a field in your select list. The examples we are going to use are from our bookstore database (click to download at box.com). In our first example we want to look at the order_filled column and depending on its value display a message. To do this we can use the CASE expression. In our second example we will look at the customer table and show the referrer, if any, for each customer. There are two types of CASE expressions: simple or unsearched and searched. Our examples demonstrate both.

Simple Syntax

CASE selector when expr1 then value1 when expr2 then value2 ... when exprN then valueN else value 3

The else clause is optional. The alternative is selected based on the value of the selector.

Searched Syntax

This one has no selector. The alternative expressions are evaluated and if true that choice is used.

CASE when expr1 then value1 when expr2 then value2 ... when exprN then valueN else value 3

Simple Example

Here is an example of this syntax. It expands the order_filled yes/no field.

use bookstore;  select order_numb, order_date,  case order_filled
  when 'Yes' then 'Order status: Filled'  when 'No' then 'Order status: Not filled'  else 'Errorneous order status detected'  end 'Order_Filled'from orders;
Simple Results



Searched CASE example

This example below shows who referred a customer. If the customer was not referred by another customer we print "self". In this case we cannot use a selector since it might evaluate to a null which leads to no defined choice. Instead, this example uses a searched case which separately evaluates each condition. You have to do it this way if the field you might use for a selector can contain nulls.

use bookstore;
select
c.customer_first_name
, c.customer_last_name
, case  when c.referred_by is null then 'Self'  else r.customer_last_name
  end as 'Referred By'from customers c left join customers r on c.referred_by = r.customer_numb;
Searched CASE reuslts


Conclusion


The CASE expression can be very helpful when you need to choose between several alternatives. I am sure you will find it useful. Note there is another similar keyword - DECODE - used in Oracle.



 







Thursday, June 14, 2012

Left Outer Join with Partial Match
There are some subleties to outer joins involving partial matches. We have looked at joins where we want to show all the rows from the one side of a relationship. Or conversely the rows from the one side that have no matches on the many side. But what if we want to see all the rows from the one side and only a subset from the many side? For eaxmple show all my customers along with their orders for last year. Our first pass at this might be something like the query below.



But this will not work since the filter for 1999 orders effectively masks out the effect of the outer join. We don't want to filter out customers, just orders. The missing values should be replaced by nulls as is normal for outer joins.

Solution
The solution to the above is to prefilter the orders and then join the results of that to the customers using an outer join. We can prefilter the orders in a derived table or inline view using the following syntax.

Syntax

select columns
from table1
left join
(select statement) derived table alias
on table1 key = derived table key

Sample Code
Here is the actual code using the bookstore database (download from Box.net).



Results

Here is an extract of the results of running the above query, Emily Jones and Mary Collins did not place any orders in 1999 but were still listed.













Follow Up
We will expand on this concept in future additions to this post. Hopefully this post will have shown you how to work with outer joins that partially match. It also provided a look at inline views or derived tables which we will cover in more detail in other posts.

Tuesday, June 5, 2012

Left Outer Join

Introduction
This post shows how to create a left outer join. Outer joins are often used in reporting. It also shows how to modify the outer join to create a "find unmatched" query.

Outer Joins
When you join two tables in SOL the default join type is an inner join. This means that only rows with matching key values from each table are retrieved. For example if I join customers with their orders I will not see customer names with no orders. But it is common in reporting that you want to see all rows from the "one" side of the relationship even if there is no match. In the above example I might want to see all my customer names even if they have not placed an order yet. This is accomplished with an outer join. They come in three flavors: left, right and full.
  • Left - all matched rows plus unmatched from the "left" table. Note that left refers to reading order. It means the first table mentioned in the query, the one to the "left".
  • Right - all unmatched plus unmatched from the right table. The unmatched from the right table would imply they are orphan records since their foreign key did not refer to an existing parent record.
  • Full- not often seen. Adds unmatched from both left and right tables. 
We will present an example of the left outer join, which is the most common, below. This example uses the bookstore database which can be downloaded from box.net.

Left Outer Join Syntax
Here is the basic syntax for a left outer join. We will assume the "one" side is the left table. Note the word outer is optional.

Select columnlist
from table1
left [outer] join table2
on table1.primarykey = table2.foreignkey;

Example
Below is an example using the bookstore database.


Results
Below is a section of the result set. Note that when there is no match the missing values are filled in as nulls by SOL. In the results below the Browns have not placed any orders.










Unmatched (Negative) Left Outer Join
Suppose you want to list all customers who have not placed an order. You can do this by creating a left outer join from the customers table to the orders table. As we have seen this will produce a list of all customers along with their orders. The list will include customers that have not placed any orders since a left join includes all rows from the left table. You can restrict the result set to only those who have not placed orders. Do this by adding a where clause to test for null order numbers. The order number is the primary key in the orders table and wouldn't be in the result set as a null unless it was generated by the left join. This is a common query to test for missing information or missing records.

Syntax
select columnlist
from table1
left [outer] join table2
on table1.primarykey = table2.foreignkey
where table2.primarykey is null;

Example
Results
Below are the results using the bookstore sample database. (In reality you might not want to show the order columns).





More to follow...
There is another type of unmatched join where there is a partial match. For example: list all customers and the titles of books they bought that were written by a certain author. Include all customers even if they did not buy any books from the given author. We will cover this in a subsequent post and in our Intermediate SOL course (SQL302 & 312).

Thursday, April 5, 2012

With Cube

Background
SQL does not normally put total lines in the same result set as the detail like an accounting spreadsheet. By adding with cube to the group by clause you will get the total lines as shown below. It is similar to with rollup but subtotals each dimension. For our examples we will use a tiny fact table from the pets database. You can download the database script here. It is a tiny fact table that summarizes animals available by store. We originally obtained the table from the internet, I forget where. At some point we may add dimension tables to get a true star schema.

Notes
The result set returned by a group by with cube is a valid SQL result set. It can be filtered or manipulated like any other result set. The total line or lines returned are not the total of the groups shown. They are the totals in the table. An example below will make this clearer. A NULL is placed in the dimension column where a summary row has been inserted.

Syntax
SELECT statement...
...
GROUP BY groupbylist
WITH CUBE

Example 1
Show the animals available by store with subtotals for each store type and a grand total. In addition show the subtotals for each animal type.























Example 2
Same above but retain only rows with number available greater than 10. Note that the grand total row still shows 63 animals available.




Friday, March 2, 2012

With Rollup

Background
SQL does not normally put a total line in the same result set as the detail like an accounting spreadsheet. By adding with rollup to the group by clause you will get the total line as shown below. For our examples we will use a tiny fact table from the pets database. You can download the database script here. It is a tiny fact table that summarizes animals available by store. We originally obtained the table from the internet, I forget where. At some point we may add dimension tables to get a true star schema.

Notes
The result set returned by a group by with rollup is a valid SQL result set. It can be filtered or manipulated like any other result set. The total line or lines returned are not the total of the groups shown. They are the totals in the table. An example below will make this clearer. A NULL is placed in the column where the summary row has been inserted.

Syntax
SELECT statement...
...
GROUP BY groupbylist
WITH ROLLUP

Example 1
Show the animals available by store with subtotal for each animal type and a grand total.






















Example 2
Same above but retain only rows with number available greater than 10. Note that the grand total row still shows 63 animals available.


Sunday, February 19, 2012

Combination Queries

There is a set of queries sometimes referred to as combination queries. There are three set operators used to create them...
  • UNION
  • INTERSECT
  • EXCEPT

We looked at the Union in our basic class. Below we will present the other two. Each is based on the bookstore database which can be downloaded here.

INTERSECT
The intersect operator retrieves all unique rows found in both tables.

Example
The following query will find all cities in common between the sources and customers tables.

Script

use bookstore -- MySQL and SQL Server
select customer_city, customer_state, customer_zip
from customers
intersect
select
source_city, source_state, source_zip

from sources;

EXCEPT
The except operator will retrieve all rows found in the first table but not in the second.

Example
Find all cities where the source is located in a city that does not have a customer.

Script

use bookstore -- MySQL and SQL Server
select source_city, source_state, source_zip
from sources
except
select customer_city, customer_state, customer_zip
from customers;