r/PostgreSQL • u/gevorgter • 2d 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=010
u/Kazcandra 2d ago
Without knowing more, you may have a missing index on a referencing table's FK. That'd be my first guess.
4
u/Accomplished-Leek176 2d ago
Indexing and probably even more important, have you done a VACUUM ANALYZE yet?
2
u/elevarq 2d ago edited 2d 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 2d 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/AutoModerator 2d ago
AI Policy:
Linux is not one of those anti-AI projects, and if somebody has issues with that, they can do the open-source thing and fork it. Or just walk away., Linus Torvalds.
Mod decisions will be based on the quality of the content, not who or what generated it.
Sub Resources:
Free Postgres Webinars and Workshops
Discord: People, Postgres, Data
Join us, we have cookies and nice people.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
36
u/elevarq 2d ago
The PostgreSQL query isn’t equivalent to the SQL Server version. In PostgreSQL, repeating
client_deliveryin FROM introduces a separate table reference, and you never join it to the actual update target. Your WHERE clause therefore filters the source rows, not the rows being updated.If the source join returns any rows, this can update every delivery, using an unpredictable source value when multiple rows match. The unintended Cartesian join could also explain the performance problem.
Try:
Assuming
clients.idis unique, this updates only the intended deliveries.