Gomaa Intelligence.Data Hub
عربي

Foundations › SQL › Combining Tables

🔗 Combining Tables

Subqueries, UNION and INTERSECT

Lesson 14 / 14· 10 min

A subquery is a SELECT inside a SELECT, in parentheses. We use it when we need an intermediate result such as an average or a list of customers.

▶ Try it yourself

Products pricier than the average of all products. Open in SQL Lab

▶ Try it yourself

Customers with orders in 2026. Open in SQL Lab

▶ Try it yourself

EXISTS asks whether a row exists. Here: products never sold. Open in SQL Lab

Subquery in FROM

▶ Try it yourself

Aggregate per customer first and then per city: aggregation on aggregation. Open in SQL Lab

Combining results: UNION, INTERSECT, EXCEPT

CommandResult
UNIONCombine without duplicates
UNION ALLCombine keeping duplicates (faster)
INTERSECTWhat both results share
EXCEPTIn the first but not in the second
▶ Try it yourself

Customers who ordered in both 2025 and 2026. Open in SQL Lab

For advanced readers CTEs and performance

A WITH clause (CTE) names a subquery and makes the query clearer; we cover it in the advanced stage with window functions. EXISTS is often faster than IN on large tables, and some optimizers rewrite one into the other.

Exercise 1 — Show the name and price of products pricier than the average price of all products.

Exercise 2 — Show the names of products that were never sold (absent from order_items).

Exercise 3 — Show customer_id of customers who ordered both before 2026 and in 2026.

Summary
  • A subquery is a SELECT inside a SELECT.
  • EXISTS and IN check existence.
  • UNION, INTERSECT and EXCEPT combine results.

Want an expert to do it for you?

Gomaa Intelligence turns your data into clear reports and decisions. Tell us your problem and we will reply.

Get your data analyzed by an expert ↗