Common Table Expressions

Gegevens manipuleren in SQL

Mona Khalil

Data Scientist, Greenhouse Software

Bij het toevoegen van subqueries...

  • Querycomplexiteit neemt snel toe!
    • Informatie kan moeilijk bij te houden zijn

Oplossing: Common Table Expressions!

Gegevens manipuleren in SQL

Common Table Expressions

Common Table Expressions (CTE's)

  • Tabel gedefinieerd voor de hoofdquery
  • Genoemd en gerefereerd later in FROM statement

CTE's instellen

WITH cte AS (
    SELECT col1, col2
    FROM table)

SELECT AVG(col1) AS avg_col FROM cte;
Gegevens manipuleren in SQL

Neem een subquery in FROM

SELECT
  c.name AS country,
  COUNT(s.id) AS matches
FROM country AS c
INNER JOIN (
  SELECT country_id, id 
  FROM match
  WHERE (home_goal + away_goal) >= 10) AS s
ON c.id = s.country_id
GROUP BY country;
| country     | matches |
|-------------|---------|
| England     | 3       |
| Germany     | 1       |
| Netherlands | 1       |
| Spain       | 4       |
Gegevens manipuleren in SQL

Plaats het aan het begin

(
  SELECT country_id, id 
  FROM match
  WHERE (home_goal + away_goal) >= 10
)
Gegevens manipuleren in SQL

Plaats het aan het begin

WITH s AS (
  SELECT country_id, id 
  FROM match
  WHERE (home_goal + away_goal) >= 10
)
Gegevens manipuleren in SQL

Toon de CTE

WITH s AS (
  SELECT country_id, id 
  FROM match
  WHERE (home_goal + away_goal) >= 10
)
SELECT
  c.name AS country,
  COUNT(s.id) AS matches
FROM country AS c
INNER JOIN s
ON c.id = s.country_id
GROUP BY country;
| country     | matches |
|-------------|---------|
| England     | 3       |
| Germany     | 1       |
| Netherlands | 1       |
| Spain       | 4       |
Gegevens manipuleren in SQL

Toon alle CTE's

WITH s1 AS (
  SELECT country_id, id 
  FROM match
  WHERE (home_goal + away_goal) >= 10),
s2 AS (                              -- Nieuwe subquery
  SELECT country_id, id 
  FROM match
  WHERE (home_goal + away_goal) <= 1
)
SELECT
  c.name AS country,
  COUNT(s1.id) AS high_scores,
  COUNT(s2.id) AS low_scores         -- Nieuwe kolom
FROM country AS c
INNER JOIN s1
ON c.id = s1.country_id
INNER JOIN s2                        -- Nieuwe join
ON c.id = s2.country_id
GROUP BY country;
Gegevens manipuleren in SQL

Waarom CTE's gebruiken?

  • Eenmalig uitgevoerd

    • CTE wordt dan in geheugen opgeslagen
    • Verbetert query-prestaties
  • Betere organisatie van queries

  • Andere CTE's refereren

  • Zichzelf refereren (SELF JOIN)
Gegevens manipuleren in SQL

Laten we oefenen!

Gegevens manipuleren in SQL

Preparing Video For Download...