Sub topic 15
Translating from MySQL and SQL Server Syntax
Assume you know basic SELECT, WHERE, and INNER JOIN syntax, single-table UPDATE and DELETE, table aliases, and primary and foreign keys. This chapter focuses on PostgreSQL syntax and the mistakes that occur when you bring join-based modifications from another database system.
The three dialects use different shapes
PostgreSQL does not use UPDATE ... JOIN or DELETE ... JOIN. It uses UPDATE ... FROM and DELETE ... USING.
| Task | PostgreSQL | MySQL | SQL Server |
|---|---|---|---|
| Update from another table | `UPDATE ... FROM` | `UPDATE ... JOIN` | `UPDATE ... FROM` with a joined target |
| Delete using another table | `DELETE ... USING` | `DELETE target FROM ... JOIN` | `DELETE target FROM ... JOIN` |
The same business rule can therefore require different statement structures.
Translating an update
Suppose price_updates contains a new price for each product.
In MySQL, you might write:
UPDATE products AS p
JOIN price_updates AS u ON u.product_id = p.id
SET p.price = u.new_price;In SQL Server, the target table appears again in the FROM clause:
UPDATE p
SET p.price = u.new_price
FROM products AS p
JOIN price_updates AS u
ON u.product_id = p.id;In PostgreSQL, name the target once after UPDATE. Put only the source table in FROM, and write the join condition in WHERE:
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;PostgreSQL does not allow the target table name or alias before the column in the SET list. Write SET price, not SET p.price.
Translating a delete
To delete orders belonging to closed customers, MySQL and SQL Server commonly use this form:
DELETE o
FROM orders AS o
JOIN customers AS c
ON c.id = o.customer_id
WHERE c.status = 'closed';PostgreSQL expresses the source table with USING:
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed';The USING table supplies matching rows, but PostgreSQL deletes only from the table named after DELETE FROM.
Preserve the matching-row rules
Syntax translation does not fix ambiguous data. If several source rows match one target row, the update value is not safely defined. Before translating, make sure the source has one row per target, for example by selecting the newest price in a subquery.
Also check whether the source database treats duplicate matches, NULL values, or affected-row counts differently. Test the PostgreSQL statement with a SELECT using the same joins before changing data.
Exercise
Convert this SQL Server statement to PostgreSQL: DELETE o FROM orders AS o JOIN customers AS c ON c.id = o.customer_id WHERE c.status = 'closed';
Show answer
DELETE FROM orders AS o USING customers AS c WHERE o.customer_id = c.id AND c.status = 'closed';