How can I create a MySQL boolean column and assign value 1 while altering the same column?

MySQLMySQLi Database

To assign value 1 while altering, use the MySQL DEFAULT. This will itself enter 1 if nothing is inserted in the same column while using the INSERT command.

Let us first create a table −

mysql> create table DemoTable
(
   isAdult int
);
Query OK, 0 rows affected (1.39 sec)

Following is how you can assign value 1 default to the already created column −

mysql> alter table DemoTable CHANGE isAdult isAdult BOOLEAN DEFAULT '1' NOT NULL;
Query OK, 0 rows affected (1.18 sec)
Records: 0 Duplicates: 0 Warnings: 0

Insert some records in the table using insert command −

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(0);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------+
| isAdult |
+---------+
|       1 |
|       1 |
|       0 |
+---------+
3 rows in set (0.00 sec)
raja
Published on 27-Sep-2019 06:54:45
Advertisements