ح
حبيبي قطر
Module 13intermediate

CTEs - WITH Clause

Take Quiz
Lessons
What is a CTE?
1 / 1

A CTE (Common Table Expression) is a temporary result set that you can reference within a query. It makes complex queries easier to read.

Syntax

text-blue-600 dark:text-blue-400 font-semibold">WITH cte_name text-blue-600 dark:text-blue-400 font-semibold">AS (text-blue-600 dark:text-blue-400 font-semibold">SELECT ... ) text-blue-600 dark:text-blue-400 font-semibold">SELECT ... text-blue-600 dark:text-blue-400 font-semibold">FROM cte_name;

Sample Tables Used in This Course

employeesEmployee records
ColumnTypeKey
idINTEGERPK
nameTEXT
departmentTEXT
salaryINTEGER
countryTEXT
manager_idINTEGERFK → employees.id
emailTEXT
hire_dateTEXT
Sample Data (first 5 rows)
idnamedepartmentsalarycountrymanager_idemailhire_date
1Ahmed Al-ThaniIT25000QatarNULLahmed@qatarco.qa2018-03-15
2Fatima Al-KuwariHR18000Qatar1fatima@qatarco.qa2019-06-01
3Mohammed Al-SulaitiFinance22000Qatar1mohammed@qatarco.qa2017-09-20
4Sara Al-MansouriIT20000Qatar1sara@qatarco.qa2020-01-10
5Khalid HassanIT17000Egypt4khalid@qatarco.qa2021-04-05
ordersOrder transactions
ColumnTypeKey
idINTEGERPK
customer_idINTEGERFK → customers.id
amountDECIMAL
order_dateTEXT
regionTEXT
statusTEXT
Sample Data (first 5 rows)
idcustomer_idamountorder_dateregionstatus
11150002024-01-15Dohacompleted
2285002024-01-20Dohacompleted
33220002024-02-01Dohapending
4150002024-02-10Al Wakrahcompleted
54120002024-02-15Lusailshipped

Relationships: Primary Keys (PK) uniquely identify rows. Foreign Keys (FK) reference other tables.

Practice with these tables in the SQL Console. Click "Open Console" in the sidebar.

Example

text-blue-600 dark:text-blue-400 font-semibold">WITH high_earners text-blue-600 dark:text-blue-400 font-semibold">AS (
  text-blue-600 dark:text-blue-400 font-semibold">SELECT * text-blue-600 dark:text-blue-400 font-semibold">FROM employees text-blue-600 dark:text-blue-400 font-semibold">WHERE salary > text-amber-600 dark:text-amber-400">15000
)
text-blue-600 dark:text-blue-400 font-semibold">SELECT department, text-blue-600 dark:text-blue-400 font-semibold">COUNT(*) text-blue-600 dark:text-blue-400 font-semibold">FROM high_earners text-blue-600 dark:text-blue-400 font-semibold">GROUP BY department;

Creates a temporary table of high earners, then counts by department

Learning Objectives

  • Understand what CTEs are
  • Write queries using WITH clause