Thursday, December 19, 2024

SQL NOT NULL Keyword

 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.

  1. 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.

  1. Altering an Existing Table: You can add a NOT NULL constraint to an existing column using the ALTER TABLE statement:
ALTER TABLE table_name
MODIFY column_name datatype NOT NULL;
  1. 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, and salary columns cannot contain NULL values.
  • The hire_date column can contain NULL values, as it is not defined with NOT NULL.

Key Points:

  • The NOT NULL constraint ensures data integrity by preventing null values in specified columns.
  • You can define a column as NOT NULL when creating the table or later with an ALTER statement.
  • If you attempt to insert a row where a NOT NULL column has no value (or is NULL), 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 NULL constraint because a primary key must always have a value.
  • Important Attributes: For columns that must always have a value (e.g., name, email, etc.), the NOT NULL constraint ensures that no missing data can exist in those fields.

No comments:

Post a Comment