Quick revision
The short answer
I would move the endpoint off the primary to a replica or a reporting database fed by CDC, precompute per-department ranked distinct salaries on a schedule or on change, index (dept_id, salary DESC) and cap N, and treat salary data as sensitive: authorization at the API and in the database, access logging, and a minimum group size so small departments cannot reveal one person's pay. Freshness is agreed with HR, and payroll-time figures rarely need to be real time.
What to remember
In this answer, we redesigned the Nth-highest-salary endpoint. Reads move off the primary to a replica or a reporting database fed by CDC, with salary data classified as sensitive and every access logged. Per-department ranked distinct salaries are precomputed in a materialized view refreshed concurrently, which needs a unique index, and any live query uses an index on (dept_id, salary DESC) with N capped and validated. Authorization sits in the API and in the database through row level security or a filtering view, small groups are protected by a minimum size, and freshness is agreed with HR so precomputation is acceptable.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would move the endpoint off the primary to a replica or a reporting database fed by CDC, precompute per-department ranked distinct salaries on a schedule or on change, index (dept_id, salary DESC) and cap N, and treat salary data as sensitive: authorization at the API and in the database, access logging, and a minimum group size so small departments cannot reveal one person's pay. Freshness is agreed with HR, and payroll-time figures rarely need to be real time.
Why this question is asked
An internal endpoint that started as a quick helper for one HR dashboard has become a load problem and a security problem at the same time. That combination is common: the thing that made it easy to build, running live SQL on the main database with few checks, is exactly what now hurts. Interviewers ask this scenario because the right answer joins performance design with data protection, and many candidates only see one half. In this answer, we will look at why the current design spikes CPU, move the reads, precompute the rankings, index and validate the remaining queries, lock down who can see salaries, handle small groups, and agree freshness with HR.
1Why the Current Design Hurts
Each call runs something like DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) on the primary, the database that also runs payroll. Without a suitable index, each call reads and sorts the employees of the department, and some versions of the query rank the whole table before filtering. When payroll runs, the same tables are busy with heavy writes and reads, and dashboards refresh more often because people want numbers. The CPU spikes are the two workloads colliding.
The security side is just as serious. Salary is personal data. Today, anyone who can call the endpoint can ask for any department and any N, which means they can walk N from 1 upwards and list every distinct salary in every department, and there is probably no log of who did it.
2Moving the Reads Off the Primary
The first change is where the query runs. A read replica takes the load off the primary with almost no lag. A reporting database fed by CDC, change data capture that streams committed changes from the primary's log, is even better here, because it lets us keep only the columns HR analytics needs, not names, bank details or addresses. In both cases the reporting copy is classified as sensitive, encrypted, and every read through the API is logged with the caller, the department and N.
- HR dashboardcalls the API with a user token
- Analytics APIchecks role and department, caps N, logs every call
- Reporting databasesalary ranks per department, RLS, no names
- CDC or nightly loadonly the columns analytics needs
- Primary HR databasepayroll and HR apps only
5 layers, from the top down. Step through them one at a time.
3Precomputing the Rankings
Salaries change rarely, a few times a year per person, but the endpoint reads them all the time. So we compute the answer once: for each department, the distinct salaries sorted, with their rank and the number of people at each salary. A materialized view does that, and we refresh it nightly or after a payroll change is loaded.
Notice the unique index. REFRESH MATERIALIZED VIEW CONCURRENTLY compares the old and new contents row by row and needs a unique index to do it; without one it refuses to run. The concurrent refresh is slower than a plain refresh but does not lock out readers, which matters for an API. The answer for any department and N is now one index lookup on a small table.
4Indexing and Validating What Remains
If some queries must still run against the live employee table, for example on the replica, an index on (dept_id, salary DESC) turns a per-department ranking into an index range scan: the database jumps to the department and reads its salaries already in order, stopping after N distinct values with the offset form. We also cap N, say at 50, and validate department ids against the caller's permissions, because an unlimited N is both a load problem and a way to dump every salary.
5Controlling Who Can See Salaries
Authorization belongs in two places. The API checks the caller's role and which departments they may see, from the HR system's own access rules, before running any query. The database enforces the same rule as a second line, so a bug in the API or a direct connection cannot bypass it. PostgreSQL row level security, RLS, adds a policy that filters rows per user. One detail: RLS applies to tables, not materialized views, so we either load the ranks into a regular table or expose the view through a security barrier view that filters by the caller's departments, and grant access only to that.
Every call is logged with who asked, which department and which N, and security can review unusual patterns, such as one user stepping through N from 1 to 40 across many departments.
6Stopping Small Groups From Revealing One Person
Aggregates can leak individuals. In a department of three, the highest salary is one person's salary, and most colleagues know who that is. The usual protection is a minimum group size, sometimes called k-anonymity: we only answer when enough people stand behind the number. A rule might be that the department has at least 10 people and the salary value has at least 3 people at or around it, otherwise we return a range or nothing.
- Is the caller allowed this department?YesContinueNoRefuse and log
- Is N between 1 and the cap?YesContinueNoReject the request
- At least 10 people in the department?YesLook up the rank tableNoReturn a band or nothing
- Return value and log the callwho, department, N, time
4 steps in order. Play them, or step through them one at a time.
Because the materialized view already stores people per salary, the API can apply this rule cheaply. Often the better product answer is to offer percentiles or salary bands per department instead of exact Nth values, which answers the real HR question, such as pay spread, with far less risk.
7Agreeing Freshness With HR
Finally, we ask HR how fresh the numbers need to be. During a payroll run, numbers from last night or from the last approved salary change are almost always what they want, because figures that move during the run are confusing. That agreement is what makes precomputation, caching and a lagging reporting database acceptable. We show the as-of time on the dashboard, and if HR needs a fresh figure after a change, they can trigger a refresh of the view.
8Follow-up questions
How would you stop small groups from revealing individual salaries?
Enforce a minimum group size before answering, such as at least 10 people in the department and several at the salary value, and return a band, a percentile or nothing otherwise. Also watch for differencing attacks, where two overlapping queries reveal one person, by limiting which slices can be asked and logging access.
Why not cache the API responses in Redis instead?
Caching would reduce load, but each new department and N combination still hits the database, and the cache becomes another copy of sensitive data to protect. Precomputing a small rank table solves the load at the source and keeps the data in one controlled place.
Does REFRESH MATERIALIZED VIEW CONCURRENTLY have a cost?
Yes. It builds the new result and computes the difference against the old one, which takes longer and needs more temporary space than a plain refresh. For a few thousand rows per department that is negligible, and it keeps reads available.
9Conclusion
In this answer, we redesigned the Nth-highest-salary endpoint. Reads move off the primary to a replica or a reporting database fed by CDC, with salary data classified as sensitive and every access logged. Per-department ranked distinct salaries are precomputed in a materialized view refreshed concurrently, which needs a unique index, and any live query uses an index on (dept_id, salary DESC) with N capped and validated. Authorization sits in the API and in the database through row level security or a filtering view, small groups are protected by a minimum size, and freshness is agreed with HR so precomputation is acceptable.
Open with
I see two problems, load and exposure, and I would fix them together. For load, the query should not run on the primary that does payroll. I would serve it from a reporting database fed by CDC, or at least a replica, and copy only the columns analytics needs.
Then, if they want more
Since salaries change rarely, I would precompute per department the distinct salaries with their dense rank and the number of people at each, in a materialized view refreshed nightly or after a payroll load, using refresh concurrently so readers are not blocked, which needs a unique index on department and rank. Then any request is one index lookup.
If some queries still hit the employee table, an index on department and salary descending makes them range scans, and I cap N and validate the department.
For exposure, I classify the data as sensitive, check authorization in the API against HR's access rules, and enforce it again in the database with row level security or a security barrier view, since RLS does not apply to materialized views directly. Every call is logged with caller, department and N.
I would also add a minimum group size so a small department cannot reveal one person's salary, and suggest bands or percentiles instead of exact values. Finally I agree freshness with HR; payroll-time numbers rarely need to be real time.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "An internal HR analytics API exposes an endpoint that returns the Nth highest salary for...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/c543586410/