r/PostgreSQL • • 25d ago

Help Me! Query optimization

Moving my project from MS Sql to PostrgesSql,

Need to run mass update query, ClientDelivery table has 1,054,155 records

In MsSql query takes about 10 seconds, In PostgresSql it actually never finishes because i am canceling it after waiting for 5 minutes. Records are identical in both databases. I am running queries in PgAdmin and SqlManagment client.

Any reason for such huge difference? I understand i am doing table scan but 1 million records is not that much.

/*MSSQL*/
UPDATE tblClientDelivery
SET routeId=t1.routeId
FROM tblClientDelivery t
INNER JOIN tblClients t1 ON t.clientId=t1.id
WHERE t.routeId=0

/*PostgreSql*/
UPDATE client_delivery
SET route_id=t1.route_id
FROM client_delivery t
INNER JOIN clients t1 ON t.client_id=t1.id
WHERE t.route_id=0
27 Upvotes

17 comments sorted by

View all comments

Show parent comment

2

u/elevarq 25d ago edited 25d ago

Why VACUUM ANALYZE? That solves a different problem, when autovacuum has not been configured for your workload.

And it doesn't solve the real problem: an UPDATE that is just wrong.

3

u/Accomplished-Leek176 25d ago

If you have a large table and don’t generate stats, the query planner just does a full scan every time. You can run ANALYZE independently, but I just always run it with a manual vacuum, two birds one statement.

1

u/elevarq 25d ago

And that can only happen when you turn OFF autovacuum... That's like driving your car into a tree and then complaining about the scratches.

If you need a manual VACUUM, something is wrong.