Sub topic 15
Translating from MySQL and SQL Server syntax
This chapter assumes you can write UPDATE ... FROM and DELETE ... USING in PostgreSQL, as covered earlier in this tutorial. It also assumes you have used UPDATE ... JOIN in MySQL or UPDATE ... FROM ... JOIN in SQL Server. The goal is to turn statements written for those systems into PostgreSQL, and to catch the places where a literal translation compiles but does the wrong thing.
All examples use the customers, orders, products, and price_updates tables from the start of this tutorial.
The core difference
MySQL and SQL Server let you put a JOIN directly in the statement that modifies rows. PostgreSQL does not. It has one target table, named right after UPDATE or DELETE FROM, and a separate list of extra tables: FROM for updates, USING for deletes. The join condition between the target and those extra tables goes in WHERE.
| Idea | MySQL | SQL Server | PostgreSQL |
|---|---|---|---|
| Update with a join | `UPDATE t JOIN s ON ... SET ...` | `UPDATE t SET ... FROM t JOIN s ON ...` | `UPDATE t SET ... FROM s WHERE ...` |
| Delete with a join | `DELETE t FROM t JOIN s ON ...` | `DELETE t FROM t JOIN s ON ...` | `DELETE FROM t USING s WHERE ...` |
| Qualify column in `SET` | `SET p.price = ...` | `SET p.price = ...` | `SET price = ...` (no alias allowed) |
| Return changed rows | Not available | `OUTPUT` | `RETURNING` |
| Limit rows changed | `LIMIT` (single table) | `TOP (n)` | Subquery on the key |
| Update several tables at once | Yes | No | No (use a CTE) |
Translating an update
Here is the price update written for MySQL:
-- MySQL
UPDATE products AS p
JOIN price_updates AS u ON u.product_id = p.id
SET p.price = u.new_price;And for SQL Server:
-- SQL Server
UPDATE p
SET p.price = u.new_price
FROM products AS p
JOIN price_updates AS u ON u.product_id = p.id;The PostgreSQL version:
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;Apply these steps in order:
- Move the target table (with its alias) to the
UPDATEline. - Put the remaining tables in
FROM. - Move the
ONcondition between the target and the source intoWHERE. - Remove the alias from the column on the left side of each assignment in
SET.
Step 4 is the one people forget. PostgreSQL rejects SET p.price = ... with a syntax error, because the column on the left of = always belongs to the target table.
Do not repeat the target in FROM
The SQL Server form lists the target table again in FROM. In SQL Server the alias after UPDATE points at that same table. In PostgreSQL, repeating the target creates a second, independent copy of it:
-- Wrong in PostgreSQL: products appears twice
UPDATE products
SET price = u.new_price
FROM products AS p
JOIN price_updates AS u ON u.product_id = p.id;The target products has no join condition to p, so every target row is paired with every matching pair of p and u. The result is the Cartesian-product problem from earlier in this tutorial, and it usually updates every row. When you translate a SQL Server statement, delete the target from FROM. If it joined other tables, keep those joins.
Joins inside FROM, and the ON restriction
PostgreSQL does let you write explicit joins among the extra tables:
UPDATE orders AS o
SET status = 'cancelled'
FROM customers AS c
JOIN customers AS ref ON ref.id = c.id
WHERE o.customer_id = c.id
AND c.status = 'closed';An ON clause inside FROM can see only the tables in that FROM list. It cannot refer to the target. If you write JOIN customers AS c ON c.id = o.customer_id where o is the target, PostgreSQL reports an invalid reference to a FROM-clause entry. That is why the target-to-source condition belongs in WHERE.
Translating a delete
MySQL and SQL Server both accept this shape:
-- MySQL or SQL Server
DELETE o
FROM orders AS o
JOIN customers AS c ON o.customer_id = c.id
WHERE c.status = 'closed';In PostgreSQL the target moves into DELETE FROM, and the joined table goes in USING:
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed';One trap is the LEFT JOIN ... WHERE right.id IS NULL pattern that MySQL and SQL Server users often write to delete unmatched rows. USING joins only matching rows, so it cannot express this. Use NOT EXISTS, as shown earlier:
DELETE FROM orders AS o
WHERE NOT EXISTS (
SELECT 1 FROM customers AS c WHERE c.id = o.customer_id
);The self-join delete for duplicates translates the same way:
-- MySQL
DELETE a
FROM contacts AS a
JOIN contacts AS b ON a.email = b.email AND a.id > b.id;-- PostgreSQL
DELETE FROM contacts AS a
USING contacts AS b
WHERE a.email = b.email
AND a.id > b.id;Behaviors that do not carry over
Updating two tables in one statement
MySQL allows UPDATE a JOIN b ... SET a.x = 1, b.y = 2. PostgreSQL updates exactly one table per statement. Split it into two modifications and chain them in a data-modifying CTE, so both see a consistent starting state:
WITH closed AS (
UPDATE customers
SET status = 'archived'
WHERE status = 'closed'
RETURNING id
)
UPDATE orders AS o
SET status = 'cancelled'
FROM closed AS c
WHERE o.customer_id = c.id
AND o.status = 'open';There is a caveat. Both parts of a statement with CTEs read the same snapshot, so the outer UPDATE does not see the inner one's changes in the tables themselves. It sees them only through RETURNING. That is why the example joins to closed rather than to customers.
Limiting how many rows change
MySQL accepts LIMIT on single-table updates and deletes, and SQL Server uses TOP (n). PostgreSQL accepts neither. Select the keys in a subquery instead:
DELETE FROM orders
WHERE id IN (
SELECT id
FROM orders
WHERE status = 'cancelled'
ORDER BY id
LIMIT 1000
);This is also the basis for batching large changes.
Getting the changed rows back
SQL Server's OUTPUT inserted.id, deleted.status becomes RETURNING in PostgreSQL. Differences to watch:
RETURNINGin anUPDATEshows the new values only. There is nodeleted.side with the old values.- In
UPDATE ... FROMyou may return columns from theFROMtables too, such asu.new_price. - MySQL has no equivalent for
UPDATEorDELETE, so code that ran aSELECTafterwards can often be simplified.
Several matches for one target row
If two price_updates rows exist for one product, none of the three systems raises an error. Each picks a row without a guaranteed order. The fix is the same everywhere: reduce the source to one row per target first, as in the DISTINCT ON example earlier. Don't rely on the order that a MySQL or SQL Server statement happened to produce, because PostgreSQL's plan may differ.
MERGE as an alternative
PostgreSQL 15 and later support the standard MERGE statement, which SQL Server users may already know:
MERGE INTO products AS p
USING price_updates AS u ON u.product_id = p.id
WHEN MATCHED THEN
UPDATE SET price = u.new_price;MERGE differs from UPDATE ... FROM in an important way. If more than one source row matches the same target row, MERGE raises a cardinality-violation error instead of choosing one. That makes it a safer translation when you want duplicates in the source to surface as a failure. The cost is more verbose syntax and a different locking and concurrency behavior, so test it under load before replacing existing statements.
Translation checklist
The diagram summarizes the decisions when converting a statement.
Exercises
Exercise
A SQL Server statement reads UPDATE o SET o.status = 'cancelled' FROM orders AS o JOIN customers AS c ON c.id = o.customer_id WHERE c.status = 'closed';. Write the PostgreSQL equivalent.
Show answer
UPDATE orders AS o SET status = 'cancelled' FROM customers AS c WHERE c.id = o.customer_id AND c.status = 'closed'; The target moves to the UPDATE line, the join condition moves to WHERE, the target is not repeated in FROM, and the SET column has no alias.
Exercise
A MySQL statement deletes orders that have no customer using DELETE o FROM orders o LEFT JOIN customers c ON c.id = o.customer_id WHERE c.id IS NULL;. Why can't you translate it to DELETE ... USING, and what do you write instead?
Show answer
USING joins only matching rows, so it cannot reach rows that have no match. Use NOT EXISTS: DELETE FROM orders AS o WHERE NOT EXISTS (SELECT 1 FROM customers AS c WHERE c.id = o.customer_id);
Exercise
You translate a SQL Server update and leave the target table in the FROM clause as FROM products AS p JOIN price_updates AS u ON ..., while the UPDATE line names products without an alias. What goes wrong?
Show answer
PostgreSQL treats p as a second, independent copy of products. The target table has no join condition to it, so target rows are paired with every matching row and most or all rows get updated. Remove the repeated table from FROM and join the target to the source in WHERE.