how to update latest post sqlite3?

Question:

I need to update the latest entry in the database. While the query works correctly in the DB browser, it doesn’t work in code. Please tell me what’s the matter?

class MySQL:
    def __init__(self):
        self.connection = sqlite3.connect(file_db, check_same_thread=False)
        self.cursor = self.connection.cursor()
        self.add_bd()     
    def update_sell_price(self, sell_price):
        with self.connection:
            self.cursor.execute(
                f'UPDATE Deals SET sell_price={sell_price}  ORDER BY deal_id DESC LIMIT 1')

Gives an error message: sqlite3.OperationalError: near "ORDER": syntax error

Answers:

The LIMIT and ORDER BY Clauses are available in the UPDATE statement only if SQLite is built with the SQLITE_ENABLE_UPDATE_DELETE_LIMIT compile-time option, which I suspect is not what you have in the version that you work with.

Instead use a scalar subquery to get the max deal_id:

sql = """
  UPDATE Deals 
  SET sell_price = ?
  WHERE deal_id = (SELECT MAX(deal_id) FROM Deals)
"""
self.cursor.execute(sql, (sell_price,))
Answered By: forpas
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.