Back to cookbooks list Articles Cookbook

How to Use DISTINCT in SQL

Problem:

You’d like to query your data to return the result without duplicate rows.

Example:

Our database has a table named books with data in the columns author_firstname, author_lastname, and book_title. You’d like to get a list of unique first and last names of the authors.

author_firstnameauthor_lastnamebook_title
GeorgeOrwellAnimal Farm
DanBrownThe Davinci Code
GeorgeOrwell1984
DanielSilvaThe Order
FranzKafkaThe Metamorphosis

Solution:

We’ll use the DISTINCT clause. Here’s the query:

SELECT DISTINCT
   author_firstname,
   author_lastname
FROM books;

Here’s the result of the query:

author_firstnameauthor_lastname
GeorgeOrwell
DanBrown
DanielSilva
FranzKafka

Discussion:

The DISTINCT clause is used in the SELECT statement to filter out duplicate rows in the result set. You can use DISTINCT when you select a single column, or when you select multiple columns as we did in our example.

Recommended courses:

Recommended articles:

See also: