r/sqlite•
Maykey

How to insert a value if only it doesn't exist but make RETURNING return a value in either case?

Let's say I have a table which holds some unique value

sqlite> CREATE TABLE t(key TEXT NOT NULL unique);
sqlite> INSERT INTO t(key) VALUES('foo');

Now I want to make a query that A) inserts a unique value if it doesn't exist, B) doesn't insert a value if it already exists with no error, C) returns some field(we'll use rowid) along the way

My initial attempt works for the case if value doesn't exist:

sqlite> INSERT  INTO t(key)  VALUES('foo3') 
ON CONFLICT DO NOTHING 
RETURNING ROWID;

3

However if we try to do the same once again

sqlite> INSERT INTO t(key) VALUES('foo3') 
ON CONFLICT DO NOTHING 
RETURNING ROWID;

SQLite interprets "DO NOTHING" too literally and skips the "RETURNING" part. How to trigger RETURNING part in both cases: when value exists and when doesn't?

I can do something stupid like ...on conflict do update set key=key returning rowid; which does produce expected result, but it seems sketchy (and also it's not being optimised out: if I try the same trick with other field, EXPLAIN produces different plan: in key=key it wants to touch index).

Posted Jun 13, 2022, 3:59 PM UTC

31
[deleted]•

[deleted]

1
[deleted]•

Your last version using on conflict do update with a dummy set works fine.

Another solution would be insert or replace into t (key) values ('foo3') but this changes the rowid whenever the key is replaced.

Since SQLite is meant to be used from a programming language, you can also split the query into a select and an insert like this (Python):

def select_or_insert(key):
    query1 = """
        select id from t where key = :key
        """
    query2 = """
        insert into t (key) values (:key) returning id
        """
    cursor = conn.execute(query1, dict(key=key))
    row = cursor.fetchone()
    if row is None:
        cursor = conn.execute(query2, dict(key=key))
        row = cursor.fetchone()
    return row[0]  # id

To decide which solution to chose, measure. It turns out that the first two solutions require about the same time to execute but the third solution with the two separate queries is considerably faster.

Here is a complete test script in Python:

from contextlib import closing
import random
import sqlite3
import string
import time


def random_key(length):
    return ''.join([random.choice(string.ascii_letters)
                    for _ in range(length)])


def setup_database(conn):
    conn.executescript("""
        drop table if exists t;

        create table t (
            id integer not null primary key,
            key text not null unique
        );
        """)


def test_upsert(conn, keys):
    query = """
        insert into t (key) values (:key)
        on conflict do update set id = id
        returning id
        """
    key = random.choice(keys)

    cursor = conn.execute(query, dict(key=key))
    row = cursor.fetchone()
    return row[0]  # id


def test_replace(conn, keys):
    """Drawback: changes id when replacing"""
    query = """
        insert or replace into t (key) values (:key)
        returning id
        """
    key = random.choice(keys)

    cursor = conn.execute(query, dict(key=key))
    row = cursor.fetchone()
    return row[0]  # id


def test_two(conn, keys):
    """Drawback: not pure SQL"""
    query1 = """
        select id from t where key = :key
        """
    query2 = """
        insert into t (key) values (:key) returning id
        """
    key = random.choice(keys)

    cursor = conn.execute(query1, dict(key=key))
    row = cursor.fetchone()
    if row is None:
        cursor = conn.execute(query2, dict(key=key))
        row = cursor.fetchone()
    return row[0]  # id


def main():
    db_file = 'test.db'
    num_queries = 1_000
    seed = 236425

    random.seed(seed)

    keys = [random_key(8) for _ in range(100)]

    tests = [
        ('test_upsert', test_upsert),
        ('test_replace', test_replace),
        ('test_two', test_two),
    ]

    print('separate transactions')

    for test_name, test_fn in tests:
        print(f'    {test_name}')

        random.seed(seed)

        with closing(sqlite3.connect(db_file)) as conn:
            with conn:  # Automatically commits or rolls back the transaction
                conn.execute('begin')  # required
                setup_database(conn)

            t0 = time.time()

            # Slow!
            for _ in range(num_queries):
                with conn:
                    conn.execute('begin')
                    test_fn(conn, keys)

            t1 = time.time()
            t_query_ms = (t1 - t0) * 1_000 / num_queries
            print(f'       elapsed: {t_query_ms:.1f} ms / query')

    print('combined transactions')

    for test_name, test_fn in tests:
        print(f'    {test_name}')

        random.seed(seed)

        with closing(sqlite3.connect(db_file)) as conn:
            with conn:
                conn.execute('begin')
                setup_database(conn)

            t0 = time.time()

            with conn:
                conn.execute('begin')
                for _ in range(num_queries):
                    test_fn(conn, keys)

            t1 = time.time()
            t_query_us = (t1 - t0) * 1_000_000 / num_queries
            print(f'       elapsed: {t_query_us:.1f} us / query')


if __name__ == '__main__':
    main()
1