2

I'm trying to write a query to retrieve exactly two rows from a table using the same column for identification.

SELECT * FROM teams WHERE name = $1 OR name = $2;

Is there any way to ensure that the result for name = $1 is the first result returned and name = $2 is the second?

0

2 Answers 2

3
SELECT * 
FROM teams 
WHERE name IN ($1, $2)
ORDER BY CASE WHEN name = $1 THEN 0 ELSE 1 END;
2

Another way would be to arrange the arguments and their respective sorting values as a (derived) table, join that table and use the sorting column in ORDER BY:

SELECT
  t.*
FROM
  teams AS t
  INNER JOIN
    (
      SELECT $1 AS name, 1 AS sort
      UNION ALL
      SELECT $2 AS name, 2 AS sort
    ) AS s ON t.name = s.name
ORDER BY
  s.sort ASC
;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.