Module 01 · lesson 5

DISTINCT: removing duplicates

For the site's menu the founder needs a list of categories — each one once. But in the table a category repeats as many times as there are products in it.

The duplicate problem

The GadgetHub catalog has two products named Cotton T-Shirt — different batches, different ids, but the same name. If you just output the names:

SELECT name
FROM products;

…then Cotton T-Shirt shows up in the list twice. For a menu or a filter that's redundant — you need unique values.

DISTINCT

The keyword DISTINCT removes repeated rows, leaving only the unique ones. It goes right after SELECT:

SELECT DISTINCT name
FROM products;

Now Cotton T-Shirt is a single row. A few details:

  • DISTINCT applies to the whole combination of listed columns (the entire combination must be unique).
  • All NULLs are treated as one value — collapsed into a single row.

SELECT category category Electronics Electronics Clothing Electronics Clothing Home DISTINCT прибирає повториremoves duplicates quita duplicados SELECT DISTINCT category category Electronics Clothing Home

Your turn

The site menu needs the categories, each one once. Output a list of the unique categories.

Summary

  • DISTINCT returns unique values (handy for lists of categories, cities, statuses, and so on).
  • All NULLs count as one value.