If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

SQL: CREATE table with a primary key

When you create a table in SQL, you usually want to specify an id column to be the primary key. That will make that value the unique identifier for the row in the table. You can write PRIMARY KEY after a column to make it the primary key.
If you attempt to insert a row with the same primary key as a previous row, you will get a SQL error (try it in the commented out code below). If you insert a row without specifying the primary key, then SQL will automatically pick one for you that's different from other values.
You can also specify AUTOINCREMENT after PRIMARY KEY. When you do that, the SQL engine makes sure that it picks a completely new id, one that wasn't even used by deleted rows. This might be necessary if you are using ids in a user-facing way, and want to guarantee lifetime uniqueness of them. It does take more processing power, so only use AUTOINCREMENT if you need it.
For more details, see the SQLite reference for Data constraints and AUTOINCREMENT.

Want to join the conversation?

No posts yet.