Check if a field of table has NOT NULL property set in SQL?



To check if field of a table has NOT NULL property, you can use any of the two syntaxes. The first syntax is as follows −

desc yourTableName;

Following is the second syntax −

select column_name,    is_nullable    from information_schema.columns    where table_schema = ‘yourDatabaseName’    and table_name = 'yourTableName’;

Let us first see an example and create a table −

mysql> create table DemoTable (    StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,    StudentName varchar(40),    StudentAge int NOT NULL,    IsActiveStudent ENUM('ACTIVE",INACTIVE') NOT NULL,    StudentCountryName varchar(40) ); Query OK, 0 rows affected (1.53 sec)

The first syntax is as follows to check if field of table has NOT NULL property set −

mysql> desc DemoTable;

This will produce the following output −

+--------------------+--------------------------+------+-----+---------+----------------+ | Field              | Type                     | Null | Key | Default |          Extra | +--------------------+--------------------------+------+-----+---------+----------------+ | StudentId          | int(11)                  | NO   | PRI | NULL    | auto_increment | | StudentName        | varchar(40)              | YES  |     | NULL    |                | | StudentAge         | int(11)                  | NO   |     | NULL    |                | | IsActiveStudent    | enum('ACTIVE",INACTIVE') | NO   |     | NULL    |                | | StudentCountryName | varchar(40)              | YES  |     | NULL    |                | +--------------------+--------------------------+------+-----+---------+----------------+ 5 rows in set (0.00 sec)

The second syntax is as follows to check if field of table has NOT NULL property set −

mysql> select column_name,    is_nullable    from information_schema.columns    where table_schema = 'web'    and table_name = 'DemoTable';

This will produce the following output −

+--------------------+-------------+ | COLUMN_NAME        | IS_NULLABLE | +--------------------+-------------+ | StudentId          | NO | | StudentName        | YES | | StudentAge         | NO | | IsActiveStudent | NO | | StudentCountryName | YES | +--------------------+-------------+ 5 rows in set (0.00 sec)
Updated on: 2019-10-10T12:01:06+05:30

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements