Answer the question
In order to leave comments, you need to log in
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
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question