Search⌘ K
AI Features

Fetching Unique Results

Explore how to use the DISTINCT keyword in SQL to extract unique values from query results. Understand how DISTINCT works with single and multiple fields to filter duplicates, and practice generating lists with unique entries, such as unique salespersons, to improve your data retrieval skills.

The DISTINCT keyword

Let’s write a query to retrieve ProductCategories . Run the following query to show results:

MySQL
SELECT ProductCategory FROM SalesData

It extracts the ProductCategory names from all records. Notably, the result set displays numerous repeated product categories, a typical occurrence where a table column often contains duplicate values. Sometimes, our interest lies only in obtaining a list of unique (distinct) values. To achieve this, we utilize the DISTINCT keyword in our SQL query.

Demonstration of the use of DISTINCT
Demonstration of the use of DISTINCT

Let’s run the query below and see the results:

MySQL
SELECT DISTINCT ProductCategory FROM SalesData

Note: When multiple fields are used with the DISTINCT keyword in SQL, it combines the unique combinations of those fields together. It ensures that the combination of values across those specified fields is distinct in the result set. In other words, it retrieves unique combinations of values across all the specified fields, rather than distinct values from each individual field.

Let’s answer the following question:

Technical Quiz
1.

(True or False) The provided SQL query SELECT ProductName FROM SalesData will display only unique ProductName values.

A.

True

B.

False


1 / 1

Task 1: Generate a list of salespersons

Let’s produce our first report for the project. For this task, we’ll write an SQL query that retrieves distinct salesperson names from the database. Our query should aim to display a unique list of salespersons, ensuring that each name appears only once in the result set.

Report 1: List of salespersons
Report 1: List of salespersons

We need to consider the structure of the database and the necessary SELECT statement to achieve this goal.

MySQL
-- Write your query here.