Derived Table and Common Table Expressions in SQL

Derived Table and Common Table Expressions in SQL

What are Derived Tables ?

  • Query which is treated like a temporary table

  • Always contained with the main query

  • They are specified in the FROM clause

  • Can contain intermediate calculations to be used in the main query or different joins than in the main query.

SELECT a.RecordId, a.Age, a.BloodGlucoseRandom, 
#Select maximum glucose value (use colname from derived table)    
       b.MaxGlucose
FROM Kidney a
#Join to derived table
Join (SELECT Age, MAX(BloodGlucoseRandom) AS MaxGlucose FROM Kidney GROUP BY Age) b
#Join on Age
on a.Age = b.Age

Creating a derived table to return all patient records with the highest BloodPressure at their Age level

SELECT *
FROM Kidney a
#JOIN and create the derived table
JOIN (SELECT Age, MAX(BloodPressure) AS MaxBloodPressure FROM Kidney GROUP BY Age) b
#JOIN on BloodPressure equal to MaxBloodPressure
ON a.BloodPressure = b.MaxBloodPressure
#Join on Age
AND a.Age = b.Age

Creating A Common Table Expression (CTE)

Using the WITH keyword to define the CTE name and also to specify the condition you want attributed to the name defined

-- Specify the keyword to create the CTE
WITH BloodGlucoseRandom (MaxGlucose) 
AS (SELECT MAX(BloodGlucoseRandom) AS MaxGlucose FROM Kidney)

Then we can match the CTE with a table for manipulation.

SELECT a.Age, b.MaxGlucose
FROM Kidney a
#Join the CTE on blood glucose equal to max blood glucose
JOIN BloodGlucoseRandom b
on a.BloodGlucoseRandom = b.MaxGlucose

Let's assume assume that CTE is like writing a function as it takes parameters needed only from the table. You can now use this to get matching result from the actual table. This is another way of condition statement as it allows you derive results based on the expression you have defined.