J
J
Johnem2021-04-26 17:47:08
Python
Johnem, 2021-04-26 17:47:08

How to make a negative offset in sqlite?

Hello. To be clear, when you specify the OFFSET parameter in the query, it only works with positive numbers (if OFFSET is negative, then sqlite seems to ignore it altogether). Here is my crutch solution:

import sqlite3

def get_data(id, date, limit=1, offset=0):
    con = sqlite3.connect('db.db')
    cur = con.cursor()
    data = []
    if offset < 0:
        cur.execute('SELECT * FROM db WHERE id == ? AND date >= '
                    '(SELECT date FROM db WHERE date <= ? '
                    'ORDER BY _rowid_ DESC LIMIT 1 OFFSET ?) LIMIT ?',
                    (id, date, -offset, limit))
    else:
        cur.execute('SELECT * FROM db WHERE id == ? AND date >= ? '
                    'LIMIT ? OFFSET ?',
                    (id, date, limit, offset))
    for row in cur.fetchall():
        data.append({'date': datetime.date.fromisoformat(row[1]),
                       'name': row[2], 'address': row[3]})
    return data

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-04-26
@vabka

In SQL, according to the standard, OFFSET must always be >=0, so there is no way to force it to be negative.
Your crutch option is quite acceptable.
But I would once again think whether this feature is needed at all.

P
prochanev, 2021-04-29
@prochanev

I don't understand anything :) But what if we sort in the reverse order and apply the usual OFFSET? :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question