Hope you all are fine and doing good!
I have a table items with 2 million+ records the structure looks like below:
id (int) | price (decimal) | priority (int)
-------------------------------------------
10001 | 59000.25 | 1
10002 | 73000.91 | 2
10003 | 1000.23 | 1
10004 | 9567.18 | 1
The solution that I am looking for is very straightforward: How do I sort this table on price+priority on ASC|DESC order?
Current and working solution: I am using ORDER BY priority ASC, price ASC. But as far as my knowledge goes, sorting on multiple column is slow and not optimised approach (and I am facing realtime slowness because of this).
Solutions I tried: I've added a temporary column to this table:
id (int) | price (decimal) | priority (int) | new_priority (varchar)
--------------------------------------------------------------------
10001 | 59000.25 | 1 | a59000.25
10002 | 73000.91 | 2 | b73000.91
10003 | 1000.23 | 1 | a1000.23
10004 | 9567.18 | 1 | a9567.18
I've replaced 1 => a, 2 => b, 3 => c up till 10 (max number I have in database)
Now, whenever I am trying below SQLs, none of them is working
SELECT * FROM items
ORDER BY new_priority ASC
SELECT * FROM items
ORDER BY new_priority::bytea
SELECT * FROM items
ORDER BY SUBSTRING(new_priority FROM '^(.*?)( \\d+)?$'),
COALESCE(SUBSTRING(new_priority FROM ' (\\d+)$')::INTEGER, 0)
Please advise!
Links I referred:
limitandoffsetwill not help since in order to it work the database still do a full scan. The database need to know the total amount so it can know where to start/stop with the limit/offset clause. About the index it would be something likecreate index idx_blabla on yourTable (priority ASC, price ASC)And for reference read this: postgresql.org/docs/8.3/static/indexes-ordering.htmlexplain (analyze, verbose). Formatted text please, no screen shots