Explain the purpose of the DISTINCT keyword in SQL and provide an example.
Explain the purpose of the DISTINCT keyword in SQL and provide an example.
Student
Skilled in SEO, content writing, and digital marketing. Completed several years of working in many organizations including multinational companies. I love to learn new things in life that keep me motivated.
Sure. The DISTINCT keyword in SQL is used to remove duplicate rows from the result set of a SELECT statement. For example, let's say we have a table called
productswith the following columns:product_id(integer)product_name(string)price(decimal)If we run the following SELECT statement:
SQL
The result set will contain all of the rows in the
productstable, including any duplicate rows.To remove the duplicate rows, we can use the DISTINCT keyword:
SQL
This will return a result set that contains only the unique product names from the
productstable.Here is another example. Let's say we have two tables,
customersandorders:SQL
We can use the DISTINCT keyword to combine the results of a SELECT statement that queries the
customerstable with a SELECT statement that queries theorderstable, and remove any duplicate rows:SQL
This will return a result set that contains the unique names of all customers who have placed orders, along with the date of their most recent order.