Constraints

Draft

Constraints move basic data rules into PostgreSQL. They make invalid states harder to store, no matter which application sends the SQL.

Insert valid data

The row passes NOT NULL, UNIQUE, PRIMARY KEY, and CHECK constraints.

INSERT INTO products (sku, name, price_cents)
VALUES ('TEE-001', 'PgQuest T-shirt', 3200)
RETURNING *;
idskunameprice_cents
3TEE-001PgQuest T-shirt3200
Insert on products  (cost=0.00..0.01 rows=1 width=72)
  ->  Result  (cost=0.00..0.01 rows=1 width=72)

Inspect constraints

PostgreSQL stores constraints in system catalogs that you can query.

SELECT conname, contype
FROM pg_constraint
WHERE conrelid = 'products'::regclass
ORDER BY conname;
connamecontype
products_id_not_nulln
products_name_not_nulln
products_pkeyp
products_price_cents_checkc
products_price_cents_not_nulln
products_sku_keyu
products_sku_not_nulln
Sort  (cost=7.44..7.44 rows=1 width=65)
  Sort Key: conname
  ->  Seq Scan on pg_constraint  (cost=0.00..7.43 rows=1 width=65)
        Filter: (conrelid = '16385'::oid)

Try Yourself

Loaded Database:constraints.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 2 DONE
1.Insert a product with sku BAG-001, name PgQuest Tote, price 4200, and return it.
2.List the constraint names for the products table ordered by name.

What We Learned

  • PRIMARY KEYidentifies each row and prevents duplicate ids.
  • UNIQUEprevents duplicate values in selected columns.
  • CHECKrequires each row to satisfy a boolean expression.
  • pg_constraintis a PostgreSQL catalog containing table constraints.