• NostraDavid@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    4 days ago

    Here’s my quick guide to fixing slow queries:

    1. grab your query.
    2. run EXPLAIN ANALYZE <query>
    3. If there’s a Parallel Seq Scan, check the Filter value (which column are we checking) - you should likely try adding an index.
    4. run CREATE INDEX ON <table>(<column>);
    5. run EXPLAIN ANALYZE <query> again to check for improvements

    Note that EXPLAIN <query> will only do a rough analysis, while EXPLAIN ANALYZE <query> will run your actual query, and analyse it.

    If you want to ANALYSE EXPLAIN an INSERT query, do this:

    BEGIN;
    EXPLAIN ANALYZE INSERT ...;
    ROLLBACK;
    

    A simple ROLLBACK will help you here.

    Rewriting the query will typically not do much - it might, but the chance it relatively small vs slapping an index on it.