Skip to content
  • Users, Roles, GRANT & REVOKE · SQL

Users, Roles, GRANT & REVOKE

LearnViaNotes @learnvianotes· 2 min read

DCL controls who may do what on which objects. Grant the minimum needed — the principle of least privilege.

Users and roles

A role is a named bundle of privileges; users get privileges by being members of roles. Manage roles, not individual grants.

PostgreSQL
CREATE ROLE analyst;                                    -- a group of privileges
CREATE ROLE app_rw;
CREATE USER priya WITH PASSWORD 's3cret';               -- PostgreSQL: a role that can log in
GRANT analyst TO priya;

GRANT and REVOKE

PostgreSQL (MySQL / SQL Server are similar)
-- read-only reporting
GRANT SELECT ON employees, departments TO analyst;

-- the application: data changes, no schema changes
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_rw;

-- column-level: hide salary from HR assistants
GRANT SELECT (emp_id, name, dept_id) ON employees TO hr_assistant;

-- let a user pass on the privilege
GRANT SELECT ON orders TO team_lead WITH GRANT OPTION;

REVOKE DELETE ON orders FROM app_rw;
REVOKE analyst FROM priya;
PrivilegeAllows
SELECTRead rows (optionally only some columns)
INSERT / UPDATE / DELETEChange data
EXECUTERun a procedure/function
REFERENCESCreate a foreign key pointing at the table
CREATE / ALTER / DROPSchema changes (usually only for migration users)
ALL PRIVILEGESEverything on the object — avoid for applications

Row-level and view-based security

SQL
-- expose a safe subset through a view and grant access only to the view
CREATE VIEW employee_public AS
SELECT emp_id, name, dept_id, hire_date FROM employees;     -- no salary, no email

SELECT * FROM employee_public WHERE dept_id = 3 ORDER BY emp_id;
Output
emp_id | name   | dept_id | hire_date
-------+--------+---------+-----------
8      | Vikram | 3       | 2018-09-05
9      | Sara   | 3       | 2023-01-09
PostgreSQL (row-level security)
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY own_orders ON orders
    USING (customer_id = current_setting('app.customer_id')::int);

Checklist

  • Separate accounts for the app, migrations, analysts and admins.

  • No application connects as root/postgres/sa.

  • Revoke defaults you don't need (e.g. PostgreSQL's CREATE on public for everyone before v15).

  • Store credentials in a secret manager; rotate them; require TLS.

  • Audit privileged actions and review grants periodically.

What is the difference between GRANT and REVOKE?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report