Q&A for SQL Server migrated here from this question.
What happens if a "NOT NULL" constraint is added to a table to a column that already has NULL values?
sql server
Q&A for SQL Server migrated here from this question.
What happens if a "NOT NULL" constraint is added to a table to a column that already has NULL values?
Best Answer
The question:
A simple example in SQL Server is a constraint to disallow NULLs.
Create a table and insert two rows, one not null and one null.
The
ALTER TABLE
syntax can direct what happens when you create the constraint. UsingWITH NOCHECK
will tell the engine (vroom vroom) not to check the column contents, but just to add the constraint for future rows.Adding this constraint runs successfully, but it means that the constraint is untrusted, and you lose certain query optimizations. For instance, if this were a Foreign Key, you would lose join elimination. For a column constraint, the optimizer can skip doing any work period if constraint information tells it that a search will yield no results.
But now this insert fails:
You can also direct the engine (beep beep) to check the column values while adding the constraint.
Adding this constraint will fail.
If you add one with no formal direction (at least for column check constraints), the engine (screeeeech) will throw an error.
An example of the type of optimization you can get with a trusted constraint is like so:
Rather than look for values at all, the engine (honk honk) knows that such a value can't exist because of the trusted constraint. Rather than put together a 'real' query plan and read any data, the optimizer short circuits and uses a Constant Scan operator to return NADA!