How to insert NULL keyword as a value in a character type column of MySQL table having NOT NULL constraint?

MySQLMySQLi Database

It is quite possible to insert the NULL keyword as a value in a character type column having NOT NULL constraint because NULL is a value in itself. Following example will exhibit it −

Example

Suppose we have a table test2 having character type column ‘Name’ along with NOT NULL constraint on it. It can be checked from the DESCRIBE statement as follows −

mysql> Describe test2\G
*************************** 1. row ***************************
  Field: id
   Type: int(11)
   Null: NO
    Key:
Default: NULL
  Extra:
*************************** 2. row ***************************
  Field: NAME
   Type: varchar(20)
   Null: NO
    Key:
Default: NULL
  Extra:
2 rows in set (0.03 sec) 

Now, with the help of the following query, we can insert NULL as a value in the column ‘Name’. 

mysql> Insert into test2 values(2, 'NULL');
Query OK, 1 row affected (0.06 sec)

mysql> select * from test2;
+----+--------+
| id | NAME   |
+----+--------+
|  1 | Gaurav |
|  2 | NULL   |
+----+--------+
2 rows in set (0.00 sec) 

To understand the difference between ‘NULL’ and ‘NULL as a value’ we can run the following two queries − 

mysql> delete from test2 where name IS NULL;
Query OK, 0 rows affected (0.00 sec) 

The above query affects 0 rows it means there are no NULL rows. It can be checked from the SELECT query that no rows have been deleted.

mysql> select * from test2;
+----+--------+
| id | NAME   |
+----+--------+
|  1 | Gaurav |
|  2 | NULL   |
+----+--------+
2 rows in set (0.00 sec)

mysql> delete from test2 where name = 'NULL';
Query OK, 1 row affected (0.09 sec) 

The above query affects 1 row it means there is a row having NULL as a value. It can be checked from SELECT query that row which had NULL as a value in the ‘NAME’ column has been deleted. 

mysql> select * from test2;
+----+--------+
| id | NAME   |
+----+--------+
|  1 | Gaurav |
+----+--------+
1 row in set (0.00 sec)
raja
Published on 16-Feb-2018 16:50:22
Advertisements