Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you use SQLite ROWID as a Primary key?

This does not execute:

create table TestTable (name text, age integer, primary key (ROWID))

The error message is:

11-23 11:05:05.298: ERROR/Database(31335): Failure 1 (table TestTable has no column named ROWID) on 0x2ab378 when preparing 'create table TestTable (name text, age integer, primary key (ROWID))'.

However, after the TestTable is created, this prepares and executes just fine:

create table TestTable (name text, age integer);

insert into TestTable (name, age) values ('Styler', 27);

select * from TestTable where ROWID=1;

I could potentially see ROWID as being a solution to needing an auto-increment primary key and foreign key which are never going to be used as populated as data on the application layer. Since ROWID is hidden from select result sets by default, it would have been nice to associate this with the primary key while keeping it hidden from the application logic. OracleBlog: ROWNUM and ROWID say this is impossible and inadvisable, but doesn't provide much explanation other than that.

So, since the answer to 'is this possible' is definitely no/inadvisable, the question is more or less 'why not'?

like image 680
tyler Avatar asked Nov 23 '11 17:11

tyler


1 Answers

Summary from SQLite.org:

In SQLite, table rows normally have a 64-bit signed integer ROWID which is unique among all rows in the same table. (WITHOUT ROWID tables are the exception.)

If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID. You can then access the ROWID using any of four different names, the original three names (ROWID, _ROWID_, or OID) or the name given to the INTEGER PRIMARY KEY column. All these names are aliases for one another and work equally well in any context.

Just use it as the primary key.

like image 147
Eugene Avatar answered Oct 03 '22 02:10

Eugene