0

Using PostgreSQL, is it somehow possible to restrict the SELECT privilege of a certain user so that he can only select a certain limited number of rows from a certain table?

For example, user joe should be allowed to execute

SELECT * FROM my_table WHERE id = 17;

but at the same time should not be allowed to execute (because it matches more than 1 row)

SELECT * FROM my_table;

To clarify, id = 17 is of course just an example here. I'm actually looking for a way to allow joe to execute SELECT ... FROM my_table WHERE ... only if the query returns at most one row. I obviously can't simply use GRANT SELECT ON my_table TO joe to solve this, but is it still somehow possible?

5
  • 3
    Use functions to access tables and give the user only access to this functions and revoke all direct access to the tables. Commented Dec 30, 2024 at 13:55
  • See the documentation. In particular the Limit clause. Commented Dec 30, 2024 at 18:15
  • 1
    @Belayer How does LIMIT relate to access privileges? Commented Dec 30, 2024 at 21:05
  • I actually want to have count(*) <= 1 as constraint. Please provide enough info, because it is unclear how you would create this constraint. Commented Dec 31, 2024 at 13:24
  • 1
    @Luuk I doubt it's about an actual, literal SQL constraint - OP seems to be looking for a way to constrain/restrict a user, imposing a limit of how many rows they are allowed to get at any time from a given table. Whether that's going to be handled by RLS, the privilege system, a routine, a rule, a view or a configuration setting, is less important, since it's not immediately obvious how to do that with any of these. Except by revoking all access and forcing the user to interface with everything through functions that strap on a limit clause everywhere. Commented Dec 31, 2024 at 13:38

1 Answer 1

0

In PostgreSQL, you can't directly enforce a limit on the number of rows a user can retrieve with a SELECT statement at the database permission level. However, you can achieve the desired behavior by using Row-Level Security (RLS) or by creating a security-definer function that restricts access.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.