Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate MySQL records using inline data

Tags:

sql

mysql

This may sound like an odd question, but I'm curious to know if it's possible...

Is there a way to simulate MySQL records using inline data? For instance, if it is possible, I would expect it to work something like this:

SELECT inlinedata.*
FROM (
  ('Emily' AS name, 26 AS age),
  ('Paul' AS name, 56 AS age)
) AS inlinedata
ORDER BY age
like image 689
coatesap Avatar asked Nov 25 '13 12:11

coatesap


1 Answers

Unfortunately MySQL does not support the standard values row-constructor for this kind of things, so you need to use a "dummy" select for each row and combine the rows using UNION ALL

SELECT *
FROM (
  select 'Emily' AS name, 26 AS age 
  union all 
  select 'Paul', 56
) AS inlinedata
ORDER BY age

The UNION ALL serves two purposes

  1. It preserves any duplicate you might have on purpose
  2. It's a (tiny) bit faster than a plain UNION (because it does not check for duplicates)
like image 175
a_horse_with_no_name Avatar answered Sep 19 '22 07:09

a_horse_with_no_name