Sub topic 13
Naming Constraints for Readable Errors and Easier Changes
This chapter assumes you can write a basic CREATE TABLE statement and that you know what PRIMARY KEY, UNIQUE, FOREIGN KEY, and CHECK do. Here you will learn why constraint names matter, how to choose them, and how to use them in error messages and in ALTER TABLE.
Why constraints have names
Every constraint has a name. If you do not supply one, the database generates one. Generated names are hard to read and differ between systems and between environments.
| Database | Example of a generated name |
|---|---|
| PostgreSQL | `orders_total_amount_check`, `orders_customer_id_fkey`, `customers_email_key` |
| MySQL | `orders_chk_1`, `orders_ibfk_1`, `email` (for a unique index) |
| SQL Server | `CK__orders__total_am__3B75D760`, `FK__orders__customer__3C69FB99` |
| SQLite | Usually no usable name; errors name the column instead |
The suffix on SQL Server names is a random hash. Two databases built from the same script get different names. A migration script that says DROP CONSTRAINT CK__orders__total_am__3B75D760 works on your machine and fails in production.
A name you choose yourself fixes three problems:
- Readable errors. The error message tells you which rule failed.
- Reliable changes.
ALTER TABLE ... DROP CONSTRAINTneeds a name you can predict. - Easier review. Someone reading the schema sees the intent of each rule.
The CONSTRAINT keyword
You give a constraint a name with CONSTRAINT name placed in front of the constraint definition. It works at both the column level and the table level.
CREATE TABLE products (
product_id INTEGER GENERATED ALWAYS AS IDENTITY,
sku VARCHAR(30) NOT NULL,
name VARCHAR(100) NOT NULL,
price NUMERIC(10, 2) NOT NULL
CONSTRAINT ck_products_price CHECK (price >= 0),
CONSTRAINT pk_products PRIMARY KEY (product_id),
CONSTRAINT uq_products_sku UNIQUE (sku)
);The price check is named at the column level, directly after the column. The primary key and unique constraint are named at the table level. Both forms create a constraint with the name you chose.
Two points to remember:
NOT NULLis a special case. In standard SQL it can also be named, but several systems do not store a name for it or do not let you drop it by name. In PostgreSQL, for example, you change nullability withALTER COLUMN ... SET NOT NULLorDROP NOT NULL. TreatNOT NULLas a column property, and do not rely on naming it.DEFAULTis not a constraint in most systems, so it normally has no constraint name. SQL Server is an exception, where a default is a named object.
Naming conventions
A convention matters more than the particular choice. Pick one pattern and apply it everywhere. A common pattern is a short prefix for the type, then the table, then the columns involved.
| Constraint type | Pattern | Example |
|---|---|---|
| Primary key | `pk_<table>` | `pk_orders` |
| Foreign key | `fk_<table>_<referenced table or column>` | `fk_orders_customer` |
| Unique | `uq_<table>_<columns>` | `uq_customers_email` |
| Check | `ck_<table>_<rule>` | `ck_orders_total` |
Some practical rules:
- Include the table name. In PostgreSQL, SQL Server, and Oracle some constraint types need names unique within a schema (PostgreSQL requires uniqueness per table for most constraints but indexes share the schema's namespace), so a bare name like
ck_totalcollides across tables. - Describe the rule in a
CHECKname, such asck_orders_statusorck_orders_total, so the error explains itself. - Use lowercase with underscores. Unquoted names are case-folded by most systems, and quoted mixed-case names force you to quote them forever.
- Stay within the length limit. PostgreSQL truncates identifiers at 63 bytes, MySQL allows 64 characters, and SQL Server allows 128.
Names in error messages
The main payoff comes when a statement is rejected. Consider the orders table from earlier chapters:
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL,
full_name VARCHAR(100) NOT NULL,
CONSTRAINT uq_customers_email UNIQUE (email)
);
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY,
customer_id INTEGER NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
total_amount NUMERIC(10, 2) NOT NULL,
CONSTRAINT pk_orders PRIMARY KEY (order_id),
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
ON DELETE RESTRICT,
CONSTRAINT ck_orders_total CHECK (total_amount >= 0),
CONSTRAINT ck_orders_status
CHECK (status IN ('new', 'paid', 'shipped', 'cancelled'))
);
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Ada Lovelace');
INSERT INTO orders (customer_id, total_amount)
VALUES (1, -5.00);The last statement fails. PostgreSQL reports a message like this:
ERROR: new row for relation "orders" violates check constraint "ck_orders_total"
DETAIL: Failing row contains (1, 1, new, -5.00).The name ck_orders_total tells you the rule that failed. Without a name, the message would say orders_total_amount_check, which is still readable in PostgreSQL but not in SQL Server, where it would contain a hash.
Duplicate and foreign key errors work the same way:
ERROR: duplicate key value violates unique constraint "uq_customers_email"
DETAIL: Key (email)=([email protected]) already exists.
ERROR: insert or update on table "orders" violates foreign key constraint "fk_orders_customer"
DETAIL: Key (customer_id)=(9999) is not present in table "customers".Application code can use the name too. Many database drivers expose the violated constraint name on the error object. A web application can map uq_customers_email to the message "That email is already registered" without parsing text. This only works if the names are stable, which is a second reason to choose them yourself.
Names and ALTER TABLE
Constraints are changed after creation with ALTER TABLE. Adding and dropping both need a name, as the sample below shows.
ALTER TABLE orders
ADD CONSTRAINT ck_orders_total_limit CHECK (total_amount <= 1000000);
ALTER TABLE orders
DROP CONSTRAINT ck_orders_total_limit;Because you chose ck_orders_total_limit, the same script runs unchanged on every environment. If you had relied on a generated name, you would first have to look it up, and the lookup differs per environment.
Two behaviors to know:
- Adding a constraint validates existing rows. If any row already breaks the rule, the statement fails and the constraint is not added. Fix or remove the bad rows first.
- The
DROPsyntax varies. PostgreSQL, SQL Server, Oracle, and recent MySQL versions useDROP CONSTRAINT name. Older MySQL usedDROP FOREIGN KEY nameandDROP INDEX namefor those types, andDROP PRIMARY KEYfor primary keys. SQLite cannot add or drop most constraints withALTER TABLE, so you rebuild the table instead.
Finding names you did not choose
If you inherit a schema with generated names, list them from the catalog before you change anything. In PostgreSQL, and in any system that supports the standard information_schema, this works:
SELECT constraint_name, constraint_type
FROM information_schema.table_constraints
WHERE table_name = 'orders'
ORDER BY constraint_type, constraint_name;Note that information_schema also lists generated NOT NULL entries in some systems. The table_name filter is case-sensitive in some systems, so match the stored case.
Renaming a constraint
Renaming is possible but not portable.
| Database | Rename syntax |
|---|---|
| PostgreSQL | `ALTER TABLE orders RENAME CONSTRAINT old_name TO new_name;` |
| SQL Server | `EXEC sp_rename 'dbo.old_name', 'new_name', 'OBJECT';` |
| Oracle | `ALTER TABLE orders RENAME CONSTRAINT old_name TO new_name;` |
| MySQL | No direct command for most types; drop and re-add the constraint |
Name scope and collisions
Where a name must be unique depends on the system. This affects what you can name two different constraints.
- PostgreSQL: Check and foreign key names must be unique per table. Primary key and unique constraints also create an index, and index names must be unique within the schema.
- SQL Server and Oracle: Constraint names must be unique within the schema.
- MySQL: Foreign key names must be unique per database. Check constraint names must also be unique per schema. Primary keys are always named
PRIMARY.
Including the table name in every constraint name avoids all of these collisions. It also lets you copy a table definition and rename the table without clashing with the original.
Naming at a glance
The diagram shows how a name travels from the definition to the places where you use it.
Common mistakes
- Leaving names to the database. The script works until you need to drop a constraint in another environment.
- Using one name for several tables. A name like
ck_totalcollides on systems that require schema-wide uniqueness. - Vague names.
ck_orders_1forces the reader to open the table definition. Useck_orders_total. - Renaming without searching the code. Application error handlers may match on the old name.
- Assuming
DROP CONSTRAINTworks everywhere. Check your system for the foreign key, unique, and primary key variants.
Exercise
A migration runs ALTER TABLE orders DROP CONSTRAINT CK__orders__total_am__3B75D760; successfully on a developer's SQL Server database, but fails in production with "constraint does not exist". What caused the failure, and how would you prevent it? Write the CREATE TABLE fragment you would use for a rule that total_amount must not be negative.
Show answer
The original constraint had no explicit name, so SQL Server generated one, and the random hash suffix differs between databases. The fix is to name the constraint explicitly so every environment has the same name. For example: CONSTRAINT ck_orders_total CHECK (total_amount >= 0) inside the CREATE TABLE statement, and then ALTER TABLE orders DROP CONSTRAINT ck_orders_total; in the migration.
Exercise
You run ALTER TABLE orders ADD CONSTRAINT ck_orders_total_limit CHECK (total_amount <= 1000000); and the statement fails, although the syntax is correct. What is the most likely reason, and what do you do next?
Show answer
At least one existing row has a totalamount above 1000000. Adding a constraint validates existing data, and the statement is rejected if any row breaks the rule. Find the rows with `SELECT * FROM orders WHERE totalamount > 1000000;, correct or remove them, and run the ALTER TABLE` again.