Simplify SQL "With" Common Table Expressions

SQL
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

 

Use the WITH keyword to make your SQL statements easier to code and maintain.

 

Common table expressions (CTEs) allow you to break down complex SQL logic into smaller pieces. This makes development and testing easier, and when you come back to the code next year you'll understand it more quickly. That can't be bad, and a CTE is not hard to use. In this article, I'll provide working examples of CTEs that demonstrate their ease of use and the clarity they can provide.

 

 

CTE Syntax

 

"Common table expression" is a bit of an intimidating mouthful. The V7R1 IBM i DB2 for i SQL Reference manual says this:

 

A common-table-expression permits defining a result table with a table-identifier that can be specified as a table name in any FROM clause of the fullselect that follows. Multiple common table expressions can be specified following the single WITH keyword. Each common table expression specified can also be referenced by name in the FROM clause of subsequent common table expressions.

 

This means:

  • A CTE must be part of a SELECT statement. (This is important to remember when you get around to trying to use a CTE in a CREATE statement or an INSERT statement. I'll provide an example that covers this.)
  • A CTE is defined using the WITH keyword.
  • The WITH keyword can define one or more CTEs.

Think of a CTE as a temporary named view as you follow along with the examples I provide.

 

Running the Examples

 

The examples in this article are based on file QIWS/QCUSTCDT, which I believe by default is available on almost everyone's machine, unless you have deleted it. (So far, no one has complained that QCUSTCDT is missing.) It contains just 12 records, and some of the data looks like this:

 

CUSNUM   LSTNAM   CITY   STATE ZIPCOD   CDTLMT     BALDUE

938,472   Henning   Dallas   TX   75,217   5,000     37.00

839,283   Jones     Clay     NY   13,041     400     100.00

392,859   Vine      Broton   VT     5,046     700     439.00

938,485   Johnson   Helen   GA   30,545   9,999   3,987.50

397,267   Tyron     Hector   NY   14,841   1,000       .00

389,572   Stevens   Denver   CO   80,226     400     58.75

846,283   Alison   Isle     MN   56,342   5,000     10.00

475,938   Doe       Sutter   CA   95,685     700     250.00

693,829   Thomas   Casper   WY   82,609   9,999       .00

593,029   Williams Dallas   TX   75,218     200     25.00

192,837   Lee       Hector   NY   14,841     700     489.50

583,990   Abraham   Isle     MN   56,342   9,999     500.00

 

The examples are contrived to fit this data, but they might bear some semblance to real business requirements. You should be able to cut and paste the example code into your favorite SQL client.

 

A Single CTE

 

Suppose we want to list those customers whose balance-to-credit ratio is greater than 50 percent and we want it by ratio descending. We need to take the balance due, divide by the credit limit, multiply by 100 to create a percent, and then ensure that the percent has two decimal places. We name the resulting field "Pct_Cred" for the report.

 

Our first attempt to code this query without a CTE might look like this:

 

select     decimal((BALDUE / CDTLMT) * 100,5,2) as Pct_Cred,

           CUSNUM, LSTNAM, CDTLMT, BALDUE

from       QIWS/QCUSTCDT

where     Pct_Cred > 50

order by   Pct_Cred desc

 

However, when you try to run this, SQL complains that "Column or global variable PCT_CRED not found." This is because the WHERE clause does not recognize the new Pct_Cred column (field) created in the SELECT clause.

 

A revised attempt might look like this, where we duplicate the Pct_Cred calculation in the WHERE clause:

 

select     decimal((BALDUE / CDTLMT) * 100,5,2) as Pct_Cred,

           CUSNUM, LSTNAM, CDTLMT, BALDUE

from       QIWS/QCUSTCDT

where     decimal((BALDUE / CDTLMT) * 100,5,2) > 50

order by   Pct_Cred desc

 

This does create the report we expect, which looks like this:

 

PCT_CRED   CUSNUM   LSTNAM   CDTLMT    BALDUE

   69.92   192,837   Lee         700     489.50

   62.71   392,859   Vine         700     439.00

 

I don't like coding the same calculation twice, even the relatively simple Pct_Credit calculation in this demonstration example. You all know the problems with duplicated code: It doesn't always all get changed, it doesn't always get changed the same way, and it takes more time to change. If I use a CTE, I can code the Pct_Credit calculation only once, like this:

 

with CreditRatio as (

select   decimal((BALDUE / CDTLMT) * 100,5,2) as Pct_Cred,

           a.*

from     QIWS/QCUSTCDT a

)

select     Pct_Cred, CUSNUM, LSTNAM, CDTLMT, BALDUE

from       CreditRatio

where     Pct_Cred > 50

order by   Pct_Cred desc

 

The CTE is the first five lines of the code, from the "with" on the first line to the ")" on the fifth line. The CTE name is CreditRatio. Think of CreditRatio as a temporary table that contains all columns of QCUSTCDT, plus a brand new column Pct_Cred.

 

Now that you have a table named CreditRatio, you can reference in a FROM clause, as done on the seventh line, and refer to all columns in CreditRatio, including the new column Pct_Cred.

 

The credit percent ratio logic is in a single place, it is easily changed, and I find it a lot easier to read the overall SQL.

 

Coding and Testing with CTE

 

You can develop and test incrementally. While it may be overkill for this example, I would first code and test this:

 

select   decimal((BALDUE / CDTLMT) * 100,5,2) as Pct_Cred,

           a.*

from   QIWS/QCUSTCDT a

 

Once I had this working, I would then wrap it in the WITH keyword and test again as below, to prove that I had the CTE working correctly:

 

with CreditRatio as (

select   decimal((BALDUE / CDTLMT) * 100,5,2) as Pct_Cred,

           a.*

from     QIWS/QCUSTCDT a

)

select     *

from       CreditRatio

 

Finally, I'd flesh out the final select.

 

Two CTEs

 

You can also have two, or more, CTEs.

 

Suppose the credit manager changes his mind (surprise!) and now wants to see the credit ratio of all customers, but wants them in three groups: up to 30 percent, 30–60 percent, and greater than 60 percent. We can now build a second CTE, CreditRank, based on the original CreditRatio CTE.

 

Note the following in the code below:

  • There's only one WITH keyword.
  • Each CTE is enclosed in parentheses.
  • CTEs are separated by commas.

I have changed the code formatting to highlight these points.

 

with

CreditRatio as

(

select   decimal((BALDUE / CDTLMT) * 100,5,2) as Pct_Cred,

           a.*

from     QIWS/QCUSTCDT a

)

,

CreditRank as

(

select   case

               when Pct_Cred < 30 then 1

               when Pct_Cred > 60 then 3

               else 2

           end as Cred_Rank,

           a.*

from     CreditRatio a

)

select     Cred_Rank, Pct_Cred, CUSNUM, LSTNAM, CDTLMT, BALDUE

from       CreditRank

order by   Cred_Rank, Pct_Cred, CUSNUM

 

The new CreditRank CTE selects from the CreditRatio CTE and uses a CASE statement to create another column, Cred_Rank. (If you need help with CASE syntax, check "The Case for SQL CASE.")

 

The FROM clause in the final select is then changed to use the CreditRank CTE.

 

This gives us results like this:

 

CRED_RANK   PCT_CRED   CUSNUM   LSTNAM   CDTLMT     BALDUE

       1       .00   397,267   Tyron     1,000       .00

       1       .00   693,829   Thomas     9,999       .00

       1       .20   846,283   Alison     5,000     10.00

       1       .74   938,472   Henning   5,000    37.00

       1     5.00   583,990   Abraham   9,999     500.00

       1     12.50   593,029   Williams     200     25.00

       1     14.68   389,572   Stevens     400     58.75

       1     25.00   839,283   Jones       400     100.00

       2     35.71   475,938   Doe         700     250.00

       2     39.87   938,485   Johnson   9,999   3,987.50

       3     62.71   392,859   Vine         700     439.00

       3     69.92   192,837   Lee         700     489.50

 

Note that a second or subsequent CTE does not have to select from a prior CTE as done here; it can just as easily select from another table or view.

 

CTEs with CREATE

 

Suppose we want to create a table that holds the credit ratio, customer number, and customer name of those customers who have a credit limit greater than 50 percent. It seems logical that the first thing you need to code is the WITH keyword, followed by CREATE, but this is incorrect.

 

Here is the correct syntax to use with a CREATE statement, where the WITH keyword is part of the SELECT statement:

 

create table QTEMP/Cust_Ratio as

(

with

CreditRatio as

(

   select   decimal((BALDUE / CDTLMT) * 100,5,2) as Pct_Cred,

             CUSNUM as Customer_Number,

             trim(LSTNAM) concat ', ' concat trim(INIT) as Customer_Name

   from     QIWS/QCUSTCDT

)

select     *

from       CreditRatio

where     Pct_Cred > 50

) with data

 

I created this table in QTEMP since this is a demonstration. You could create it in any library you desire. QTEMP/Cust_Ratio contains this data:

 

PCT_CRED CUSTOMER_NUMBER CUSTOMER_NAME

62.71       392,859     Vine, S S  

69.92       192,837     Lee, F L    

 

CTEs with INSERT

 

Using a CTE in an INSERT statement is very similar to CREATE. To demonstrate, we'll take those customers with a credit ratio less than 5 percent and insert then into QTEMP/Cust_Ratio.

 

insert into QTEMP/Cust_Ratio

with

CreditRatio as

(

   select   decimal((BALDUE / CDTLMT) * 100,5,2) as Pct_Cred,

             CUSNUM as Customer_Number,

             trim(LSTNAM) concat ', ' concat trim(INIT) as Customer_Name

   from     QIWS/QCUSTCDT

)

select     *

from       CreditRatio

where     Pct_Cred < 5

 

QTEMP/Cust_Ratio now contains this data:

 

PCT_CRED CUSTOMER_NUMBER CUSTOMER_NAME

62.71       392,859     Vine, S S    

69.92       192,837     Lee, F L    

   .74       938,472     Henning, G K

   .00       397,267     Tyron, W E  

   .20       846,283     Alison, J S  

   .00       693,829     Thomas, A N

  

Conclusion

Common table expressions (CTEs) are simply defined using the WITH keyword. They allow for logic to be coded in a single place and simplify coding and maintainability. SQL should be part of your developer toolbox, and using CTEs can make you more productive.

 

Notes

I ran these examples on the free V5R3 machine at http://www.rzkh.de, but CTEs have been available since V4R4.

 

I have formatted the example code because I find it much easier to read and debug. However, SQL does not require such formatting.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$