Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL/mysql - Select distinct/UNIQUE but return all columns?

SELECT DISTINCT field1, field2, field3, ......   FROM table 

I am trying to accomplish the following sql statement but I want it to return all columns is this possible? Something like:

SELECT DISTINCT field1, * from table 
like image 381
aryaxt Avatar asked May 25 '11 15:05

aryaxt


People also ask

Does SELECT distinct apply to all columns?

Yes, DISTINCT works on all combinations of column values for all columns in the SELECT clause.

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

To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.

Can you use SELECT and SELECT distinct in SQL?

The SQL SELECT DISTINCT StatementThe DISTINCT clause is used in a SELECT statement to remove duplicates from the result set of the query.

What will happen if you apply distinct on whole table?

Adding the DISTINCT keyword to a SELECT query causes it to return only unique values for the specified column list so that duplicate rows are removed from the result set.


1 Answers

You're looking for a group by:

select * from table group by field1 

Which can occasionally be written with a distinct on statement:

select distinct on field1 * from table 

On most platforms, however, neither of the above will work because the behavior on the other columns is unspecified. (The first works in MySQL, if that's what you're using.)

You could fetch the distinct fields and stick to picking a single arbitrary row each time.

On some platforms (e.g. PostgreSQL, Oracle, T-SQL) this can be done directly using window functions:

select * from (    select *,           row_number() over (partition by field1 order by field2) as row_number    from table    ) as rows where row_number = 1 

On others (MySQL, SQLite), you'll need to write subqueries that will make you join the entire table with itself (example), so not recommended.

like image 196
Denis de Bernardy Avatar answered Sep 16 '22 22:09

Denis de Bernardy