Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a tableless select with multiple rows?

Tags:

sql

A SELECT without a FROM clause gets us a multiple columns without querying a table:

SELECT 17+23, REPLACE('bannanna', 'nn', 'n'), RAND(), CURRENT_TIMESTAMP;

How can we write a query that results in multiple rows without referring to a table? Basically, abuse SELECT to turn it into a data definition statement. The result could have a single column or multiple columns.

I'm most interested in a DBMS neutral answer, but others (e.g. based on UNPIVOT) are welcome. I'd like to collect as many ways of doing this as possible. There's no technique application behind this question; it's more theoretical than practical.

like image 694
outis Avatar asked May 22 '10 00:05

outis


People also ask

Is it possible to have multiple rows with select from dual?

No. dual has just one row, but you can use union all : This is just one way to generate a table "on-the-fly" in Oracle.

Can a primary key have multiple rows?

You can't. That's what a primary key is - something that is unique to every row.

How do I select multiple rows in a single column?

In this case, we use GROUP_CONCAT function to concatenate multiple rows into one column. GROUP_CONCAT concatenates all non-null values in a group and returns them as a single string. If you want to avoid duplicates, you can also add DISTINCT in your query.

How do I select multiple row values in SQL?

You may use the IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple rows. Contents: Using IN operator with a Multiple Row Subquery. Using NOT IN operator with a Multiple Row Subquery.


1 Answers

Use a UNION:

SELECT 1
UNION
SELECT 2

Looks like this in MySQL:

+---+
| 1 |
+---+
| 1 | 
| 2 | 
+---+

Use UNION ALL to avoid the loss of non-unique rows.

like image 186
martin clayton Avatar answered Nov 15 '22 20:11

martin clayton