totn MariaDB

MariaDB: DISTINCT Clause

This MariaDB tutorial explains how to use the MariaDB DISTINCT clause with syntax and examples.

Description

The MariaDB DISTINCT clause is used to remove duplicates from the results of a SELECT statement.

Syntax

The syntax for the DISTINCT clause in MariaDB is:

SELECT DISTINCT expressions
FROM tables
[WHERE conditions];

Parameters or Arguments

expressions
The columns or calculations that you wish to retrieve.
tables
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Optional. The conditions that must be met for the records to be selected.

Note

  • When only one expression is provided in the DISTINCT clause, the query will return the unique values for that expression.
  • When more than one expression is provided in the DISTINCT clause, the query will return unique combinations for the multiple expressions listed.
  • In MariaDB, the DISTINCT clause doesn't ignore NULL values. So when using the DISTINCT clause in your SQL statement, your result set will include NULL as a distinct value.

Example - With Single Expression

Let's look at the how to use the DISTINCT clause to remove duplicates from a single expression in MariaDB

For example:

SELECT DISTINCT site_id
FROM sites
WHERE site_name = 'TechOnTheNet.com';

This MariaDB DISTINCT example would return all unique site_id values from the sites table where the site_name is 'TechOnTheNet.com'.

Example - With Multiple Expressions

Let's look at how to use the DISTINCT clause to remove duplicates from more than one expression in MariaDB.

For example:

SELECT DISTINCT site_name, server_name
FROM sites
WHERE site_id < 30
ORDER BY site_name ASC, server_name DESC;

This DISTINCT clause example would return each unique site_name and server_name combination from the sites table. In this case, the DISTINCT applies to each field listed after the DISTINCT keyword, and therefore returns distinct combinations. The results are then sorted in ascending order by site_name and then descending_order by server_name.