Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Set NOT NULL Attribute to an Existing Column in MySQL



To set NOT NULL attribute to an existing column, use ALTER TABLE command. Let us first create a table −

mysql> create table DemoTable1949
   (
   UserId int,
   UserName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Here is the query to set NOT NULL attribute to an existing column −

mysql> alter table DemoTable1949 modify UserName varchar(20) not null;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

Let us check the description of table −

mysql> desc DemoTable1949;

This will produce the following output −

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| UserId   | int(11)     | YES  |     | NULL    |       |
| UserName | varchar(20) | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1949 values(101,NULL);
ERROR 1048 (23000): Column 'UserName' cannot be null
mysql> insert into DemoTable1949 values(101,'Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1949 values(102,'Bob');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1949;

This will produce the following output −

+--------+----------+
| UserId | UserName |
+--------+----------+
|    101 | Chris    |
|    102 | Bob      |
+--------+----------+
2 rows in set (0.00 sec)
Updated on: 2019-12-31T06:47:21+05:30

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements