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

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

ClauseDescription
ORDER BYSorts the output rows
LIMITRestricts number of rows returned
OFFSETSkips a number of rows
DISTINCTRemoves duplicate values
UNIONCombines and removes duplicates
UNION ALLCombines all, including duplicates
INTERSECTOnly returns rows common to both queries
EXCEPTReturns rows in first query not in second
0
Subscribe to my newsletter

Read articles from Yash Sakhareliya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yash Sakhareliya
Yash Sakhareliya