Can we use a comma between MySQL SELECT statements?


Yes, we can do that. The syntaxes are as follows −

Syntax1: select * from yourTableName1,yourTableName2;
Syntax2: select * from yourTableName1 cross join yourTableName2;

Both the above syntaxes give the same result.

Let us first create a table −

mysql> create table DemoTable1882
   (
   Id int
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1882 values(10);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1882 values(20);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1882 values(30);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1882;

This will produce the following output −

+------+
| Id   |
+------+
|   10 |
|   20 |
|   30 |
+------+
3 rows in set (0.00 sec)

Here is the query to create second table −

mysql> create table DemoTable1883
   (
   Id int
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1883 values(100);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1883 values(101);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1883 values(102);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1883;

This will produce the following output −

+------+
| Id   |
+------+
|  100 |
|  101 |
|  102 |
+------+
3 rows in set (0.00 sec)

Here is the query to use a comma between SELECT statements −

mysql> select * from DemoTable1882,DemoTable1883;

This will produce the following output −

+------+------+
| Id   | Id   |
+------+------+
|   10 |  100 |
|   20 |  100 |
|   30 |  100 |
|   10 |  101 |
|   20 |  101 |
|   30 |  101 |
|   10 |  102 |
|   20 |  102 |
|   30 |  102 |
+------+------+
9 rows in set (0.00 sec)

Here is the second query to get the same result like comma between SELECT statements −

mysql> select * from DemoTable1882 cross join DemoTable1883;

This will produce the following output −

+------+------+
| Id   | Id   |
+------+------+
|   10 |  100 |
|   20 |  100 |
|   30 |  100 |
|   10 |  101 |
|   20 |  101 |
|   30 |  101 |
|   10 |  102 |
|   20 |  102 |
|   30 |  102 |
+------+------+
9 rows in set (0.00 sec)

Updated on: 27-Dec-2019

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements