← Back to Chapters

MySQL ORDER BY & DISTINCT

? MySQL ORDER BY & DISTINCT

? Quick Overview

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.

? Key Concepts

  • ORDER BY sorts data in ascending or descending order
  • DISTINCT filters duplicate values
  • Both are used with SELECT statements
  • Multiple columns can be used in ORDER BY

? Syntax & Theory

ORDER BY works after data retrieval, while DISTINCT works during data selection. They can be combined in a single query for refined results.

? Code Examples

? View Code Example
-- Sort employees by salary in ascending order
SELECT name, salary
FROM employees
ORDER BY salary ASC;
? View Code Example
-- Get unique department names
SELECT DISTINCT department
FROM employees;
? View Code Example
-- Use DISTINCT with ORDER BY together
SELECT DISTINCT department
FROM employees
ORDER BY department DESC;

? Live Output / Explanation

Explanation

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.

? Interactive Concept

Imagine a table as a list of items: DISTINCT removes repeated items, and ORDER BY arranges the remaining items alphabetically or numerically.

? Use Cases

  • Sorting products by price
  • Listing unique cities from a customer table
  • Generating ordered reports
  • Cleaning duplicate query results

? Tips & Best Practices

  • Always specify ASC or DESC for clarity
  • Use DISTINCT only when necessary to avoid performance issues
  • Index columns used frequently in ORDER BY

? Try It Yourself

  • Write a query to sort students by marks in descending order
  • Find unique email domains from a users table
  • Combine WHERE, DISTINCT, and ORDER BY in one query