4

I want to remove duplicate rows return from a SELECT Query in Postgres

I have the following query

SELECT DISTINCT name FROM names ORDER BY name

But this somehow does not eliminate duplicate rows?

Milen A. Radev
  • 60,241
  • 22
  • 105
  • 110
Elitmiar
  • 35,072
  • 73
  • 180
  • 229

4 Answers4

10

PostgreSQL is case sensitive, this might be a problem here DISTINCT ON can be used for case-insensitive search (tested on 7.4)

SELECT DISTINCT ON (upper(name)) name FROM names ORDER BY upper(name);
ymv
  • 2,123
  • 13
  • 21
1

Maybe something with same-looking-but-different characters (like LATIN 'a'/CYRILLIC 'а')

ymv
  • 2,123
  • 13
  • 21
1

Don't forget to add a trim() on that too. Or else 'Record' and 'Record ' will be treated as separate entities. That ended up hurting me at first, I had to update my query to:

SELECT DISTINCT ON (upper(trim(name))) name FROM names ORDER BY upper(trim(name));
Nick Poulos
  • 449
  • 3
  • 19
0

In Postgres 9.2 and greater you can now cast the column to a CITEXT type or even make the column that so you don't have to cast on select.

SELECT DISTINCT name::citext FROM names ORDER BY name::citext
JT Turner
  • 502
  • 2
  • 14