1

I have an operation which gives me a list of IDs and some score related to these IDs. Then I need query the database and sort rows using the data above.

I tried something like (I'm using PostgreSQL):

SELECT * FROM sometable
LEFT OUTER JOIN (VALUES (629, 3), (624, 1))  /* Here is my data */
AS x(id, ordering)
USING (id)
WHERE some_column_id=1
ORDER BY x.ordering;

But for ~10000 rows it runs about 15sec on my machine. Is there a better way to sort my table using a previously calculated data?

4
  • A case expression in the ORDER BY? Commented Jul 6, 2016 at 14:04
  • @jarlh will it be OK for say ~1000 clauses in the CASE expression? Commented Jul 6, 2016 at 14:06
  • If that many, consider a help table! Commented Jul 6, 2016 at 14:08
  • Write the ids and ordering into a temporary table (if they are not already in a table). Add an index on id and run the query. Commented Jul 6, 2016 at 14:10

1 Answer 1

1

What is the performance of this version?

SELECT st.*
FROM sometable st
WHERE st.some_column_id = 1
ORDER BY (CASE WHEN st.id = 629 then 3 WHEN st.id = 624 THEN 1 END);

An index on sometable(some_column_id) might also speed the query.

However, I don't understand why your version on a table with 10,000 rows would take 15 seconds.

Sign up to request clarification or add additional context in comments.

3 Comments

Well, I tried my and your solution on another database with even more rows, and this works pretty fast, seems like an issue with my local database... (There already is an index on some_column_id).
Will it be executing slow if there will be about ~1000 cases?
@coldmind . . . That would probably slow it down considerably. You should probably use a (temp) table with an index.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.