SQL Essentials: ORDER BY, LIMIT, OFFSET, UNION, INTERSECT, and More

Table of contents
- 1. ORDER BY โ Sorting Results
- ๐ข 2. LIMIT โ Restrict Number of Rows
- ๐ 3. OFFSET โ Skip Rows
- ๐ฏ 4. DISTINCT โ Remove Duplicate Rows
- ๐ 5. UNION โ Combine Results Vertically (Remove Duplicates)
- ๐ 6. UNION ALL โ Combine Results with Duplicates
- ๐ 7. INTERSECT โ Common Records
- ๐ซ 8. EXCEPT โ Remove Matching Records
1. ORDER BY
โ Sorting Results
Used to sort query output in ascending (ASC
, default) or descending (DESC
) order.
-- Sort products by price ascending
SELECT * FROM products
ORDER BY price;
-- Sort by price descending
SELECT * FROM products
ORDER BY price DESC;
โ You can sort by multiple columns too:
-- First by category, then by price descending
SELECT * FROM products
ORDER BY category, price DESC;
๐ข 2. LIMIT
โ Restrict Number of Rows
Returns only a limited number of records.
-- Show top 5 products
SELECT * FROM products
ORDER BY price DESC
LIMIT 5;
๐ 3. OFFSET
โ Skip Rows
Used with LIMIT
to paginate results.
-- Skip first 5, get next 5 (for page 2)
SELECT * FROM products
ORDER BY price DESC
LIMIT 5 OFFSET 5;
๐ Equivalent to: "Show me page 2 of top results (5 per page)."
๐ฏ 4. DISTINCT
โ Remove Duplicate Rows
Removes duplicate records in the output.
-- Unique categories
SELECT DISTINCT category FROM products;
-- Unique combination of category and brand
SELECT DISTINCT category, brand FROM products;
๐ 5. UNION
โ Combine Results Vertically (Remove Duplicates)
Combines results of two queries with distinct results.
(
SELECT name FROM employees
)
UNION
(
SELECT name FROM customers;
);
โ Ensures no duplicates.
๐ 6. UNION ALL
โ Combine Results with Duplicates
Same as UNION
but includes duplicates.
(
SELECT name FROM employees
)
UNION ALL
(
SELECT name FROM customers;
);
๐ 7. INTERSECT
โ Common Records
Returns rows common to both queries.
(
SELECT name FROM employees
)
INTERSECT
(
SELECT name FROM customers;
);
PostgreSQL supports
INTERSECT
, but some DBs like MySQL do not.
๐ซ 8. EXCEPT
โ Remove Matching Records
Returns rows from the first query that are not in the second.
(
SELECT name FROM employees
)
EXCEPT
(
SELECT name FROM customers;
);
Gives all employee names who are not customers.
๐ง Summary Table
Clause | Description |
ORDER BY | Sorts the output rows |
LIMIT | Restricts number of rows returned |
OFFSET | Skips a number of rows |
DISTINCT | Removes duplicate values |
UNION | Combines and removes duplicates |
UNION ALL | Combines all, including duplicates |
INTERSECT | Only returns rows common to both queries |
EXCEPT | Returns rows in first query not in second |
Subscribe to my newsletter
Read articles from Yash Sakhareliya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
