Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query for last id in table

I need to get the id of the last record in my table. I have tried:

Dao<ParticipantModel,Integer> participantDao  = getHelper().getParticipantsDao();
        participant = participantDao.query(participantDao.queryBuilder()
                 .orderBy("id", false).prepare()).get(1);

I'm not sure of how to use the QueryBuilder to get the result I'm looking for. Thanks in advance for any ideas.

like image 994
Inx Avatar asked Apr 08 '13 10:04

Inx


People also ask

How can I get the last ID of a table?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.

How can I get the last inserted ID from a table in SQL?

If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.

How do you get the last ID from a table if it's set to auto increment?

To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT. Creating a table, with “id” as auto-increment.


3 Answers

In my application I do the same just add the limit(int) to prepared query like this:

Dao<ParticipantModel,Integer> participantDao  = getHelper().getParticipantsDao();
    participant = participantDao.query(participantDao.queryBuilder()
         .orderBy("id", false).limit(1L).prepare());
like image 166
Martin Nuc Avatar answered Nov 02 '22 06:11

Martin Nuc


It is more efficient to ask DBMS for maxId in request. Cause DBMS shouldn't perform sorting of rows. There is a good example in this answer

    QueryBuilder<MODEL, ID> qb = dao.queryBuilder().selectRaw("max(id)");
    String[] columns = new String[0];
    try {
        GenericRawResults<String[]> results = dao.queryRaw(qb.prepareStatementString());
        columns = results.getFirstResult();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    if (columns.length == 0) {
        // NOTE: there are not any rows in table
        return 0;
    }
    return Integer.parseInt(columns[0]);
like image 45
Nick7 Avatar answered Nov 02 '22 06:11

Nick7


You can use this simply:

ParticipantModel lastItem = participantDao.queryBuilder().orderBy("id", false).limit(1L).query().get(0);
like image 1
Mahdi Moqadasi Avatar answered Nov 02 '22 08:11

Mahdi Moqadasi