LIMIT & OFFSET SQL practice problemMediumVerified answer

Compute the Total Number of Pages

Pagination UIs need to know the total page count. Given a page size of 4 and the actual employee count, return the page metadata in a single row: total_rows, page_size, total_pages. Use CEIL/CEILING division so a partial last page still counts. Aliases must be EXACTLY: total_rows, page_size, total_pages.

  • Aggregation

Interview brief

Understand the request

Pagination UIs need to know the total page count. Given a page size of 4 and the actual employee count, return the page metadata in a single row: total_rows, page_size, total_pages. Use CEIL/CEILING division so a partial last page still counts. Aliases must be EXACTLY: total_rows, page_size, total_pages.

Data you will use

Review the relevant tables before deciding how to join, filter, or aggregate them.

employees

  • employee_idINTEGER

Hints, when you need them

Open one clue at a time so you still do the reasoning.

Hint 1

The integer-division ceiling trick: `(N + D - 1) / D`. It is portable, exact, and avoids floating-point.

Hint 2

You can also use `CEILING(COUNT(*) * 1.0 / page_size)` (PostgreSQL/SQL Server) or `CEIL(...)` (MySQL/SQLite) — but the integer trick works on every engine.

Hint 3

(COUNT(*) + 4 - 1) / 4 AS total_pages

Verified SQL answer

Attempt the problem first, then compare structure and reasoning—not just syntax.

Reveal solution and explanation
SELECT COUNT(*) AS total_rows, 4 AS page_size, (COUNT(*) + 4 - 1) / 4 AS total_pages FROM employees;

Why this works

For a 15-row table with page_size 4: total_pages = (15 + 4 - 1) / 4 = 18 / 4 = 4 (integer division). The last page (page 4) has only 3 rows. Real apps often expose `hasNextPage = (page < total_pages)` based on this value.

Expected result

Use this output to verify values, aliases, ordering, and row count.

total_rowspage_sizetotal_pages
1544

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics: