SQL ORDER-BY error

13 Jun 2013

I encountered an SQL error today:

“1st ORDER BY term does not match any column in the result set”

What caused this error?

What I did is I UNIONed two SELECT clauses and did an ORDER BY on the union of the two result sets. Obviously, the term(s) you used in the ORDER BY clause does not appear in the result sets it is applying to, which is the ‘unioned’ result sets. That is what gives this error.

Pay attention in the error: ORDER BY operates on the unioned result sets because ORDER BY executed AFTER the unioned result sets is created. If there is no UNION in the query, and ORDER BY only operates on the table being query, and if the terms in ORDER BY clause appear in the columns of the table but not in the columns being selected in the SELECT statement, then the same error will NOT occur because here ORDER BY operates on the table, and the terms exist in the table.