MySQL SELECT to add a new column to a query and give it a value?

MySQLMySQLi Database

To add column to MySQL query and give it a value, use the below syntax −

select yourColumnName1,yourColumnName2,.....N ,yourValue AS anyAliasName from yourTableName;

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(20)
);
Query OK, 0 rows affected (0.84 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.15 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1  | John      |
| 2  | Larry     |
| 3  | Chris     |
| 4  | Robert    |
+----+-----------+
4 rows in set (0.00 sec)

Following is the query to add column to MySQL and give it a value. Here we have set the value 23 after creating a new column AGE −

mysql> select Id,FirstName,23 AS AGE from DemoTable;

This will produce the following output −

+----+-----------+-----+
| Id | FirstName | AGE |
+----+-----------+-----+
| 1  | John      | 23  |
| 2  | Larry     | 23  |
| 3  | Chris     | 23  |
| 4  | Robert    | 23  |
+----+-----------+-----+
4 rows in set (0.00 sec)
raja
Published on 29-Apr-2019 15:10:09
Advertisements