r/PostgreSQL • • 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

17 comments sorted by

View all comments

41

u/elevarq 28d ago

The PostgreSQL query isn’t equivalent to the SQL Server version. In PostgreSQL, repeating client_delivery in 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:

UPDATE client_delivery AS d
SET route_id = c.route_id
FROM clients AS c
WHERE d.client_id = c.id
  AND d.route_id = 0;

Assuming clients.id is unique, this updates only the intended deliveries.

6

u/gevorgter 28d ago

Thanks, you got it right. Rewrote my query as you suggested and it worked (comparable to mssql now).

And I thought i know sql pretty well :)

13

u/elevarq 28d ago

The problem with SQL is that the syntax for UPDATE and DELETE differs by database engine when using more than one table. To my knowledge, there is no ISO standard for this, so each vendor implemented it however they liked.

4

u/marr75 28d ago

Not that an ISO standard would have prevented most vendors from implementing it however they liked anyway ;)

2

u/raks1991 23d ago

One small addition to the fixed query: AND d.route_id IS DISTINCT FROM c.route_id avoids updating rows where both values are already 0. Postgres otherwise creates a new row version even though the value hasn't changed. Could save some unnecessary writes on a million-row table.