MySQL Insert Values into New Column – Step-by-Step Guide

MySQL

SQL screenshot
Please answer me if you know how to insert values into a new column added into an existing table. Your answer will be highly appreciated

Best Answer

You need to update the existing table.

mysql> create table tbl1(id int);
Query OK, 0 rows affected (0.04 sec)

mysql> insert into tbl1 values(1);
Query OK, 1 row affected (0.00 sec)

mysql> insert into tbl1 values(2);
Query OK, 1 row affected (0.00 sec)

mysql> alter table tbl1 add column name varchar(20);
Query OK, 0 rows affected (0.13 sec)
Records: 0  Duplicates: 0  Warnings: 0

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

mysql> update tbl1 set name='Jay' where id=1;
Query OK, 1 row affected (0.09 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from tbl1;
+------+------+
| id   | name |
+------+------+
|    1 | Jay  |
|    2 | NULL |
+------+------+
2 rows in set (0.00 sec)

mysql> update tbl1 set name='Joe' where id=2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from tbl1;
+------+------+
| id   | name |
+------+------+
|    1 | Jay  |
|    2 | Joe  |
+------+------+
2 rows in set (0.00 sec)