Quick revision
The short answer
A CASE expression has exactly one result type, so a CASE that returns name in one branch and created_at in another must reconcile text with a timestamp. PostgreSQL refuses and raises a type error, while MySQL converts both to a string and sorts dates as text. The fix is one CASE per type, ORDER BY CASE WHEN :sort = 'name' THEN name END, CASE WHEN :sort = 'created' THEN created_at END, or better, building ORDER BY from a whitelist in Java.
What to remember
In this answer, we saw that a CASE has one result type chosen at planning time, so mixing text and timestamptz branches fails in PostgreSQL and quietly becomes string sorting in MySQL. Splitting the sort into one CASE per column and type fixes the type problem, with a tiebreaker for stable pages, but it still prevents index use for the sort. Building the ORDER BY from a whitelist of fixed fragments is usually the better design, and the user's value must never be concatenated into SQL.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A CASE expression has exactly one result type, so a CASE that returns name in one branch and created_at in another must reconcile text with a timestamp. PostgreSQL refuses and raises a type error, while MySQL converts both to a string and sorts dates as text. The fix is one CASE per type, ORDER BY CASE WHEN :sort = 'name' THEN name END, CASE WHEN :sort = 'created' THEN created_at END, or better, building ORDER BY from a whitelist in Java.
Why this question is asked
Sortable tables in an API are everywhere, and many teams try to keep one static SQL statement by putting the sort choice inside a CASE. It works until two sortable columns have different types. Interviewers like this bug because the same query fails loudly in one database and quietly misbehaves in another, and because the obvious quick fix, concatenating the user's value into SQL, opens an injection hole. In this answer, we will recap how CASE decides its type, reproduce the two failures, apply the one-CASE-per-type fix, look at what it does to index use, and build the safer whitelist version in Java.
1A Quick Recap of How CASE Gets Its Type
Every expression in SQL has one data type, decided when the query is planned, before any row is read. A CASE expression is no exception: the database looks at the result of every THEN and ELSE branch and picks a single type that all of them can be converted to. It cannot choose a type per row, because the sort, the comparison operators and the output column must all know in advance what kind of value they handle.
Each database has its own rules for this. PostgreSQL only unifies types that have an implicit conversion between them, such as integer and numeric, and otherwise raises an error. MySQL is more lenient and falls back to a string type when the branches mix strings and temporal values.
2Reproducing the Two Failures
Here is the query, with :sort coming from the API request.
In PostgreSQL the error appears even when :sort is 'name', because the type check happens at planning time for the whole expression, not for the branch that will be used.
In MySQL the query runs, and the CASE result type becomes a character string. created_at is converted to text and the rows are compared as strings, under the string collation. A DATETIME rendered in the standard YYYY-MM-DD hh:mm:ss form happens to sort in date order as text, but the comparison is now string comparison: slower, collation dependent, and wrong as soon as a branch holds numbers ('100' sorts before '20') or a value is formatted differently. The answer we want is not to rely on that luck.
3Fix 1: One CASE Per Type
The usual fix is to give each sortable column its own CASE in ORDER BY. Each CASE has only one non-NULL branch, so each has a single clear type.
| Request | Key 1: name CASE | Key 2: created CASE | Key 3 |
|---|---|---|---|
| sort=name | name | NULL for all rows | id |
| sort=created | NULL for all rows | created_at | id |
| anything else | NULL | NULL | id |
The trick is that a CASE without ELSE returns NULL when its condition is false. When the user sorts by name, the second sort key is NULL for every row, so it has no effect, and the reverse holds for created. The final id is a tiebreaker, so rows with equal names come back in a stable order across pages; without it, pagination can repeat or skip rows.
Sort direction needs the same treatment, because DESC cannot be parameterised. We add one CASE per column and direction, such as CASE WHEN :sort = 'created' AND :dir = 'desc' THEN created_at END DESC. With five columns and two directions that is ten expressions, which shows the limit of this approach.
4What the CASE Does to Index Use
A B-tree index on created_at stores rows already sorted by created_at, so for ORDER BY created_at LIMIT 20 the database can read the first 20 index entries and stop. An expression like CASE WHEN :sort = 'created' THEN created_at END is not the indexed column; it is a computed value. Most planners will read all matching rows, compute the CASE for each, and sort them. On a table of a few thousand rows this does not matter. On ten million rows it turns a 2 millisecond page into a multi-second sort for every request.
This is the stronger reason to prefer dynamic SQL built safely: with ORDER BY created_at DESC, id DESC spelled out, the planner can use an index on (created_at, id) and stop after one page.
5Fix 2: Build ORDER BY From a Whitelist
Column names and directions cannot be bind parameters, so the tempting shortcut is to paste the request value into the SQL string. That is SQL injection: a value such as created_at; DROP TABLE customers -- or a subquery in the sort clause can run arbitrary SQL. The safe version maps the allowed values to fixed SQL fragments and rejects anything else.
Only strings from our own map can ever reach the SQL, so the user's input chooses among fixed options instead of being executed. In Spring Data, a Pageable with a Sort does the same job, but we should still check the requested property against an allowed list, because sorting on an arbitrary property can expose columns or produce slow queries. Each distinct ORDER BY produces a distinct statement, which is fine: there are only a handful of combinations, and each gets its own good plan.
6Follow-up questions
Can I keep a single CASE by casting everything to text?
It removes the error, but it makes the bug of MySQL deliberate: dates and numbers are compared as strings, numbers sort as '10' before '9', and no index can help. Casting timestamps to a fixed sortable format works for dates alone, but it is fragile and still slow. Separate CASEs or a whitelist are cleaner.
Why does PostgreSQL fail even when :sort is 'name'?
Because the query is planned before the parameter decides which branch runs, and a plan must know the type of every expression. The planner sees text in one branch and timestamptz in another and cannot pick one type, so it refuses the whole statement.
Where do NULLs go in the sort?
In PostgreSQL, NULLs sort last in ascending order and first in descending order, and NULLS FIRST or NULLS LAST overrides that. MySQL puts NULLs first in ascending order. A sortable column that can hold NULLs should state the intended place explicitly so pages look the same across databases.
7Conclusion
In this answer, we saw that a CASE has one result type chosen at planning time, so mixing text and timestamptz branches fails in PostgreSQL and quietly becomes string sorting in MySQL. Splitting the sort into one CASE per column and type fixes the type problem, with a tiebreaker for stable pages, but it still prevents index use for the sort. Building the ORDER BY from a whitelist of fixed fragments is usually the better design, and the user's value must never be concatenated into SQL.
Open with
The problem is that a CASE expression has a single result type, decided when the query is planned. Here one branch returns name, which is text, and the other returns created_at, a timestamp with time zone.
Then, if they want more
PostgreSQL has no implicit conversion between them, so it raises an error saying the CASE types cannot be matched, even when the parameter is 'name'. MySQL is lenient and converts the whole CASE to a string, so the dates are compared as text under a collation, which is slower and only right by accident of the format.
The quick fix is one CASE per column: ORDER BY CASE WHEN sort is 'name' THEN name END, then CASE WHEN sort is 'created' THEN created_at END, then id as a tiebreaker. A CASE without ELSE gives NULL for every row when it is not selected, so only one key really sorts.
Direction needs its own CASEs, since DESC cannot be a parameter. But a CASE in ORDER BY usually stops the planner from using an index for the sort, so on big tables every page becomes a full sort.
What I would actually do is build the ORDER BY in Java from a whitelist map of allowed sort names to fixed column names, reject anything else, and never concatenate the user's value into the SQL, because that is an injection hole.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A query uses ORDER BY CASE WHEN :sort = 'name' THEN name WHEN :sort = 'created' THEN...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/57e12d97c4/