Sure. The DISTINCTkeyword 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
products with the following columns:
product_id (integer)
product_name (string)
price (decimal)
If we run the following SELECT statement:
SQL
SELECT * FROM products;
The result set will contain all of the rows in the products table, including any duplicate rows.
To remove the duplicate rows, we can use the DISTINCT keyword:
SQL
SELECT DISTINCT product_name FROM products;
This will return a result set that contains only the unique product names from the
products table.
Here is another example. Let's say we have two tables, customers and
orders:
SQL
CREATE TABLE customers (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE orders (
id INT NOT NULL AUTO_INCREMENT,
customer_id INT NOT NULL,
order_date DATETIME NOT NULL,
total_amount DECIMAL(10,2) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (customer_id) REFERENCES customers (id)
);
We can use the DISTINCT keyword to combine the results of a SELECT statement that queries the
customers table with a SELECT statement that queries the orders table, and remove any duplicate rows:
SQL
SELECT DISTINCT customers.name, orders.order_date
FROM customers
INNER JOIN orders
ON customers.id = orders.customer_id;
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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
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.