Column must appear in the GROUP BY clause or be used in an aggregate function when using CASE statement in ORDER BY clause I have a PostgreSQL database that contains events. Events can have multiple date ranges. Date ranges are stored in a separate table. I’d like to get the IDs of current and upcoming events. IDs of current events should be outputted first, followed by IDs of upcoming events.

This is my current SQL query: 

SELECT date_ranges.event_id
FROM date_ranges
WHERE date_ranges.through_date &gt;= current_date
GROUP BY date_ranges.event_id
ORDER BY CASE WHEN date_ranges.from_date &lt;= current_date THEN 1 ELSE 2 END ASC;


However, it doesn’t work:

ERROR:  column "date_ranges.from_date" must appear in the GROUP BY clause or be used in an aggregate function
LINE 5: ORDER BY CASE WHEN date_ranges.from_date &lt;= current_date THE...


How can I work around this problem in this case?
If all events have the same from_date:

SELECT event_id
FROM   date_ranges
WHERE  through_date &gt;= current_date
GROUP  BY event_id, from_date  --  add it to GROUP BY
ORDER  BY from_date &gt; current_date; -- simplified expression (assuming NOT NULL)


But then the column should be in the event table once per event.

If not, your sort order is ambiguous. I would start by asking how the same event can have different date ranges?

Your setup is broken either way.