Mrunal Joshi
Mrunal Joshi

Reputation: 377

How to get last entry from sqlite in flutter?

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");

Upvotes: 7

Views: 9373

Answers (2)

Benedikt J Schlegel
Benedikt J Schlegel

Reputation: 1939

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
    );

Upvotes: 22

CopsOnRoad
CopsOnRoad

Reputation: 267524

final database = await db;
final data = await database.rawQuery('SELECT * FROM User');
final lastId = data.last['userId'];

Upvotes: 1

Related Questions