Fetching Unique Results
Learn how to obtain unique records by using the DISTINCT keyword.
We'll cover the following...
The DISTINCT keyword
Let’s write a query to retrieve ProductCategories . Run the following query to show results:
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.
Let’s run the query below and see the results:
SELECT DISTINCT ProductCategory FROM SalesData
Note: When multiple fields are used with the
DISTINCTkeyword 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:
(True or False) The provided SQL query SELECT ProductName FROM SalesData will display only unique ProductName values.
True
False
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.
We need to consider the structure of the database and the necessary SELECT statement to achieve this goal.
-- Write your query here.