First, this code does not work in any database:
INSERT INTO "Example"
VALUES (SELECT MAX(entryID)+1 FROM "Example"), 2);
It is missing the parentheses around the subquery. This is more naturally written as INSERT . . . SELECT
, rather than INSERT . . . VALUES
. The narrow answer to your question is COALESCE()
:
INSERT INTO "Example" (EntryId, Number)
SELECT COALESCE(MAX(entryID) + 1, 1), 2
FROM "Example";
Note the column list in the INSERT
. It is a best practice to always include those.
This is the narrow answer, because this is not the right way to have an incrementing id. You don't specify your database, but basically most databases have a syntax for incremental ids -- usually using syntax such as identity
, auto_increment
, serial
, or generated always as
. This is the right way to add an incremental id.
Why is it the right way? Your method can result in duplicates in a multi-threaded environment, where two inserts are made at the same time.