Suppose you are analyzing sales data. You want to identify the highest-value transactions.
SELECT customer_id, product_id, quantity, price,
quantity * price AS transaction_value
FROM sales
ORDER BY transaction_value DESC;
This can help with:
โข Finding high-value transactions
โข Identifying important customers
โข Investigating unusually large purchases
โข Preparing data for further analysis
๐น Common Mistakes
Mistake 1 โ Forgetting DESC
If you want the highest salary first:
ORDER BY salary DESC; Not ORDER BY salary;Mistake 2 โ Wrong column
Make sure the column used for sorting actually represents what you want to analyze.
Mistake 3 โ Incorrect multiple-column ordering
ORDER BY department, salary DESC; does NOT mean both columns are descending. It means: department โ ASC, salary โ DESCIf you want both descending:
ORDER BY department DESC, salary DESC;Mistake 4 โ Confusing WHERE and ORDER BY
WHERE filters rows. ORDER BY sorts rows. They perform different jobs.
๐น Interview Questions
1. What is ORDER BY?
ORDER BY sorts query results based on one or more columns.
2. What is the default sorting order?
Ascending order (ASC) is generally the default.
3. How do you find the highest salary?
SELECT * FROM employees ORDER BY salary DESC;
4. Can you sort using multiple columns?
Yes.
ORDER BY department ASC, salary DESC;5. What is the difference between ASC and DESC?
ASC sorts from low to high or AโZ. DESC sorts from high to low or ZโA.
๐ฏ Practice Questions
1. Write a query to display all products from the cheapest to the most expensive.
2. Write a query to display employees from the highest salary to the lowest salary.
3. Write a query to display customers alphabetically by name.
4. Write a query to sort sales by date, showing the newest sales first.
5. Write a query to sort employees by department alphabetically and salary from highest to lowest within each department.
๐ฏ Key Takeaways
โข ORDER BY sorts query results
โข ASC means ascending
โข DESC means descending
โข Ascending is generally the default
โข You can sort numbers, text and dates
โข You can sort using multiple columns
โข WHERE filters data; ORDER BY sorts data
โข ORDER BY is especially useful when analyzing rankings and top/bottom records
๐ Double Tap โค๏ธ For More