SQLite Forum

NEXT VALUE FOR in SQLite
Login
So do you want to create an incrementing counter, or do you want to update the value and get a returned value back? Those two are not the same.

For creating a counter, Richard's example will work a treat, and it can never return a value because it happens invisibly to the statements (i.e. In the background).

For the second option, should the counter increase by being updated? or upon inserting a new row?

If updating a value and getting the new value back, that can be achieved with this type of query - imaging there is a table "t" with an integer field "i" in record with "id" 5 that will be our update target:

```
UPDATE t SET i = IFNULL((SELECT MAX(i) FROM t),0) + 1 
 WHERE id = 5
RETURNING i
```

If it has to be an Insert query then a very similar (assuming id is also a Autoinc PK):

```
INSERT INTO t(i, x, y....) VALUES
(IFNULL((SELECT MAX(i) FROM t),0) + 1, x-value, y-value, ... )
RETURNING id, i
```

BIG NOTE: You need a very recent release of SQLite to be able to use the "RETURNING" clause.

ALSO NOTE: I've not tested these, the principle is sound but there may be syntax errors. [The docs are your friend](https://sqlite.org/lang_returning.html).