liveBook · Manning

Common table expression

As explained in AI for Everyday IT

A common table expression is a named temporary query result defined within a SQL statement and referenced by that statement.

A common table expression (CTE) names an intermediate query result inside a SQL statement. It helps separate data conversion from later calculations, making a complex administrative query easier to simplify and refine. section 10.6.2

Calculating memory utilization

A memory-monitoring query can use one CTE to convert settings such as 6G into megabytes, then a second CTE to calculate total memory in use. The final query filters systems using more than 75 percent of physical memory. The result can support a scheduled monthly SQL Server Agent report, but generated SQL should be validated and corrected when syntax or edge cases are wrong. section 10.6.2

figure
-- CTE for converting memory settings to MB and calculating total memory
   in use
WITH MemoryCalculations AS (
    SELECT
        [SERVERNAME],
        [DB_NAME],
        [PhysicalMemory],
        CASE
            WHEN RIGHT([memory_max_target], 1) = 'M' THEN CAST(SUBSTRING(
              [memory_max_target], 1, LEN([memory_max_target]) -              1) AS INT)
            WHEN RIGHT([memory_max_target], 1) = 'G' THEN CAST(SUBSTRING(
              [memory_max_target], 1, LEN([memory_max_target]) - 1)
              AS INT) * 1024
            ELSE [memory_max_target]
        END AS [memory_max_target_MB],
...
),
-- Second CTE for calculating total memory in use
FinalCalculations AS (
    SELECT
        [SERVERNAME],
        [DB_NAME],
        [PhysicalMemory],
        CASE
            WHEN [memory_max_target_MB] != 0 THEN [memory_max_target_MB]
            ELSE [sga_max_size_MB] + [pga_aggregate_limit_MB]
        END AS [TotalMemoryInUse_MB]
    FROM
        MemoryCalculations
)
SELECT
    *,
    ([TotalMemoryInUse_MB] * 1.0 / [PhysicalMemory]) * 100
       AS [TotalMemoryInUse_Percentage]
FROM
    FinalCalculations
WHERE
    ([TotalMemoryInUse_MB] * 1.0 / [PhysicalMemory]) * 100 > 75

Inspect the two-stage CTE structure for unit conversion followed by total-memory calculation. section 10.6.2

How AI for Everyday IT covers it

How deep it goes
Demonstrates a two-stage implementation but stops short of explaining CTE execution internals.
Examples
Uses Oracle memory settings, megabyte conversion, utilization thresholds, and a monthly SQL Server Agent report.
What you can do after
Apply it via SQL to organize calculations and produce a monitorable memory-configuration query.
How it connects
Connects CTEs with SQL queries, data conversion, conditional calculations, filtering, and scheduled monitoring.

Also explained in

Compare how 6 books explain common table expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of AI for Everyday IT. The section links point to the parts of the book it draws on.