View video tutorial

MYSQL DISTINCT

MYSQL

The MySQL DISTINCT keyword is used to get only unique (non-duplicate) rows from a table.

MySQL DISTINCT


➔ DISTINCT eliminates redundant data, ensuring that each returned row is unique.

➔ The DISTINCT keyword is used in the SELECT clause.

➔ The DISTINCT keyword should appear immediately after the SELECT keyword.

➔ When multiple columns are specified, DISTINCT uses the combination of values ​​from all listed columns and finds uniqueness.

Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name
WHERE condition;
Customers table structure:
Field Type Null Key Default Extra
CustomerID int(11) NO PRI auto_increment
CustomerName varchar(255) YES
ContactName varchar(255) YES
Address varchar(255) YES
City varchar(255) YES
PostalCode varchar(255) YES
Country varchar(255) YES

Example

SELECT DISTINCT Country FROM Customers;

Copy the code, have practical experience in your environment and see how it works.


With multiple columns

➔ With multiple columns, DISTINCT finds unique combinations across all selected columns.

Example

/* DISTINCT on multiple columns. */
SELECT DISTINCT city, state
FROM customers
WHERE country = 'USA';

Copy the code, have practical experience in your environment and see how it works.


COUNT() Function

➔ DISTINCT can be used with COUNT() to count unique values.

Example

SELECT COUNT(DISTINCT Country) FROM Customers;

Copy the code, have a practical experience in your environment and see how it works.