Search code examples
postgresqlnestjstypeormnextval

nextval on sequence returns all nextval values for all table rows in typeORM on postgresql table


I have a sequence in postgreSQL database, and when I run NEXTVAL(sequence_name) query inside pgAdmin 4 it returns only one value that is correct. However inside NestJS project that's bootstrapped with TypeORM when I run this.repo.createQueryBuilder().select("NEXTVAL(sequence_name)").execute() It returns array of objects with all next values generated.

Example: If I have 500 rows inside the table, it will return 500 NEXTVAL values for some reason.

I've tried my best to find a solution online, but no luck. Any ideas?


Solution

  • The solution was fairly simple, thanks @nbk for the comment. This was a solution:

    this.repo
          .createQueryBuilder()
          .where('id = (select MAX(id) FROM table_name)')
          .select("nextval('sequence_name")
          .getRawOne();