D
D
dailysse2017-04-26 11:24:24
PostgreSQL
dailysse, 2017-04-26 11:24:24

Database query?

Good day. db structure:

CREATE TABLE testTable (
    id              serial,
    date          int,
    testField1 smallint,
    testField2 real,
    val            smallint,
    PRIMARY KEY(id)
);

I need to select the last record by date grouped by testField1 and testField2 and then add the val values ​​grouped by testField1
Query:
SELECT SUM(val), testField1 FROM (
    SELECT DISTINCT ON (testField1, testField2) testField1, testField2, val FROM testtable ORDER BY testField1, testField2, date DESC
) t1 GROUP BY testField1

Everything works well and gives the result I need, but if the request is needed with conditions like:
SELECT SUM(val), testField1 FROM (
    SELECT DISTINCT ON (testField1, testField2) testField1, testField2, val FROM testtable ORDER BY testField1, testField2, date DESC
) t1 where testField1 in (1,5,50,10,19) and testField2 in (5,8,10,13) GROUP BY testField1

That request is executed by an order of magnitude more.
index:
CREATE INDEX testIndex on testtable (testField1, testField2, date desc)

So here's how you can optimize it and make those fetches faster. There are about 10 million documents in the database. And it's constantly growing. testField1 from 1 to 1500, testField2 from 1 to 1500. Postgresql 9.6.2 database. Thanks in advance for your reply

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Max, 2017-04-26
@MaxDukov

EXPLAIN (ANALYZE, BUFFERS) says what?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question