Database.Beginner.What is the purpose of DISTINCT?

DISTINCT is used to:

Remove duplicate rows from the result set.

  • It ensures that the output has only unique rows — no duplicates.
  • It compares all selected columns — if all columns in a row match, it’s considered a duplicate.

When Do You Use DISTINCT?

  • When you want to get only unique values.
  • When you want to avoid duplicates in your results.
  • When you’re doing reporting or analytics and you need clean, non-repeating data.

Example

Imagine a Products table:

product_idcategory
1Electronics
2Books
3Electronics
4Books
5Furniture

Without DISTINCT

SELECT category FROM Products;

Result:

category
Electronics
Books
Electronics
Books
Furniture

(You get duplicates.)


With DISTINCT

SELECT DISTINCT category FROM Products;

Result:

category
Electronics
Books
Furniture

Only unique categories are shown — duplicates are removed.

How DISTINCT Works

  • SQL compares all selected columns together.
  • If two rows are exactly the same in all selected columns, only one is kept.

Example with two columns

SELECT DISTINCT product_id, category FROM Products;

Now, it looks at the combination of product_id and category — if they’re unique together, the row stays.

Key Points

PointMeaning
Removes duplicatesReturns only unique rows.
Works on all selected columnsDuplicates are based on all selected columns.
Often used with COUNT(DISTINCT column)To count unique values.

Important Tip

  • DISTINCT is expensive for large datasets because SQL must sort or hash to find duplicates.
  • If you don’t need uniqueness, avoid it for better performance.

In Short

DISTINCT is used to remove duplicate rows and make your result set contain only unique rows.

This entry was posted in Без рубрики. Bookmark the permalink.