ORDER BY is used to sort query results, while DISTINCT removes duplicate rows from the result set. These clauses help in organizing and cleaning data when querying tables.
ORDER BY sorts data in ascending or descending orderDISTINCT filters duplicate valuesSELECT statementsORDER BYORDER BY works after data retrieval, while DISTINCT works during data selection. They can be combined in a single query for refined results.
-- Sort employees by salary in ascending order
SELECT name, salary
FROM employees
ORDER BY salary ASC;
-- Get unique department names
SELECT DISTINCT department
FROM employees;
-- Use DISTINCT with ORDER BY together
SELECT DISTINCT department
FROM employees
ORDER BY department DESC;
The first query sorts employee records by salary from lowest to highest. The second query removes duplicate department names. The third query removes duplicates and then sorts the remaining values in descending order.
Imagine a table as a list of items: DISTINCT removes repeated items, and ORDER BY arranges the remaining items alphabetically or numerically.
ASC or DESC for clarityDISTINCT only when necessary to avoid performance issuesORDER BYWHERE, DISTINCT, and ORDER BY in one query