How To Use Not Null In Sql in SQL
How to Use NOT NULL in SQL
The NOT NULL constraint ensures that a column cannot have NULL values. This means every row must have a valid (non-null) value for that column.
Syntax:
CREATE TABLE table_name ( column_name datatype NOT NULL, ...);Or add NOT NULL constraint to an existing column:
ALTER TABLE table_nameMODIFY column_name datatype NOT NULL; -- MySQL syntax-- or in PostgreSQL:ALTER TABLE table_nameALTER COLUMN column_name SET NOT NULL;Example 1: Create table with NOT NULL column
CREATE TABLE employees ( employee_id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL, department VARCHAR(50));Here,
nameandemailcolumns must have a value for every row.
Example 2: Insert with NOT NULL columns
INSERT INTO employees (employee_id, name, email, department)VALUES (1, 'John Doe', 'john@example.com', 'Sales');If you try to insert
NULLintonameoremail, SQL will give an error.
Notes:
NOT NULLis useful to enforce required fields.When a column is
NOT NULL, you cannot insert or update it with a NULL value.Some databases require
NOT NULLcolumns to have a default value if not explicitly inserted.
If you want help adding NOT NULL constraints to existing tables or have any other questions, just ask!