SQL NOT NULL Constraint

SQL NOT NULL CONSTRAINT example – Learn how to deny accepting of NULL values for columns in MySQL database with example and important points.

All columns in the table accept NULL as default. To deny accepting NULL values we can use NOT NULL CONSTRAINT.

SQL syntax to create a table and applying constraints for columns and tables.

Syntax: CREATE TABLE [table_name]
([column_name ] [data type]  ([size]) [column constraint]..
[table_contsraint]  ([[column_name]…..]……….);

SQL query to create a table and restrict the null values for a column in database.

Query example:

CREATE TABLE ADDRESSBOOK
(
ADDRBOOK_ID BIGINT NOT NULL,
MEMBER_ID BIGINT NOT NULL,
DSIPLAYNAME VARCHAR(254)
);

the above query results in restricting the null values for columns (ADDRBOOK_ID, MEMBER_ID) in ADDRESSBOOK table by applying not null constraint.

SQL query to add a not null constraint to an existing column.

SQL syntax to add a constraint to existing column

  Syntax:

ALTER TABLE [table_name]
CHANGE [old_column_name] [new_column_name] [data_type] [constraints]  ;

query example to add a constraint to an existing column in the table.

Example query:

ALTER TABLE ADDRESSBOOK
CHANGE DSIPLAYNAME DISPLAYNAME VARCHAR(254) NOT NULL;

In this case old column and new column name and datatype are same except for the column definition that has not null constraint.

Related Posts