In SQL, the NOT NULL keyword is used to enforce that a column in a database table cannot have a NULL value. When a column is defined with NOT NULL, it means that every row must have a valid (non-null) value for that column.
Syntax:
The NOT NULL constraint is typically defined when creating or altering a table.
- Creating a Table:
CREATE TABLE table_name (
column1 datatype NOT NULL,
column2 datatype,
column3 datatype NOT NULL
);
In this example, column1 and column3 are defined with the NOT NULL constraint, meaning they cannot contain NULL values, while column2 is optional and can contain NULL.
- Altering an Existing Table:
You can add a
NOT NULLconstraint to an existing column using theALTER TABLEstatement:
ALTER TABLE table_name
MODIFY column_name datatype NOT NULL;
- Example:
CREATE TABLE employees (
id INT NOT NULL,
name VARCHAR(100) NOT NULL,
hire_date DATE,
salary DECIMAL(10, 2) NOT NULL
);
In this example:
- The
id,name, andsalarycolumns cannot containNULLvalues. - The
hire_datecolumn can containNULLvalues, as it is not defined withNOT NULL.
Key Points:
- The
NOT NULLconstraint ensures data integrity by preventing null values in specified columns. - You can define a column as
NOT NULLwhen creating the table or later with anALTERstatement. - If you attempt to insert a row where a
NOT NULLcolumn has no value (or isNULL), an error will be thrown.
Common Use Cases:
- Primary Key Columns: The columns that define the primary key of a table usually have the
NOT NULLconstraint because a primary key must always have a value. - Important Attributes: For columns that must always have a value (e.g.,
name,email, etc.), theNOT NULLconstraint ensures that no missing data can exist in those fields.
No comments:
Post a Comment