66

Is it possible to get a row with all column names of a table like this?

|id|foo|bar|age|street|address|

I don't like to use Pragma table_info(bla).

BBG_GIS
  • 306
  • 5
  • 17

11 Answers11

96
SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'

Then parse this value with Reg Exp (it's easy) which could looks similar to this: [(.*?)]

Alternatively you can use:

PRAGMA table_info(table_name)
Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121
  • 9
    `Then parse this value with Reg Exp (it's easy)...` is really vague, a full example of a query with the regex to get the column defs would have gone a long way here. – ChrisProsser Jul 03 '17 at 09:46
  • I leave this for the next ones : this regex `"([^"]+)" (?!\()` seems to work. – Timothé Malahieude Aug 26 '17 at 13:14
  • Does this work for getting the names of the columns returned by a JOIN query? I didn't think so. – Throw Away Account Sep 01 '17 at 02:50
  • An example Perl regex that I am using: "qr/\s (id) \s+ INTEGER \s+ PRIMARY \s KEY \s/msx" ("qr/" and "/msx" are the Perl-y bits for declaring as a regex that handles multi-line strings "ms" and allows embedded comments "x"). – Mark Leighton Fisher Sep 21 '18 at 18:38
38

If you are using the command line shell to SQLite then .headers on before you perform your query. You only need to do this once in a given session.

  • 12
    Use both `.mode column` and `.headers on` for those who want to get the typical SELECT output format they're used to seeing with other SQL shells. – Lèse majesté Sep 16 '16 at 15:56
  • or ideally you can create a .sqliterc file in your system root dir (Windows Ex: C:/windows) and inputs those commands there, that way the config will be set for every session – 8koi Jan 11 '23 at 00:18
13

You can use pragma related commands in sqlite like below

pragma table_info("table_name")
--Alternatively
select * from pragma_table_info("table_name")

If you require column names like id|foo|bar|age|street|address, basically your answer is in below query.

select group_concat(name,'|') from pragma_table_info("table_name")
Omrum Cetin
  • 1,320
  • 13
  • 17
10

Yes, you can achieve this by using the following commands:

sqlite> .headers on
sqlite> .mode column

The result of a select on your table will then look like:

id          foo         bar         age         street      address
----------  ----------  ----------  ----------  ----------  ----------
1           val1        val2        val3        val4        val5
2           val6        val7        val8        val9        val10
Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
6

This helps for HTML5 SQLite:

tx.executeSql('SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "your_table_name";', [], function (tx, results) {
  var columnParts = results.rows.item(0).sql.replace(/^[^\(]+\(([^\)]+)\)/g, '$1').split(','); ///// RegEx
  var columnNames = [];
  for(i in columnParts) {
    if(typeof columnParts[i] === 'string')
      columnNames.push(columnParts[i].split(" ")[0]);
  }
  console.log(columnNames);
  ///// Your code which uses the columnNames;
});

You can reuse the regex in your language to get the column names.

Shorter Alternative:

tx.executeSql('SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "your_table_name";', [], function (tx, results) {
  var columnNames = results.rows.item(0).sql.replace(/^[^\(]+\(([^\)]+)\)/g, '$1').replace(/ [^,]+/g, '').split(',');
  console.log(columnNames);
  ///// Your code which uses the columnNames;
});
GeekTantra
  • 11,580
  • 6
  • 41
  • 55
  • 2
    just to note, both of these solutions assume there aren't any extra spaces or other whitespace in the `sql` field of the SQLITE_MASTER table. since this field contains literal query text used to create the table, this is not always true. I'm also thinking it won't correctly handle field names that contain spaces. – Michael Apr 26 '16 at 19:15
  • Great solution. I was concerned this wouldn't include subsequent column alterations, but, per the spec, the "sql" column contains "a copy of the original CREATE statement text that created the object, except normalized as described above and as modified by subsequent ALTER TABLE statements.". – Brett Zamir Jul 05 '16 at 14:34
  • These regexes can fail when the column type includes a parentheses, such as "VARCHAR(255)" which is a perfectly valid SQLite column type. – xixixao Jan 23 '22 at 07:53
2

Use a recursive query. Given

create table t (a int, b int, c int);

Run:

with recursive
  a (cid, name) as (select cid, name from pragma_table_info('t')),
  b (cid, name) as (
    select cid, '|' || name || '|' from a where cid = 0
    union all
    select a.cid, b.name || a.name || '|' from a join b on a.cid = b.cid + 1
  )
select name
from b
order by cid desc
limit 1;

Alternatively, just use group_concat:

select '|' || group_concat(name, '|') || '|' from pragma_table_info('t')

Both yield:

|a|b|c|
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
1

The result set of a query in PHP offers a couple of functions allowing just that:

    numCols() 
    columnName(int $column_number )

Example

    $db = new SQLIte3('mysqlite.db');
    $table = 'mytable';

    $tableCol = getColName($db, $table);

    for ($i=0; $i<count($tableCol); $i++){
        echo "Column $i = ".$tableCol[$i]."\n";
    }           

    function getColName($db, $table){
        $qry = "SELECT * FROM $table LIMIT 1";
        $result = $db->query($qry);
        $nCols = $result->numCols();
        for ($i = 0; $i < $ncols; $i++) {
            $colName[$i] = $result->columnName($i);
        }
        return $colName;
    }
Luis Rosety
  • 396
  • 4
  • 10
1

Easiest way to get the column names of the most recently executed SELECT is to use the cursor's description property. A Python example:

print_me = "("
for description in cursor.description:
    print_me += description[0] + ", "
print(print_me[0:-2] + ')')
# Example output: (inp, output, reason, cond_cnt, loop_likely)
gherson
  • 169
  • 2
  • 9
0

Using @Tarkus's answer, here are the regexes I used in R:

getColNames <- function(conn, tableName) {
    x <- dbGetQuery( conn, paste0("SELECT sql FROM sqlite_master WHERE tbl_name = '",tableName,"' AND type = 'table'") )[1,1]
    x <- str_split(x,"\\n")[[1]][-1]
    x <- sub("[()]","",x)
    res <- gsub( '"',"",str_extract( x[1], '".+"' ) )
    x <- x[-1]
    x <- x[-length(x)]
    res <- c( res, gsub( "\\t", "", str_extract( x, "\\t[0-9a-zA-Z_]+" ) ) )
    res
}

Code is somewhat sloppy, but it appears to work.

Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235
0

Try this sqlite table schema parser, I implemented the sqlite table parser for parsing the table definitions in PHP.

It returns the full definitions (unique, primary key, type, precision, not null, references, table constraints... etc)

https://github.com/maghead/sqlite-parser

c9s
  • 1,888
  • 19
  • 15
0
$<?
$db = sqlite_open('mysqlitedb');
$cols = sqlite_fetch_column_types('form name'$db, SQLITE_ASSOC);
foreach ($cols as $column => $type) {
  echo "Column: $column  Type: $type\n";
}
Nigel Alderton
  • 2,265
  • 2
  • 24
  • 55