Introduction to the NOT NULL Constraint in SQL
In SQL, the NOT NULL constraint ensures that a column does not accept NULL values.
This constraint is typically used when creating or modifying tables to ensure data integrity and accuracy.
Here are some common uses of NOT NULL:
-
Specifying NOT NULL Constraint When Creatign a Table: When creating a new table, you can add
NOT NULLafter the column definition to specify that the column cannot containNULLvalues.CREATE TABLE customers ( customer_id INT NOT NULL, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(100) );In this example, the columns
customer_id,first_name, andlast_namecannot containNULLvalues, whereas theemailcolumn has no such constraint and can beNULL. -
Adding NOT NULL Constraint When Modifying a Table: If an existing table needs to have a
NOT NULLconstraint added to a specific column, you can use theALTER TABLEstatement.ALTER TABLE customers MODIFY email VARCHAR(100) NOT NULL;This statement changes the constraint of the
emailcolumn from allowingNULLto disallowingNULL. -
Using NOT NULL with DEFAULT Values in Column Definitions: You can combine
NOT NULLwith theDEFAULTkeyword to provide a default value for a column.CREATE TABLE orders ( order_id INT NOT NULL, customer_id INT NOT NULL, order_date DATETIME NOT NULL DEFAULT NOW() );In this case, if a new order is inserted without specifying the
order_date, the current date will be autmoatically used as the default value. -
Handling NOT NULL Constraints in INSERT Statements: When inserting data into a table that contains
NOT NULLconstraints, values must be provided for those columns.INSERT INTO orders (order_id, customer_id) VALUES (1, NULL); INSERT INTO orders (order_id, customer_id) VALUES (1, 1);Attempting to insert a record missing values for
order_idorcustomer_idwill result in a error because these columns haveNOT NULLconstraints. -
Handling NOT NULL Constraints in UPDATE Statements: Even though a column has a
NOT NULLconstraint, you can still update it using anUPDATEstatement, as long as the new value is notNULL.UPDATE customers SET first_name = 'Jane' WHERE customer_id = 1;
The NOT NULL constraint is an essential part of database design. It helps maintain data integrity and prevents incomplete data from being stored in the database. Properly using NOT NULL constraints during database design enhances data reliability and application robustness.