Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite query to find primary keys

In SQLite I can run the following query to get a list of columns in a table:

PRAGMA table_info(myTable)

This gives me the columns but no information about what the primary keys may be. Additionally, I can run the following two queries for finding indexes and foreign keys:

PRAGMA index_list(myTable)
PRAGMA foreign_key_list(myTable)

But I cannot seem to figure out how to view the primary keys. Does anyone know how I can go about doing this?

Note: I also know that I can do:

select * from sqlite_master where type = 'table' and name ='myTable';

And it will give the the create table statement which shows the primary keys. But I am looking for a way to do this without parsing the create statement.

like image 741
Kyle Avatar asked May 06 '12 16:05

Kyle


People also ask

How do I find the primary key of a table in SQLite?

find the record that column 'pk' is 1, it's the primary key.

Is there primary key in SQLite?

In SQLite, a primary key is a single field or combination of fields that uniquely defines a record. A table can have only one primary key. TIP: While the SQL-89 and SQL-92 standards do not allow a NULL value in a primary key, SQLite does allow a NULL under certain circumstances.

How do I know if a primary key exists?

To check if a primary key exists on a table uses the system stored procedure named SP_PKEYS or view INFORMATION_SCHEMA.


2 Answers

The table_info DOES give you a column named pk (last one) indicating if it is a primary key (if so the index of it in the key) or not (zero).

To clarify, from the documentation:

The "pk" column in the result set is zero for columns that are not part of the primary key, and is the index of the column in the primary key for columns that are part of the primary key.

like image 114
Mattias Isegran Bergander Avatar answered Oct 03 '22 18:10

Mattias Isegran Bergander


Hopefully this helps someone: After some research and pain the command that worked for me to find the primary key column name was:

SELECT l.name FROM pragma_table_info("Table_Name") as l WHERE l.pk = 1;
like image 40
Oogway101 Avatar answered Oct 03 '22 18:10

Oogway101