What is the ORDER BY clause?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for MySQL / SQL development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

ORDER BY sorts the query result set by one or more columns. Syntax: ORDER BY column1 ASC, column2 DESC. ASC (ascending, default) — smallest to largest, A to Z, oldest to newest. DESC (descending) — largest to smallest, Z to A, newest to oldest. Sorting by multiple columns: ORDER BY last_name ASC, first_name ASC — sorts by last name first, then by first name within the same last name. Sort by position: ORDER BY 2 DESC — sorts by the second column in the SELECT list (works but fragile — column order can change). Sort by expression: ORDER BY LENGTH(name), ORDER BY price * quantity DESC. Sort by alias: SELECT price * 1.1 AS total ORDER BY total. Handling NULLs: MySQL sorts NULL values as lowest value (ASC puts NULLs first, DESC puts them last). ORDER BY RAND() — randomly shuffles results (slow on large tables — loads all rows, shuffles, then returns). ORDER BY is processed after SELECT, so you can order by computed columns or aliases.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.