Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select several hardcoded SQL rows?

Tags:

sql

mysql

oracle

If you execute this query

SELECT 'test-a1' AS name1, 'test-a2' AS name2

the result will be a one row-selection with two columns having these values:

test-a1, test-a2

How can I modify the above query to have a selection with several rows, e.g.

test-a1, test-a2
test-b1, test-b2
test-c1, test-c2

I know how to do this with UNION but I feel that there exists a more simple way to do it.

PS. Sorry for such a basic question, it is very hard to google it.

like image 832
Eugene Avatar asked Jun 14 '11 15:06

Eugene


People also ask

How do I select multiple rows in SQL?

Syntax - SELECT column1,column2, …, columnN FROM table_name; column1,column2 – Specifies the name of the columns used to fetch. table_name - Specifies the name of the table.

How do I select multiple items in SQL query?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

How do I select specific rows in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.


3 Answers

Values keyword can be used as below.

select * from  (values ('test-a1', 'test-a2'), ('test-b1', 'test-b2'), ('test-c1', 'test-c2')) x(col1, col2) 
like image 165
Muthu Avatar answered Sep 17 '22 12:09

Muthu


The following will work for SQL:

SELECT 'test-a1' AS name1, 'test-a2' AS name2 
UNION ALL 
SELECT 'test-b1', 'test-b2'
UNION ALL 
SELECT 'test-c1', 'test-c2'
like image 31
openshac Avatar answered Sep 18 '22 12:09

openshac


UNION ALL is the best bet. It's faster than UNION and you will have mutually exclusive rows.

like image 39
HLGEM Avatar answered Sep 21 '22 12:09

HLGEM