Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate rows on a SQL query [duplicate]

Possible Duplicate:
Duplicate result
Interview - Detect/remove duplicate entries

I have a SQL Query, which returns a table with one column.

The returned data may be duplicate. for example, my query may be something like:

SELECT item FROM myTable WHERE something = 3

and the returned data may be something like this:

item
-----
2
1
4
5
1
9
5

My Question is, How to remove duplicated items from my query?

I mean, I want to get these results:

item
-----
2
1
4
5
9

Please note that I don't want to change or delete any rows in table. I just want to remove duplicates in that query.

How to do that?

like image 623
Mahdi Ghiasi Avatar asked Nov 28 '22 02:11

Mahdi Ghiasi


2 Answers

SELECT DISTINCT item FROM myTable WHERE something = 3
like image 113
DJ Quimby Avatar answered Dec 17 '22 18:12

DJ Quimby


As noted, the distinct keyword eliminates duplicate rows—where the rows have identical values in column—from the result set.

However, for a non-trivial query against a properly designed database, the presence of duplicate rows in the result set — and their elimination via select distinct or select ... group by is, IMHO, most often a "code smell" indicating improper or incorrect join criteria, or a lack of understanding of the cardinalities present in relationships between tables.

If I'm reviewing the code, select distinct or gratuitous group by without any obvious need present will get the containing query flagged and that query gone over with a fine toothed comb.

like image 28
Nicholas Carey Avatar answered Dec 17 '22 20:12

Nicholas Carey