Search code examples
sqlnode.jstypeorm

TypeORM - How to remove last added row?


I'm trying to remove only the last added row. Instead, of the last one, it removes all rows.

this.connection.getRepository(EditorEvent)
    .createQueryBuilder('editor_events')
    .orderBy('created_at', 'DESC')
    .limit(1)
    .delete()
    .execute();

I was thinking about adding where corresponding to the newest date but I feel it's not a good approach to solve this problem.


Solution

  • Use a subquery to query the last insert row first, then delete this row by the returned id:

    await connection.getRepository(EditorEvent).createQueryBuilder()
        .delete()
        .where(qb => `id IN (${qb.createQueryBuilder()
                .select('id')
                .from(EditorEvent, 'ev')
                .orderBy('created_at', 'DESC')
                .limit(1)
                .getQuery()})`;
        ).execute();