2.4 SQL Subqueries & Temporary Tables (Advanced)

2.4.1 Subqueries

This is a way to nest queries, it means: The result of one query will be used as FROM to the next query.

SELECT *
FROM(SELECT something
     FROM   interesting) AS table_1

In the example above, I have one query nested to another. Bear in mind, I must give a alias to the nested query.

If the result of the subquery is a single value, you are allowed to insert this subquery wherever you want.

2.4.2 WITH

Also known as Common Table Expression (CTE), is a kinf of subquery but could be more helpful if someone is going to read the code. Due to the possibility to write the code in fragments an assign name, this is very handy.

Example

WITH my_with_example AS (SELECT ... MY CODE)

SELECT something
FROM my_with_example

As you can see it provide a better way to code because the code became more readable.

 

A work by AH Uyekita

anderson.uyekita[at]gmail.com