Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I name the output column in a sqlite values clause?

Tags:

sqlite

If I run this query in sqlite3 (3.17.0)

select T.* from (values (1),(2),(3),(4),(5)) as T;

I get the below output where there is no name for the first column of T.

----------
1
2
3
4
5

How do I give the first column of T a name/alias, or alternatively, is there any way to refer to it by index somehow?

like image 664
feihtthief Avatar asked May 11 '17 10:05

feihtthief


People also ask

How do I name an output column in SQLite?

So, you could change to: SELECT T.a AS my_column_alias FROM ( SELECT 1 as a UNION ALL SELECT 2 as a UNION ALL SELECT 3 as a UNION ALL SELECT 4 as a UNION ALL SELECT 5 as a ) as T; Then "my_column_alias" is your column name/alias.

How do I get the column names in sqlite3?

Click on Columns and drag it to the query window. This will enumerate the columns names in that given table separated by comma at the cursor position. (easier/faster than writing queries for an equivalent result!). sqlite> .

How do I select specific data in SQLite?

To select data from an SQLite database, use the SELECT statement. When you use this statement, you specify which table/s to select data from, as well as the columns to return from the query. You can also provide extra criteria to further narrow down the data that is returned.


2 Answers

with cte(my_column_alias) as 
  (values (1),(2),(3),(4),(5))
select * from cte;
like image 103
Catherine Devlin Avatar answered Sep 20 '22 09:09

Catherine Devlin


The VALUES form of a query does not have any mechanism for you to specify the column name. (The VALUES clause is intended to be used in CTEs or views where you can specify the column names elsewhere.)

As it happens, the columns returned by VALUES do have names (but they are undocumented):

sqlite> .header on
sqlite> .mode columns
sqlite> values (42);
column1
----------
42

In any case, even if that name does not survive the subquery, an empty column name is no problem at all:

select "" from (values (1),(2),(3),(4),(5));

To apply column name(s), wrap a CTE around it:

WITH T(my_column) AS (
  VALUES (1),(2),(3),(4),(5)
)
SELECT * FROM T;

or use a compound query (the WHERE 0 suppresses the row from the first query):

SELECT NULL AS my_column WHERE 0
UNION ALL
VALUES (1),(2),(3),(4),(5);
like image 39
CL. Avatar answered Sep 21 '22 09:09

CL.