GROUP BY
ELI5 — The Vibe Check
GROUP BY collapses rows with the same value into one group so you can count, sum, or average them. 'How many orders per user?' — GROUP BY user_id. It is like pivoting a list into a summary.
Real Talk
GROUP BY aggregates rows that share the same values in specified columns into summary rows. It is always used with aggregate functions (COUNT, SUM, AVG, MAX, MIN). Non-aggregated columns in the SELECT must appear in the GROUP BY clause.
Show Me The Code
SELECT user_id, COUNT(*) AS order_count, SUM(total) AS revenue
FROM orders
GROUP BY user_id
ORDER BY revenue DESC;
When You'll Hear This
"GROUP BY user_id to count how many orders each user has placed." / "I forgot the GROUP BY and got an aggregation error."
Related Terms
HAVING
HAVING is like WHERE but it filters after GROUP BY aggregation. WHERE filters rows before grouping, HAVING filters groups after.
ORDER BY
ORDER BY sorts your query results. Add DESC for newest first, ASC for oldest first.
SELECT
SELECT is how you ask a database to give you data. It is the 'Read' in CRUD.
Subquery
A subquery is a query inside a query. The inner query runs first and its result is used by the outer query.