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

1.6k Views Asked by At

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?

2

There are 2 best solutions below

0
milut.in On BEST ANSWER

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();
0
Ayrton Everton On

More efficient alternatives that don't need to go through select on a specific table:

const [{ id }] = await dataSource.query("SELECT NEXTVAL('users_id_seq') AS id");

OR

const [{ id }] = await userRepository.query("SELECT NEXTVAL('users_id_seq') AS id");

NOTE: When using select from createQueryBuilder, you are not just getting the next value in the sequence, you are actually bringing a next value to each row of the select in this table (Repository), that is, it is a column in the select.