Menu▾

Close the loophole on a column that's never actually null

customers.email is declared as a nullable TEXT column, but every process that writes to this table already requires an email — none of the existing rows have one missing. The nullability is just an oversight from when the table was first created.

Add a NOT NULL constraint to customers.email so the database enforces what's already true of the data.

Schema

▸customers
idINT
emailTEXT
nameTEXT

Example input

Why

ALTER TABLE ... ALTER COLUMN ... SET NOT NULL is a scan-and-check operation: Postgres reads every existing row to confirm none of them actually has a null in that column before it agrees to add the restriction. If even one row did, the whole statement rolls back and nothing changes — the constraint is all-or-nothing, never applied partially. This is the same guarantee a PRIMARY KEY gives you implicitly (a primary key column is always NOT NULL), just spelled out explicitly for a column that isn't a key.

↑ Read the question

Keep going

Company names are trademarks of their respective owners, used here only to describe practice material. mahir_data is not affiliated with, endorsed by, or sponsored by any company named on this site. Terms.