r/PostgreSQL • u/gevorgter • 29d 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
26
Upvotes
View all comments
41
u/elevarq 28d 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.