Database Essentials - Writing Advanced SQL Queries - Overview of Named Queries

Let us understand how to use WITH clause to define a named query.

  • At times we might have to develop a large query in which the same complex logic needs to be used multiple times. The query can become cumbersome if you define the same logic repeatedly.
  • One way to mitigate this issue is by providing a name to the logic using the WITH clause.
  • We can only use the names provided to named queries as part of the main query that follows the WITH clause.

Named Query Example

In case of frequently used complex and large queries, we use named queries while defining the views. We will then use the view for reporting purposes.

Here is an example of using a named query with the WITH clause to simplify the logic.
WITH order_details_nq AS (
    SELECT * FROM orders o
    JOIN order_items oi
    ON o.order_id = oi.order_item_order_id
) 
SELECT * FROM order_details_nq LIMIT 10
One cannot use the named queries apart from the query in which it is defined. Following query will fail.

Using Named Query for Aggregation

Here is an example of using a named query for aggregating data based on product ID and order date to calculate revenue:

WITH order_details_nq AS (
    SELECT * FROM orders o
    JOIN order_items oi
    ON o.order_id = oi.order_item_order_id
) 
SELECT order_date,
    order_item_product_id,
    round(sum(order_item_subtotal)::numeric, 2) AS revenue
FROM order_details_nq 
GROUP BY order_date,
    order_item_product_id
ORDER BY order_date,
    revenue DESC
LIMIT 10

Using Named Query in a View

You can create a view using the named query for easy retrieval and reporting:

CREATE OR REPLACE VIEW daily_product_revenue_v AS
WITH order_details_nq AS (
    SELECT * FROM orders o
    JOIN order_items oi
    ON o.order_id = oi.order_item_order_id
) 
SELECT order_date,
    order_item_product_id,
    round(sum(order_item_subtotal)::numeric, 2) AS revenue
FROM order_details_nq 
GROUP BY order_date,
    order_item_product_id

Once the view is created, you can query the view directly:

SELECT * FROM daily_product_revenue_v
ORDER BY order_date, revenue DESC
LIMIT 10

This covers the usage of named queries with the WITH clause to simplify and reuse complex logic in SQL queries. Feel free to explore and experiment with this feature to enhance your SQL querying capabilities.

Watch the video tutorial here