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.
288
30-Jun-2023
Updated on 02-Jul-2023
Aryan Kumar
02-Jul-2023Sure. 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.