Sub topic 16
Differences between database systems
This chapter covers where the constraint syntax from the earlier chapters changes between database systems. It also covers the cases where a constraint is accepted but not enforced. It assumes you can write CREATE TABLE with PRIMARY KEY, UNIQUE, FOREIGN KEY, and CHECK, and that you know how ALTER TABLE ... ADD CONSTRAINT works.
The examples compare PostgreSQL, MySQL (InnoDB), SQL Server, SQLite, and Oracle. The SQL standard defines the core ideas, but each product implements them differently. Most portability bugs come from two sources. The first is syntax that differs. The second is a constraint that is accepted but silently not enforced.
Identity columns and column types
The GENERATED ALWAYS AS IDENTITY syntax used in this tutorial is standard SQL. Support varies:
| System | Auto-generated key syntax | Notes |
|---|---|---|
| PostgreSQL | `GENERATED ALWAYS AS IDENTITY` | Available from version 10. Older code uses `SERIAL`. |
| Oracle | `GENERATED ALWAYS AS IDENTITY` | Available from 12c. Older code uses sequences and triggers. |
| MySQL | `AUTO_INCREMENT` | The column must be indexed, normally as the primary key. |
| SQL Server | `IDENTITY(1,1)` | The two numbers are the seed and the step. |
| SQLite | `INTEGER PRIMARY KEY AUTOINCREMENT` | The column must be declared exactly as `INTEGER PRIMARY KEY`. It then aliases the internal row ID. |
Data types differ as well. The customers table from the first example uses TIMESTAMP. In SQL Server, TIMESTAMP is not a date and time type. It is a row-version counter that you cannot give a default value. Use DATETIME2 there. SQLite has no dedicated date type and stores dates as text, numbers, or integers. Oracle uses VARCHAR2 and NUMBER.
The same table in four dialects:
-- PostgreSQL
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);-- MySQL
CREATE TABLE customers (
customer_id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);-- SQL Server
CREATE TABLE customers (
customer_id INT IDENTITY(1,1) PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
created_at DATETIME2 NOT NULL DEFAULT SYSDATETIME()
);-- SQLite
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
full_name TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);Enforcement caveats
A constraint that is not enforced is more dangerous than one that is rejected with a syntax error. You get no warning, and bad data enters the table.
CHECK in MySQL
MySQL versions before 8.0.16 parsed CHECK clauses and ignored them. From 8.0.16 on, MySQL enforces them. MariaDB has enforced them since 10.2.1. If your code must run on an older MySQL server, assume CHECK does nothing and validate in the application too.
Foreign keys in SQLite
SQLite does not enforce foreign keys by default. You must turn enforcement on for each connection:
PRAGMA foreign_keys = ON;
-- Returns 1 when enforcement is active
PRAGMA foreign_keys;The setting is not stored in the database file. A new connection starts with enforcement off again, so run the pragma every time your application opens a connection.
Foreign keys in MySQL
MySQL enforces foreign keys in the InnoDB storage engine only. Tables created with the old MyISAM engine accept the syntax and ignore it. MySQL also ignores a foreign key written inline on a column, as in customer_id INTEGER REFERENCES customers (customer_id). Use the table-level FOREIGN KEY (...) REFERENCES ... form, as the orders example does.
flowchart TD
A[New database or environment] --> B{Which system?}
B -->|SQLite| C[Run PRAGMA foreign_keys = ON per connection]
B -->|MySQL| D{Version and engine?}
B -->|PostgreSQL, SQL Server, Oracle| E[Constraints enforced]
D -->|Before 8.0.16| F[CHECK is ignored]
D -->|MyISAM tables| G[Foreign keys are ignored]
D -->|8.0.16 or later with InnoDB| E
C --> EA diagram version of this decision would normally carry a caption and alt text. The version below is the one to use:
UNIQUE and NULL
The standard says a UNIQUE constraint ignores NULL values, so a unique column can hold many NULL rows. PostgreSQL, MySQL, SQLite, and Oracle follow this for single columns. SQL Server does not. It treats two NULL values as equal, so a unique column can hold only one NULL. PostgreSQL 15 added UNIQUE NULLS NOT DISTINCT to get the SQL Server behavior on purpose.
Oracle also treats an empty string as NULL. A NOT NULL column in Oracle therefore rejects '', while the same column in PostgreSQL accepts it.
Referential actions
The actions available on ON DELETE and ON UPDATE differ:
- PostgreSQL and MySQL support
RESTRICT,NO ACTION,CASCADE,SET NULL, andSET DEFAULT. MySQL's InnoDB parsesSET DEFAULTbut rejects it. - SQL Server has no
RESTRICTkeyword.NO ACTIONis its default and blocks the delete in the same way. It also raises an error when cascade rules create multiple cascade paths to one table. - Oracle supports
CASCADEandSET NULLon delete, plus the default blocking behavior. It has noON UPDATEclause.
The ON DELETE RESTRICT clause in the orders example therefore fails in SQL Server and Oracle. Removing it, or writing NO ACTION, gives the same blocking behavior.
Changing constraints with ALTER TABLE
Adding a constraint uses the same ALTER TABLE ... ADD CONSTRAINT name ... form almost everywhere, except SQLite. Dropping is where systems diverge:
-- PostgreSQL, SQL Server, Oracle
ALTER TABLE orders DROP CONSTRAINT ck_orders_total_limit;-- MySQL: the keyword depends on the constraint type
ALTER TABLE orders DROP FOREIGN KEY fk_orders_customer;
ALTER TABLE customers DROP INDEX uq_customers_email;
ALTER TABLE orders DROP CHECK ck_orders_total_limit;
ALTER TABLE orders DROP PRIMARY KEY;MySQL 8.0.19 and later also accept DROP CONSTRAINT name for named constraints. Older versions need the type-specific forms above.
SQLite supports very little constraint change through ALTER TABLE. You cannot add or drop a CHECK, UNIQUE, or foreign key on an existing table. The usual route is to create a new table with the wanted rules, copy the rows, drop the old table, and rename the new one. Run these steps inside a transaction.
SQL Server adds one more detail. A DEFAULT is a separate named constraint object. If you let SQL Server name it automatically, you must look up the generated name before you can drop the default or the column. Naming it yourself avoids that:
ALTER TABLE orders
ADD CONSTRAINT df_orders_status DEFAULT 'new' FOR status;Constraints and their indexes
Most systems build an index to support a primary key or unique constraint, and dropping the constraint drops that index. Foreign keys differ:
- PostgreSQL, Oracle, and SQL Server do not create an index on the referencing column. Add one yourself on
orders (customer_id)if you join or delete often. - MySQL InnoDB creates an index on the referencing column automatically if none exists.
Portability checklist
- Check the identity syntax and the date type before copying a
CREATE TABLEstatement. - Use table-level
FOREIGN KEYclauses and name every constraint. - Confirm the minimum version for
CHECK(MySQL) and the pragma (SQLite). - Run one deliberately invalid insert per constraint type after setup.
- Keep the dialect-specific
DROPstatements in versioned migration scripts, one set per system.
Exercise
A team moves a schema from PostgreSQL to SQLite for local testing. Their test inserts an order with customer_id 9999 and expects an error, but the insert succeeds. What is the cause, and what single statement fixes it?
Show answer
SQLite does not enforce foreign keys unless enforcement is switched on for the connection. Running PRAGMA foreign_keys = ON; right after the connection opens makes the insert fail with a foreign key violation, as it does in PostgreSQL.
Exercise
You run ALTER TABLE orders DROP CONSTRAINT fkorderscustomer; on a MySQL 5.7 server and get a syntax error. What statement should you use instead?
Show answer
MySQL 5.7 needs the type-specific form: ALTER TABLE orders DROP FOREIGN KEY fkorderscustomer; The generic DROP CONSTRAINT form only arrived in MySQL 8.0.19.