MySQL – ORDER BY values within IN()

SELECT id, name FROM mytable WHERE name IN (‘B’, ‘A’, ‘D’, ‘E’, ‘C’) ORDER BY FIELD(name, ‘B’, ‘A’, ‘D’, ‘E’, ‘C’) The FIELD function returns the position of the first string in the remaining list of strings. However, it is much better performance-wise to have an indexed column that represents your sort order, and then … Read more

How does PostgreSQL perform ORDER BY with a b-tree index on the field?

For a simple query like this Postgres will use an index scan and retrieve readily sorted tuples from the index in order. Due to its MVCC model Postgres had to always visit the “heap” (data pages) additionally to verify entries are actually visible to the current transaction. Quoting the Postgres Wiki on index-only scans: PostgreSQL … Read more