- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL NOT NULL Constraint
In the world of databases, data integrity is everything. The NOT NULL constraint is one of the most fundamental tools a developer has to ensure that data remains reliable. By default, a table column can hold NULL values, which represent "missing" or "unknown" data. However, the NOT NULL constraint enforces a rule that a specific column must always contain a value.
Think of it as a mandatory field on a web form. If you are creating a user account, you wouldn't want a user to exist without an email address or a password. Applying NOT NULL ensures that your database rejects any attempt to insert or update a record that leaves these critical fields empty.
PRIMARY KEY, it automatically becomes NOT NULL. You don't need to specify it twice!
Key Features of SQL NOT NULL Constraint
- Guarantees Data Presence: It ensures that a column can never be left empty during an
INSERTorUPDATEoperation. - Schema Enforcement: It is defined during the
CREATE TABLEphase or added later usingALTER TABLE. - Application Safety: By enforcing this at the database level, you prevent "Null Pointer Exceptions" or similar crashes in your application code when it expects a value that isn't there.
- Validation: The database engine itself performs the check, making it faster and more reliable than checking for nulls in your backend code alone.
NOT NULL by default. Only allow NULL values if there is a specific business reason why that data might genuinely be unknown or optional.
SQL NOT NULL Constraint Syntax
Defining NOT NULL in Table Creation
When you are designing a new table, you place the NOT NULL keywords immediately after the data type definition for that column.
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
HireDate DATE NOT NULL,
PhoneNumber VARCHAR(15) -- This can be NULL (optional)
);
- In this example,
FirstName,LastName, andHireDateare mandatory. If you try to hire an employee without a start date, the database will block the entry.
NULL vs. an Empty String. In many SQL dialects, an empty string ('') is considered a value and will satisfy a NOT NULL constraint. If you want to prevent empty strings, you may need an additional CHECK constraint.
Adding NOT NULL to an Existing Column
Sometimes requirements change, and a field that was once optional becomes mandatory. You can use the ALTER TABLE statement to enforce the constraint on an existing column.
-- For MySQL / Oracle (Modify syntax)
ALTER TABLE Employees
MODIFY Age INT NOT NULL;
-- For SQL Server / PostgreSQL (Alter Column syntax)
ALTER TABLE Employees
ALTER COLUMN Age INT NOT NULL;
NOT NULL constraint to a column that already contains NULL values. You must first update all existing rows to provide a valid value before applying the constraint, or the command will fail.
Inserting Data into a Table with NOT NULL Constraint
Let's look at how the database reacts when we interact with these constraints in a real-world scenario.
-- ✅ This works! All mandatory fields are provided.
INSERT INTO Employees (EmployeeID, FirstName, LastName, HireDate)
VALUES (1, 'Jane', 'Smith', '2023-05-15');
-- ❌ This fails! The 'LastName' column is NOT NULL.
INSERT INTO Employees (EmployeeID, FirstName, HireDate)
VALUES (2, 'Bob', '2023-06-01');
-- Error Message: Column 'LastName' cannot be null.
When the second query runs, the database engine detects that LastName is missing. Instead of creating a "broken" record, it throws an error and protects the integrity of your data.
Removing NOT NULL Constraint
If a field becomes optional later in the project lifecycle, you can remove the NOT NULL constraint by allowing NULL values again.
-- For MySQL
ALTER TABLE Employees
MODIFY Age INT NULL;
-- For SQL Server
ALTER TABLE Employees
ALTER COLUMN Age INT NULL;
This "relaxes" the rules, allowing developers to insert records without providing an age.
Summary
- The NOT NULL constraint acts as a gatekeeper, ensuring essential data is never missing.
- It is much easier to define constraints at creation than to try and clean up messy data later.
- It prevents logic errors in your applications by guaranteeing that certain variables will always have data.
- If you need to remove the constraint, use
ALTER TABLEto switch the column back toNULL.