Combine columns into rows with MySQL?


To combine columns into rows, use UNION ALL. Following is the syntax −

Syntax

select yourColumnName1 from yourTableName
   union all
select yourColumnName2 from yourTableName;

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (0.88 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,200);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(500,600);
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 −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|    100 |    200 |
|    500 |    600 |
+--------+--------+
2 rows in set (0.00 sec)

Here is the query to combine columns into rows −

mysql> select Value1 from DemoTable
   -> union all
   -> select Value2 from DemoTable;

This will produce the following output −

+--------+
| Value1 |
+--------+
|    100 |
|    500 |
|    200 |
|    600 |
+--------+
4 rows in set (0.00 sec)

Updated on: 12-Dec-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements