Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I write the two queries in one query?

I use infinite scroll at my site and I have to return two variables.

The first one is data like 10 users.

the second one is total. Total all users from my whole table.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now my query is this:

    const total= await pg.query('SELECT COUNT(*) as total FROM users;');
    const users = await pg.query('SELECT * FROM users LIMIT 50 OFFSET $1', [offset]);

I do not fetch all users directly I set a limit, but I have to say to my infinite scroll how much users I have in my users table so I wrote two queries but it is possible to write it in one query ?

>Solution :

You could write a subquery

const users = await pg.query('SELECT *,(SELECT COUNT(*) as total FROM users) AS Total_count FROM users LIMIT 50 OFFSET $1', [offset]);

Every row would have the total user count as further row, which you can exract.

FYI SELECT * is bad style.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading