Sub topic 18
How MySQL, SQL Server, Oracle, and PostgreSQL differ
This chapter assumes you can write CREATE TABLE statements, declare primary and foreign keys, and read the ON DELETE actions covered earlier. The examples so far used PostgreSQL syntax. The core ideas (primary key, foreign key, referential integrity) are the same in every major database. The differences are in how you generate key values, what the engine creates for you, and which referential actions it supports.
What stays the same
All four systems follow the SQL standard for the basic constraints:
PRIMARY KEYimplies unique and not null.FOREIGN KEY ... REFERENCESrejects child rows with no matching parent.- A composite primary key is declared with a table-level
PRIMARY KEY (a, b). - A table-level
CONSTRAINT name ...clause lets you name any constraint.
If you write portable DDL (data definition language, the SQL used to create and change tables), keep to these constructs. Most trouble comes from the areas below.
Generating key values
This is the biggest visible difference. Each system has its own way to produce surrogate keys.
| System | Common syntax for an auto-generated integer key | Notes |
|---|---|---|
| PostgreSQL | `INTEGER GENERATED ALWAYS AS IDENTITY` | Identity columns need PostgreSQL 10 or later. `SERIAL` is an older shortcut. |
| MySQL | `INT AUTO_INCREMENT PRIMARY KEY` | The column must be indexed, and a table can have only one such column. |
| SQL Server | `INT IDENTITY(1,1) PRIMARY KEY` | The two numbers are the seed (first value) and the increment. |
| Oracle | `NUMBER GENERATED ALWAYS AS IDENTITY` | Identity columns need Oracle 12c or later. Older code uses a sequence plus a trigger. |
Here is the same customers table in each dialect.
-- PostgreSQL
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
-- MySQL
CREATE TABLE customers (
customer_id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
-- SQL Server
CREATE TABLE customers (
customer_id INT IDENTITY(1,1) PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
-- Oracle (12c or later)
CREATE TABLE customers (
customer_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR2(255) NOT NULL UNIQUE,
name VARCHAR2(100) NOT NULL
);Oracle also uses VARCHAR2 instead of VARCHAR for text columns. Treat that as a data type difference you will meet in every table.
Generated values are not gap-free
In all four systems, generated numbers can have gaps. A rolled-back insert or a failed statement still consumes a value, because the counter does not roll back with the transaction. Do not use a surrogate key as a "count of rows" or as an invoice number that must be continuous. If you need gap-free numbers, generate them in a separate, controlled process.
Getting the new key back
After inserting a row you often need its generated key, for example to insert child rows. The syntax differs:
- PostgreSQL:
INSERT ... RETURNING customer_id. - Oracle:
INSERT ... RETURNING customer_id INTO :var(inside PL/SQL or through a driver). - SQL Server:
INSERT ... OUTPUT INSERTED.customer_id, orSCOPE_IDENTITY(). - MySQL:
LAST_INSERT_ID()after the insert.
Prefer the form that is tied to your statement or session over a global lookup. In SQL Server, use SCOPE_IDENTITY() rather than @@IDENTITY, because @@IDENTITY can return a value generated by a trigger.
Foreign key support and the storage engine
MySQL has a trap that the other three do not. Foreign keys are enforced only by certain storage engines. The default engine, InnoDB, supports them. The older MyISAM engine parses the REFERENCES clause and then ignores it, so no error appears and no integrity is enforced.
CREATE TABLE orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT NOT NULL,
ordered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
) ENGINE = InnoDB;Naming the engine explicitly documents your intent. Also note that MySQL requires the parent and child columns to have compatible types. A signed INT child column cannot reference an unsigned INT UNSIGNED parent column.
Automatic indexes on foreign keys
Earlier you saw that PostgreSQL does not index foreign key columns for you. The systems differ here:
| System | Index created automatically on the foreign key column? |
|---|---|
| PostgreSQL | No |
| MySQL (InnoDB) | Yes, if no usable index exists already |
| SQL Server | No |
| Oracle | No |
In all four, the primary key and any UNIQUE constraint get an index automatically. The foreign key side is where they split. Because three of the four do not create the index, the safe habit is to create one yourself and not rely on the engine.
CREATE INDEX idx_orders_customer_id ON orders (customer_id);This statement works in all four systems. Without the index, deleting a parent row forces the database to scan the child table to check for referencing rows. In Oracle and others this can also cause heavier locking on the child table.
Referential actions
The standard defines five actions: NO ACTION, RESTRICT, CASCADE, SET NULL, and SET DEFAULT. Support varies.
| Action | PostgreSQL | MySQL (InnoDB) | SQL Server | Oracle |
|---|---|---|---|---|
| `ON DELETE NO ACTION` | Yes (default) | Yes (default) | Yes (default) | Yes (default) |
| `ON DELETE RESTRICT` | Yes | Yes | No | No |
| `ON DELETE CASCADE` | Yes | Yes | Yes | Yes |
| `ON DELETE SET NULL` | Yes | Yes | Yes | Yes |
| `ON DELETE SET DEFAULT` | Yes | Parsed but rejected by InnoDB | Yes | No |
| `ON UPDATE` actions | Yes | Yes | Yes | No |
Key points from the table:
- Oracle has no
ON UPDATEclause. The usual reason is that Oracle designs assume primary key values never change. If you need to change a key, you must update parent and children in a controlled sequence, or use a deferrable constraint. - SQL Server and Oracle have no
RESTRICTkeyword. UseNO ACTION, which gives the same rejection for most purposes. - The difference between
NO ACTIONandRESTRICTis timing in the standard.NO ACTIONcan be checked at the end of the statement, andRESTRICTis checked immediately. In MySQL they behave the same. - SQL Server limits cascade paths. If two cascading paths could reach the same child table, or a cascade could form a cycle, the server refuses to create the constraint with an error about multiple cascade paths. The fix is to make one of the actions
NO ACTION, or to handle the deletion in a stored procedure.
Deferrable constraints
A deferrable constraint is checked at commit time rather than at the end of each statement. This helps with circular references and with swapping key values.
- PostgreSQL and Oracle support
DEFERRABLE INITIALLY DEFERREDon foreign keys. - MySQL and SQL Server do not support deferrable constraints. For circular references you must insert a row with a
NULLforeign key first and update it later, or temporarily disable the constraint.
-- PostgreSQL and Oracle
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
DEFERRABLE INITIALLY DEFERRED;Dropping constraints
The ADD CONSTRAINT syntax is portable, but DROP differs for MySQL:
-- PostgreSQL, SQL Server, Oracle
ALTER TABLE orders DROP CONSTRAINT fk_orders_customer;
-- MySQL
ALTER TABLE orders DROP FOREIGN KEY fk_orders_customer;MySQL also uses DROP PRIMARY KEY because a table has only one. If you do not name a constraint, each system invents a name, and the names have different patterns. Naming constraints yourself avoids having to look them up in the system catalog.
Choosing and deciding
When you move between systems, use this checklist:
- Replace the key generation clause (
IDENTITY,AUTO_INCREMENT, orGENERATED ... AS IDENTITY). - Translate data types (
VARCHAR2in Oracle,TIMESTAMPversusDATETIME2in SQL Server). - Check that every
ON DELETEandON UPDATEaction exists in the target system. - Add explicit indexes on foreign key columns.
- Rewrite
DROPstatements and any code that retrieves generated keys. - For MySQL, confirm the engine is InnoDB.
Exercise
You are porting this PostgreSQL table to Oracle: order_items has a foreign key to products declared with ON DELETE RESTRICT ON UPDATE CASCADE. Which two parts need changing, and what do you do instead?
Show answer
Oracle has no RESTRICT keyword, so use ON DELETE NO ACTION (or omit the clause, since it is the default). Oracle also has no ON UPDATE clause, so remove ON UPDATE CASCADE and, if keys must ever change, update the parent and child rows in a controlled sequence or use a deferrable constraint.
Exercise
A MySQL table declares FOREIGN KEY (customer_id) REFERENCES customers (customer_id) and accepts an insert with customer_id 999, which has no parent. What is the most likely cause, and how do you check it?
Show answer
The table probably uses a storage engine that does not enforce foreign keys, such as MyISAM. Check with SHOW CREATE TABLE orders; and, if needed, convert it with ALTER TABLE orders ENGINE = InnoDB; after cleaning up any orphaned rows.