Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Distinct for 2 columns in SQL query

If I have a table such as

1 bob
1 ray
1 bob
1 ray
2 joe
2 joe

And I want to select distinct based on the two columns so that I would get

1 bob
1 ray
2 joe

How can I word my query? Is the only way to concatenate the columns and wrap them around a distinct function operator?

like image 358
Matt Avatar asked Sep 09 '10 19:09

Matt


People also ask

How can I get distinct values of two columns in SQL?

To select distinct values in two columns, you can use least() and greatest() function from MySQL.

Can we use distinct in two columns in SQL?

Answer. Yes, the DISTINCT clause can be applied to any valid SELECT query. It is important to note that DISTINCT will filter out all rows that are not unique in terms of all selected columns.

Can we use distinct for multiple columns?

The DISTINCT clause is used in the SELECT statement to remove duplicate rows from a result set. The DISTINCT clause keeps one row for each group of duplicates. The DISTINCT clause can be applied to one or more columns in the select list of the SELECT statement.

How does distinct work in SQL with multiple columns?

In SQL multiple fields may also be added with DISTINCT clause. DISTINCT will eliminate those rows where all the selected fields are identical.


1 Answers

select distinct id, name from [table]

or

select id, name from [table] group by id, name
like image 141
Denis Valeev Avatar answered Oct 01 '22 16:10

Denis Valeev