Set 'alias' for all the column names in a single MySQL query



To set alias for column names, the syntax is as follows −

select yourColumnName1 anyAliasName1,yourColumnName2 anyAliasName2 from yourTableName anyAliasName;

To understand the above syntax, let us create a table −

mysql> create table DemoTable2014    -> (    -> FirstName varchar(20),    -> LastName varchar(20)    -> ); Query OK, 0 rows affected (0.70 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2014 values('John','Smith'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable2014 values('David','Miller'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable2014 values('John','Doe'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable2014 values('Chris','Brown'); Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2014;

This will produce the following output −

+-----------+----------+ | FirstName | LastName | +-----------+----------+ | John      | Smith    | | David     | Miller   | | John      | Doe      | | Chris     | Brown    | +-----------+----------+ 4 rows in set (0.00 sec)

Here is the query to set 'alias' for column names in a single MySQL query −

mysql> select FirstName StudentFirstName,LastName StudentLastName -> from DemoTable2014 tbl;

This will produce the following output −

+------------------+-----------------+ | StudentFirstName | StudentLastName | +------------------+-----------------+ | John             | Smith           | | David            | Miller          | | John             | Doe           | | Chris | Brown | +------------------+-----------------+ 4 rows in set (0.00 sec)
Updated on: 2020-04-06T12:55:44+05:30

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements