How can I get the list of a columns in a table for a SQLite database?

Viewed 121562

I am looking to retrieve a list of columns in a table. The database is the latest release of SQLite (3.6, I believe). I am looking for code that does this with a SQL query. Extra bonus points for metadata related to the columns (e.g. length, data type, etc...)

9 Answers

What you're looking for is called the data dictionary. In sqlite a list of all tables can be found by querying sqlite_master table (or view?)

sqlite> create table people (first_name varchar, last_name varchar, email_address varchar);
sqlite> select * from sqlite_master;
table|people|people|2|CREATE TABLE people (first_name varchar, last_name varchar, email_address varchar)

To get column information you can use the pragma table_info(table_name) statement:

sqlite> pragma table_info(people);
0|first_name|varchar|0||0
1|last_name|varchar|0||0
2|email_address|varchar|0||0

For more information on the pragma statements, see the documentation.

The question is old but the following hasn't been mentioned yet.

Another convenient way in many cases is to turn headers on by:

sqlite> .headers on

Then,

sqlite> SELECT ... FROM table

will display a headline showing all selected fields (all if you SELECT *) at the top of the output.

Here's a SELECT statement that lists all tables and columns in the current database:

SELECT m.name as tableName, 
       p.name as columnName
FROM sqlite_master m
left outer join pragma_table_info((m.name)) p
     on m.name <> p.name
order by tableName, columnName
;

just go into your sqlite shell:

$ sqlite3 path/to/db.sqlite3

and then just hit

sqlite> .schema

and you will get everything.

This is a query that lists all tables with their columns, and all the metadata I could get about each column as OP requested (as bonus points).

SELECT
  m.name AS table_name, 
  p.cid AS col_id,
  p.name AS col_name,
  p.type AS col_type,
  p.pk AS col_is_pk,
  p.dflt_value AS col_default_val,
  p.[notnull] AS col_is_not_null
FROM sqlite_master m
LEFT OUTER JOIN pragma_table_info((m.name)) p
  ON m.name <> p.name
WHERE m.type = 'table'
ORDER BY table_name, col_id

Thanks to @David Garoutte for showing me how to get pragma_table_info to work in a query.

Run this query to see all the table metadata:

SELECT * FROM sqlite_master WHERE type = 'table'

In case if you want to get all column names into one single comma separated string, you can use below.

SELECT GROUP_CONCAT(NAME,',') FROM PRAGMA_TABLE_INFO('table_name')

Here the pragma table_info is used as pragma_table_info for the select statement and GROUP_CONCAT is to combine all the field names into one string. for the second parameter of GROUP_CONCAT you can pass the separator.

Related