How to add a column using MySQL SELECT in an already created table?


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100),
   -> Age int
   -> );
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name,Age) values('Robert',24);
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(Name,Age) values('Chris',22);
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+--------+------+
| Id | Name   | Age  |
+----+--------+------+
| 1  | Robert | 24   |
| 2  | Chris  | 22   |
+----+--------+------+
2 rows in set (0.00 sec)

Here is the query to add a new column while using SELECT −

mysql> select Id,Name,Age,'US' AS DefaultCountryName from DemoTable;

Output

+----+--------+------+--------------------+
| Id | Name   | Age  | DefaultCountryName |
+----+--------+------+--------------------+
| 1  | Robert | 24   | US                 |
| 2  | Chris  | 22   | US                 |
+----+--------+------+--------------------+
2 rows in set (0.00 sec)

Updated on: 30-Jul-2019

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements