How to generate field in MySQL SELECT?


Use keyword AS for this. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.50 sec)
mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.54 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+--------+
| Id | Name   |
+----+--------+
| 1  | John   |
| 2  | Robert |
| 3  | David  |
+----+--------+
3 rows in set (0.00 sec)

Following is the query to generate field in MySQL SELECT −

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

Output

+----+--------+-------------+
| Id | Name   | CountryName |
+----+--------+-------------+
| 1  | John   | US          |
| 2  | Robert | US          |
| 3  | David  | US          | 
+----+--------+-------------+
3 rows in set (0.00 sec)

Updated on: 30-Jul-2019

107 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements