Sub topic 6
Limiting what users can see
This chapter assumes you can write SELECT queries with joins, you know CREATE VIEW from the earlier chapters, and you know how GRANT and REVOKE work on tables. It uses the employees and departments tables from the sample schema. Examples use PostgreSQL syntax, and the text notes where other systems differ.
The idea: expose a query, not a table
Privileges in SQL are granted on whole objects. If you grant SELECT on employees, the user can read every column and every row, including salary and email. A view lets you grant access to a smaller thing. You write a query that returns only the columns and rows you want to share, save it as a view, and grant access to the view alone.
A view limits access in two ways:
- Column filtering. The view's select list leaves out sensitive columns.
- Row filtering. The view's
WHEREclause leaves out rows the user should not see.
The user can then read the view without holding any privilege on the base tables.
Hiding columns
The employee_directory view from the earlier chapter exposes only id, name and department. It joins employees to departments but never selects salary, email or status.
To make this a real restriction, remove any direct access to the base table and grant access to the view.
-- PostgreSQL. Run as the owner of the tables and the view.
CREATE ROLE analyst NOLOGIN;
REVOKE ALL ON employees FROM analyst;
REVOKE ALL ON departments FROM analyst;
GRANT SELECT ON employee_directory TO analyst;Now test it by acting as the analyst role.
SET ROLE analyst;
SELECT * FROM employee_directory; -- works: id, name, department
SELECT salary FROM employees; -- ERROR: permission denied for table employees
RESET ROLE;The analyst can run any query against the view, such as filtering, sorting or aggregating. The analyst cannot reach a column the view does not expose.
Hiding rows
A WHERE clause in the view definition removes rows before the user's own query runs. This view shows only active employees and omits pay data.
CREATE VIEW active_directory AS
SELECT e.id,
e.name,
d.name AS department
FROM employees e
JOIN departments d ON d.id = e.department_id
WHERE e.status = 'active';
GRANT SELECT ON active_directory TO analyst;A user cannot undo the filter. A query such as SELECT * FROM active_directory WHERE status = 'inactive' fails because the view has no status column. A query that filters on a column the view does expose can only narrow the result further.
Whose privileges does the view use?
When the analyst queries a view, the database must decide whose privileges to check on the base tables. If it used the analyst's, the analyst would need access to employees and the whole scheme would fail. Most systems check the view owner's privileges on the base tables and the caller's privileges on the view. This is called definer rights.
| System | Default behavior | How to change it |
|---|---|---|
| PostgreSQL | Base tables are checked as the view owner. | `WITH (security_invoker = true)` in version 15 and later checks as the caller. |
| MySQL | `SQL SECURITY DEFINER`. | `SQL SECURITY INVOKER` in the view definition. |
| SQL Server | Ownership chaining: if the view and base tables have the same owner, only the view permission is checked. | Break the chain with a different owner, or use explicit `DENY`. |
| Oracle | The view owner must hold the base-table privileges directly, not through a role. | Not applicable. |
Invoker rights are the right choice when you want the view to be a convenience and want the base-table permissions to still apply. Definer rights are the right choice when the view is the security boundary.
Filtering rows by the current user
Sometimes each user should see a different slice of the data. A view can compare a column with a function that returns the session's user name. First you need a table that maps users to the departments they may see.
CREATE TABLE department_access (
role_name VARCHAR(100) NOT NULL,
department_id INTEGER NOT NULL REFERENCES departments (id),
PRIMARY KEY (role_name, department_id)
);
CREATE VIEW my_department_staff AS
SELECT e.id,
e.name,
e.department_id
FROM employees e
JOIN department_access a ON a.department_id = e.department_id
WHERE a.role_name = session_user;
GRANT SELECT ON my_department_staff TO analyst;Each user who queries my_department_staff gets only the employees in departments listed for their own login. The analyst gets no access to department_access itself.
Aggregates as a privacy tool
A view can share totals without sharing rows. A manager can see how much each department costs without seeing any individual's salary.
CREATE VIEW department_payroll AS
SELECT d.name AS department,
COUNT(*) AS headcount,
SUM(e.salary) AS total_salary
FROM employees e
JOIN departments d ON d.id = e.department_id
GROUP BY d.name;Watch for small groups. If a department has one employee, total_salary is that person's salary. A common safeguard is to add HAVING COUNT(*) >= 5 so tiny groups never appear.
Writes through a restricted view
Restricting reads is only half the job. If the view is updatable, the user can also write through it, and the earlier chapter on WITH CHECK OPTION applies here. Without it, a user with UPDATE on active_employees could set a row's status to 'inactive'. The row would then disappear from the view and the user could not see or fix it. Grant only the privileges the role needs, such as SELECT alone for read-only roles, and add WITH CHECK OPTION to any view you open to writes.
Where views fall short as security
Views are a good, simple tool, but they have limits you should know.
- Leaky functions. The optimizer may push a user's condition below the view's filter. If that condition calls a function that raises an error or logs its input, it can reveal values from rows the view should hide. In PostgreSQL, create such views with
WITH (security_barrier = true). This stops the optimizer from running user conditions before the view's own filter, at some cost in plan quality. SELECT *in the definition. In most systems the column list is fixed when the view is created, so new columns added later do not appear. Still, spell out the columns. It makes the review of what is exposed explicit.- Error messages and timing. Constraint violations, such as a duplicate key on insert through a view, can reveal that a hidden row exists.
- Ownership. Whoever owns the view holds the base-table privileges it depends on. A view owned by a superuser exposes whatever the superuser could read. Create security views under a dedicated owner role with only the privileges the views need.
- Not a replacement for row-level security. If you need policies enforced for every query path, including direct table access, use the database's row-level security feature where it exists, such as
CREATE POLICYin PostgreSQL. Views only protect the paths that go through them.
A checklist for a restricted view
- Choose the columns and rows the audience may see, and write the query.
- Create the view under an owner role that holds only the privileges it needs.
- Revoke the audience's access to the base tables, including any inherited access.
- Grant
SELECTon the view, and write privileges only if required, withWITH CHECK OPTION. - Test as the audience role: the view works, and the base tables are refused.
- Review the view when the base tables change.
Exercise
The role reporting currently has SELECT on the whole employees table. You want it to see only id, name and email of active employees. Which statements do you need, and why is the REVOKE necessary?
Show answer
Create a view such as CREATE VIEW active_contacts AS SELECT id, name, email FROM employees WHERE status = 'active';, then GRANT SELECT ON active_contacts TO reporting;, and REVOKE SELECT ON employees FROM reporting;. The REVOKE is necessary because the existing table privilege lets reporting query employees directly, which bypasses the view's column and row limits.
Exercise
In PostgreSQL, a view my_department_staff is defined with WHERE a.role_name = session_user. A teammate proposes replacing it with a view that has security_invoker = true, and the analyst has no privileges on employees. What happens when the analyst queries the view, and why?
Show answer
The query fails with a permission denied error on employees. With security_invoker = true, PostgreSQL checks the base-table privileges as the caller instead of the view owner. Because the analyst has no SELECT on employees, the view cannot read it.