r/SQL • u/Then_Respect_1964 • 10d ago
PostgreSQL I thought aggregates were the safe way to expose sensitive data. Turns out MAX and GROUP BY leak individual values
I’ve been working on access rules for AI agents that query a Postgres database. Some fields are sensitive, like payment amounts, so reading those rows directly needs a person to approve it. Aggregates were allowed without approval, because something like total refunds this quarter seemed harmless. That was the whole point, the agent can do analytics without seeing anyone’s actual payments.
Then I started testing it with queries an agent might actually write, and the rule fell apart pretty quickly.
MAX(amount) isn’t a summary of anything, it’s one real payment from one row. Same with MIN. And SUM(amount) GROUP BY customer_id gives you one total per customer, which is basically reading the sensitive column customer by customer with extra steps. All of these went through as aggregates and skipped the approval.
The problem was the rule was checking what kind of function the query used, not how many rows were actually behind each value it returned. An aggregate over a million rows and an aggregate over one row looked exactly the same to it.
MIN and MAX were the easy part, they now count as row reads so they follow the same approval rules. Grouping I haven’t settled yet. One option is treating GROUP BY on identifier columns as row access, but then you need to know which columns are identifiers, and near-unique stuff like emails or exact timestamps slips through. The other is a minimum group size, k-anonymity style, which catches more but changes the results, and someone running overlapping queries can still narrow things down. Or some mix of both.
I put the full investigation in a comment. Has anyone dealt with this in a reporting tool or an analytics API? Would be interesting to hear what actually worked in practice.
