SQL-NOT NULL Constraints And Default Values

sql-not-null
Spread the love

In SQL, NOT NULL constraints are used to ensure that column(s) do not accept NULL values. Sometimes it is important to ensure no NULL values are present in table.

Syntax:

CREATE TABLE demo_tab (
    customer_id INT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    registration_date DATE DEFAULT CURRENT_DATE
);

Above code will make sure zero NULL values are present in columns i.e. first_name, last_name and email.

Here are the uses of NOT NULL Constraint in SQL –

Enforcing Non-Null Values: When you apply a NOT NULL constraint to a column, it makes sure all the accepted values will be not null. If user tried to insert not null values, error will be raised.

Default Values : In some cases user can define defult values in case user tries to insert null values.

Data Integrity: Sometimes it is important to have certain values present in the table otherwise it will affect the analyses or calculation. It’s particularly important for columns that play a central role in the structure of your data, such as primary key columns.

Not Null Default Value

In SQL, user can specify default values in not null columns.

Here is how user can specify default values in not null column

CREATE TABLE example_table (
    column1 INT NOT NULL DEFAULT 0,
    column2 VARCHAR(50) NOT NULL DEFAULT 'Default Value',
    column3 DATE NOT NULL DEFAULT CURRENT_DATE
);

In the code above, you can see user defined the not null default values for all three columns.
In column1, the default value is 0.
in column2, the default value(string) is ‘Default Value’ .
in column3, the default value is the value of Current_Date.

Thanks For Reading!

Read More :
Unique Constraints
LEARN SQL FAST