MySQL Wildcards

MySQL Wildcards

MySQL Aliases

MySQL Aliases

MySQL Data Types

MySQL Data Types

MySQL Interview Questions

MySQL Interview Questions and Answers


MySQL Distinct Clause

The MySQL DISTINCT clause is used to eliminate duplicate records from the table and retrieve only unique records. The MySQL DISTINCT clause is used with the SELECT statement only.

Note: In MySQL, the DISTINCT clause doesn't ignore NULL values.

MySQL DISTINCT CLAUSE Syntax

To retrieve only unique records from existing table, use the following syntax:

Syntax

SELECT DISTINCT col1,col2,col3... FROM tablename

Parameters:

tablename: The table name from which you want to remove all records.

DISTINCT: To eliminate duplicate records.

Note:

If DISTINCT clause is used with single field, the query will return the unique values for that field only.

If DISTINCT clause is used with multiple fields, the query will retrieve unique combinations for the expressions listed.

MySQL DISTINCT CLAUSE example with single field

The following MySQL statement to retrieve single field with unique records from "tblCustomer" table:

Example

SELECT DISTINCT address FROM tblCustomerLoan;

Note:

In the above example, we have fetched unique "address" from "tblCustomerLoan"

You can use MySQL Command Line Client to fetched unique records from "tblCustomerLoan" table. It will look like this:

Show DISTINCT CLAUSE Example with multiple fields

To retrieve unique records for multiple fields from existing table, use the following syntax:

Example

SELECT DISTINCT address, cellNo, aadharNo FROM tblCustomerLoan; 

You can use MySQL Command Line Client to retrieve unique records for multiple fields in table. It will look like this:

Show DISTINCT CLAUSE Example with NULL value

To retrieve unique records for NULL value, MySQL keeps one NULL value and eliminates the other because the DISTINCT clause treats all NULL values as the same value, use the following syntax:

Example

SELECT DISTINCT firstName FROM tblCustomerLoan; 

You can use MySQL Command Line Client to retrieve unique records for NULL values in table. It will look like this: