Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

Sub-Queries, Derived Tables, and Common Table Expression Examples

1. Introduction

In this example, we will explore some useful select queries that comes handy when we want to retrieve data from different tables. There many ways one can form select queries that returns the same result. For this article, we will use Microsoft’s Pubs database and explore Sub-Queries, Derived Tables and Common Table Expressions (CTE). We will explore these queries one by one.

2. Authors’ Mailing Address – Formatting the Result

Let us say we want to create a mailing address of Authors from the Pubs database. The problem is that the data stored in the Authors table is not in the mailing address format. The data is spawn among multiple columns. Now, have a look at the below query:

Formatting Columns - Mailing Address Example
Formatting Columns – Mailing Address Example

The above query uses the operator + which joins two strings. We use this operator to concatenate special chars, two columns, a constant string, etc.  Note, the space(2) function adds two blank spaces to the string formed. The char(13)  and char(10) together forms a ‘Line Feed’ and ‘Carriage Return’. The result of executing the above query is below:

Output of author's mailing address
Output of author’s mailing address

This output looks like a mailing address, right? Note, we should change the output format in the management studio to see the formatted result. The below picture shows how to turn ON the ‘Result to Text’ option:

Results to Text
Results to Text

3. SQL Case..When..Then Decision Making

The ‘ Case..When’ is decision making structure in SQL Queries. To know how it can be used, let us consider an example. The Titles table from the Pubs database has the book titles, and it also has the price of it. Now, let us say that when we are querying the books from this table, we need to display the title and price of the book along with the cost suggestion like Low, Medium and High; based on some price range. Now look at the below query example:

SQL Case...When...End Struct Example
SQL Case…When…End Struct Example

The portion of query marked in blue box shows how the costing level is done. The ‘case when then’ statement structure is making the decision in ‘When’ condition statement. When the condition evaluates to true, it will execute the ‘Then’ portion. For Example, when the price lies between 0 and 3, ‘Low’ will be returned from the ‘Then’ part. The ‘Else’ portion comes in combination with the ‘When’. It is like:

We use the ‘End’ keyword to tell the SQL Server that we are going to terminate the Case…When conditional construct.

4. Main Query and Sub-Query

Main query refers a ‘Sub-Query’ to decide something. Sub-query can use the data returned by the Main query and in the meantime, the main query cannot have access to the columns retrieved by the sub queries. This is shown in the below picture:

Main Query Don't have access to data of Sub-Query
Main Query Don’t have access to data of Sub-Query

Now we will look at the Pubs Database. We already know about the ‘Titles’ table since we used it in the previous examples. This table contains the book title and its price along with other information. The ‘Sales’ table contains information about the sales of the book titles along with some other information.

Let us see, how do we use sub-query to return the Book Titles that is not yet sold even a single piece. This means we have a book in the titles table and no entry for that book in the Sales Table. Have a look at the below Query:

SQL Sub-Query and Main Query Relation Example
SQL Sub-Query and Main Query Relation Example

In the above example, Main query is on the ‘Titles’ table and we want to return the titles, which are not making any sales. The Sub-Query is on the ‘Sales’ table which takes part in the where clause condition of the Main table. Note, the sub-query uses the column returned by the main table as ‘T.Title_Id’. The Main Query calls the Sub-Query for every row that it returns. Means, for each row in ‘Titles’ table it will make use of the Sub-Query to test the where condition.

When the sub Query returns no record, the ‘Not Exists’ check, which is part of the where condition, returns true there by signalling main query to include the current row in the query result.

5. Derived Tables (Sub-Query in From Clause)

In the previous example we saw a select statement embedded inside the ‘Where Clause’ of the main select statement. If similar sub query takes part in the ‘From Clause’ of the Main select query, we call that as ‘Derived Table’. When we do not have a table in the with required field values, we derive the table on the fly from the existing tables. Have a look at the below example which shows how a Table is derived in the ‘From Clause’ of the query:

SQL Server Derived Table Example
SQL Server Derived Table Example

The query takes the data from the ‘Titles’ table of the ‘Pubs’ database. The internal select statement (marked as a blue box) which looks like a sub-query is the Derived Table here. It gives the Title_id and total sales made on that specific title by using the aggregate function on the Sales table.

Note, we are joining the Titles table with the data returned from the Derived Table. The Inner Join is based on the Title_id from the Titles table and Title_Id returned by the Derived Table. The query output in the FROM portion of the SELECT query makes it as Derived Table. In this Query Example, we used the derived table technique to display book titles along with Total Sales.

The derived Table is an ‘In-Memory Table’ and SQL server wipes that from the memory when the query execution is done. In our example, the derived table is TS (Title_id, Total Sold).  This two-column table get removed from memory when the Query execution is over.

6. SQL CTE (Common Table Expressions)

We can reach the same result given by the Derived Table technique by using the ‘Common Table Expression’ approach. In CTE Style, we pull the table of data before starting the actual select query. Once the query is set, we can pick it in the subsequent select query multiple times. Now look at the below example:

Common Table Expression -CTE Example
Common Table Expression (CTE) Example

In the above example, first we set the Common Table Expression as shown in the above depiction (sign Mark 1). The common table Name is TotalByTitleId with two fields TitleId, Total in it. In our example, the mapping of CTE columns TitleId and Total is done by querying the Sales table. We keep the pulled result as table construct, TotalByTitleId.

In the above example, the next select query uses this CTE construct as a table. The select query retrieves the data from the Titles table and joins that with our CTE to get the total sales made by a book title. One can also use multiple CTE in SQL scripts. In that case, the comma will separate each CTE like below:

That is all in this Example!

Categories: SQL Server

Tags: , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.