Video in progress

Which columns can you put in the SELECT list when you use GROUP BY?

Only the columns listed in GROUP BY and aggregate functions (count, sum, max...). If you list any other column, PostgreSQL raises an error, because it doesn't know which of the group's values of that column to take.

📖 Answer

-- error: column "o.created_at" must appear in the GROUP BY clause...
SELECT user_id, created_at, sum(total)
FROM orders
GROUP BY user_id;

One user has 10 orders, so created_at has 10 different values. Which one should it show? The database won't guess.

The correct versions depend on what you need:

SELECT user_id, max(created_at) AS last_order, sum(total)
FROM orders
GROUP BY user_id;

There is one exception: if you GROUP BY the primary key, PostgreSQL also allows the other columns of that table, since they are functionally dependent on the PK.

SELECT u.id, u.email, count(o.id)
FROM users u LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id;   -- u.email is allowed too, because u.id is the PK

In old MySQL versions such a query ran without an error and returned an arbitrary value. People who bring that habit to PostgreSQL trip on this a lot.