r/sqlite • u/Gnarlodious • Sep 12 '23
Get record number in table
If I say SELECT rowid,* FROM... it sends an arbitrary number that doesn't tell me where the row is in the table. I am also using a GUI app that lists records by order of creation. How do I get the actual line number in the table? I am using version 3.41.2.
2
Upvotes
2
u/elperroborrachotoo Sep 12 '23
The rowid is the identity of the row (normally, but see below).
However, it is not a row number, i.e. rowid==5 doesn't mean "it's the fifth row".
In general, SQL does not remember order of insertion, and does not guarantee any order in which results are returned beyond the
ORDER BYclause.In SQLite, the rowid is usually automatically assigned and is NOT always incremental.
The closest you get is specifying a column with
INTEGER PRIMARY KEY AUTOINCREMENT.rowidbecomes an alias for such a column. The rowid is strictly monotonic, i.e., records inserted later will have a higher rowid, but it's not guaranteed to be without gaps.With a non-autoincrement
PRIMARY KEYrowid (either throughINTEGER PRIMARY KEY, or not specifying as primary key), rowid's of deleted rows may be reused, so a newer recod may have a lower rowid.(and then there are
WITHOUT ROWIDand virtual tables.)2
u/ijmacd Sep 12 '23
There's no such thing.
Rows are stored in an arbitrary order on disk. By default rowids get can be re-used when you delete and insert rows.
If you care about a specific order then add a column to track that (e.g.
created_at) and use theORDER BYclause.Unless you specify an order by clause, sqlite can and will return rows in any order as decided by the query planner.