Tutorialspoint

How to create and fill a new column in an already created MySQL table?


1 Answer
Rama Giri

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (0.77 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10,10);
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values(20,30);
Query OK, 1 row affected (0.24 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     10 |   10 |
|     20 |   30 |
+--------+--------+
2 rows in set (0.00 sec)

Following is the query to create and fill a new third column in a MySQL table. Here, boolean is considered as an integer in an integer context, i.e. the values 0 for false and 1 for true.

We have used generated column here −

mysql> alter table DemoTable add Value3 int generated always as (Value1 = Value2);
Query OK, 0 rows affected (0.51 sec)
Records: 0  Duplicates: 0  Warnings: 0

Let us display all records from the table once again −

mysql> select *from DemoTable;

This will produce the following output −

+--------+--------+--------+
| Value1 | Value2 | Value3 |
+--------+--------+--------+
|     10 |   10 | 1 |
|     20 |   30 | 0 |
+--------+--------+--------+
2 rows in set (0.00 sec)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.