Adding a column that doesn't exist in a query?


Add a column that does not exist in a query, with the help of AS keyword. The syntax is as follows −

SELECT yourColumnName1,yourColumnName2,....N,yourValue AS yourColumnName,....N' FROM yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table ColumnDoesNotExists
    -> (
    -> UserId int,
    -> UserName varchar(20)
    -> );
Query OK, 0 rows affected (0.67 sec)

Example

Insert some records in the table using insert command. The query is as follows −

mysql> insert into ColumnDoesNotExists(UserId,UserName) values(100,'Larry');
Query OK, 1 row affected (0.14 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(101,'Sam');
Query OK, 1 row affected (0.22 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(102,'Mike');
Query OK, 1 row affected (0.15 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(103,'David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(104,'Robert');
Query OK, 1 row affected (0.10 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(105,'Maxwell');
Query OK, 1 row affected (0.20 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(106,'Bob');
Query OK, 1 row affected (0.17 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(107,'John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into ColumnDoesNotExists(UserId,UserName) values(108,'James');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from ColumnDoesNotExists;

Output

+--------+----------+
| UserId | UserName |
+--------+----------+
|    100 |    Larry |
|    101 |      Sam |
|    102 |     Mike |
|    103 |    David |
|    104 |   Robert |
|    105 |  Maxwell |
|    106 |      Bob |
|    107 |     John |
|    108 |    James |
+--------+----------+
9 rows in set (0.00 sec)

Example

Here is the query to add a column name that does not exist in a query −

mysql> select UserId,UserName,23 AS Age from ColumnDoesNotExists;

Output

+--------+----------+-----+
| UserId | UserName | Age |
+--------+----------+-----+
|    100 |    Larry |  23 |
|    101 |      Sam |  23 |
|    102 |     Mike |  23 |
|    103 |    David |  23 |
|    104 |   Robert |  23 |
|    105 |  Maxwell |  23 |
|    106 |      Bob |  23 |
|    107 |     John |  23 |
|    108 |    James |  23 |
+--------+----------+-----+
9 rows in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

809 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements