Summary: in this tutorial, you will learn how to use the MariaDB distinct
to select distinct rows from a table.
Introduction to the MariaDB distinct option
A select
statement may return some identical rows. To explicitly specify that you want to remove duplicate rows from the result set, you use the distinct
option:
select
distinct column_name
from
table_name;
Code language: SQL (Structured Query Language) (sql)
In this syntax, the distinct
keyword appears after the select
keyword and before columns or expressions of the select list.
The query will return only distinct values from the column_name
in the table_name
.
The distinct
option can also be applied to multiple columns as shown in the following statement:
select
distinct column1, column2,...
from
table_name;
Code language: SQL (Structured Query Language) (sql)
In this case, the query will use the combinations of values in all the columns, which appear after the distinct
option, to evaluate the distinction of rows.
Note that if you want to select distinct values of some columns only, you use the group by
clause.
MariaDB distinct examples
We’ll use the country_stats
table from the nation
sample database for demonstration:
A) Using the MariaDB distinct with one column
The values in the year
column repeats for each country.
select
year
from
country_stats
order by
year;
Code language: SQL (Structured Query Language) (sql)
The following statement uses the distinct
option to select the distinct years from the the year
column:
select
distinct year
from
country_stats
order by
year desc;
Code language: SQL (Structured Query Language) (sql)
MariaDB distinct with null
In MariaDB, the distinct
option treats null
values the same. In other words, if you use the select distinct
to query data from a column that has null
values, the distinct
option will keep only one null
value.
See the countries
table from the sample database:
The following statement uses the distinct
option to select unique national days:
select
distinct national_day
from
countries;
Code language: SQL (Structured Query Language) (sql)
Even though, many rows have null
values in the national_day
column, the distinct option keeps only one value.
In this tutorial, you will learn how to use the MariaDB distinct
to select distinct rows from a table.