Consider the table Employees with columns Department and Salary. What will be the order of rows returned by this query?
SELECT * FROM Employees ORDER BY Department ASC, Salary DESC;
CREATE TABLE Employees (Name VARCHAR(20), Department VARCHAR(20), Salary INT); INSERT INTO Employees VALUES ('Alice', 'Sales', 5000), ('Bob', 'Sales', 6000), ('Charlie', 'HR', 5500), ('David', 'HR', 5200); SELECT Name, Department, Salary FROM Employees ORDER BY Department ASC, Salary DESC;
Rows are sorted first by Department alphabetically, then by Salary in descending order within each department.
The query orders rows by Department ascending (HR before Sales). Within each department, rows are ordered by Salary descending. So HR rows come first with Charlie (5500) before David (5200), then Sales rows with Bob (6000) before Alice (5000).
When you use ORDER BY with multiple columns, how does the database sort the rows?
Think about sorting a list of people by last name, then first name.
The database sorts rows first by the first column listed in ORDER BY. If two rows have the same value in that column, it uses the second column to decide their order, and so on for additional columns.
Choose the correct SQL query that orders Products by Category ascending and Price descending.
Check the correct keywords for ascending and descending order in SQL.
The correct keywords are ASC for ascending and DESC for descending. The other options use invalid keywords like DESCENDING or ASCENDING.
You have a large table Orders with columns CustomerID and OrderDate. You often run:
SELECT * FROM Orders ORDER BY CustomerID ASC, OrderDate DESC;
Which index will best improve this query's performance?
Indexes should match the order of columns in the ORDER BY clause.
An index on (CustomerID ASC, OrderDate DESC) matches the ORDER BY clause exactly, allowing the database to retrieve rows in the desired order efficiently. Other indexes either have columns in wrong order or only cover one column.
Given the table Students with columns Name, Grade, and Age, a developer runs:
SELECT * FROM Students ORDER BY Grade, Age DESC;
But the results are not sorted by Grade ascending as expected. What is the most likely cause?
Think about how NULL values affect sorting order.
By default, NULL values in Grade appear first when sorting ascending, which can make it seem like sorting is incorrect. The syntax is valid, and the database does not ignore columns in ORDER BY. The table having no data would return no rows, not unexpected order.