Search code examples
sqlpostgresqlduplicateswhere-clause

PostgreSQL - Want SELECT/FROM/WHERE/IN query to return ALL values correlated to search terms. Even if duplicate


By default, PostgreSQL returns just the distinct values for a SELECT/FROM/WHERE/IN query. What do I need to do to get the number of results to match the number of input fields?

How can I achieve this?

Example:

SELECT ALL "letter" 
FROM "letters" 
WHERE id IN ('1', '2', '3', '4', '1', '2')

This will result in the following: 'A', 'B', 'C', 'D'

This is what I'm looking for the result to be: 'A', 'B', 'C', 'D', 'A', 'B'


Solution

  • You need to use a JOIN, which will return one row for each matched parameter.

    select l.letter
    from letters l
      join (
         values (1),(2),(3),(4),(1),(2)
      ) as t(id) on t.id = l.id