I am trying to use a CASE expression in the ORDER BY clause of my SQL statement, but I want to order by more than one column. I keep getting a "missing keyword" error when I try to compile this.
ORDER BY CASE WHEN sortorder = 1 THEN x WHEN sortorder = 2 THEN x,y END;
"sortorder" is a variable I pass in, by the way.
ORDER BY x , ... something for sortorder 2
Now the only thing to worry about is sortorder 2. This requires that the rows be in sequence by the "y" column values within each "x" value.
But what if we simply do this:
ORDER BY x , y
Let's recap. If sortorder is 2, then the rows will be in sequence by "y" within "x," and we're all set, right? But if sortorder is 1, then the rows will also be in sequence by "y" within "x," but for sure they'll be in sequence by "x." So that's okay too, right?
You don't need a CASE expression at all.
Dig Deeper on Oracle and SQL
Related Q&A from Rudy Limeback
Read an example of an SQL case expression from our SQL expert Rudy Limeback. Continue Reading
Read SQL expert Rudy Limeback's advice for counting combinations in a table with SQL's GROUP BY clause Continue Reading
Read about the Mimer Validator, a tool used to verify your SQL code, in this tip from SQL expert Rudy Limeback. Continue Reading