Dynamically choosing a column in MySQL?


First, you need to prepare a query and then you need to execute the PREPARED statement to dynamically choose a column in MySQL.

Let us first create a table −

mysql> create table DemoTable
(
   EmployeeName varchar(100)
);
Query OK, 0 rows affected (0.77 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John Doe');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------------+
| EmployeeName |
+--------------+
| John Doe     |
+--------------+
1 row in set (0.00 sec)

Let us now dynamically choose a column in MySQL −

mysql> set @dynamicQuery=CONCAT("SELECT ", (SELECT "EmployeeName from DemoTable"));
Query OK, 0 rows affected (0.00 sec)
mysql> select @dynamicQuery;
+---------------------------------------+
| @dynamicQuery                         |
+---------------------------------------+
| SELECT EmployeeName from DemoTable    |
+---------------------------------------+
1 row in set (0.00 sec)
mysql> prepare myStatement from @dynamicQuery;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute myStatement;

This will produce the following output −

+--------------+
| EmployeeName |
+--------------+
| John Doe     |
+--------------+
1 row in set (0.00 sec)

Updated on: 25-Sep-2019

812 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements