How to get last entry from sqlite in flutter?

Viewed 4781

I have seen many answers in SO but all are related to android.

I want to get the last ID entered in the table.This is my user table:

await db.execute("CREATE TABLE User("
          "userId INTEGER PRIMARY KEY,"
          "first_name TEXT,"
          "last_name TEXT,"
          "user_password TEXT,"
          "mobile_no TEXT,"
          "email_id TEXT," 
          ")");
    print("User Table created");
2 Answers

You can use the Order by and Limit keywords. I can't test it myself right now, but google said they are supported on sqflite. Should look something like this:

db.rawQuery("SELECT * FROM $table ORDER BY userId DESC LIMIT 1");

Or like this:

 db.query(
      dbTable, 
      orderBy: "userId DESC",
      limit: 1
    );
final database = await db;
final data = await database.rawQuery('SELECT * FROM User');
final lastId = data.last['userId'];
Related