Users, Roles and Privileges: GRANT, REVOKE and Row-Level Security
How databases control who can do what: roles, users and group roles, GRANT and REVOKE on tables and columns, views as a security layer, default privileges, row-level security policies, superusers and owners, and least-privilege designs for applications.
kvi5hnuCode Sprout team member11 min readOn this page
A database usually serves many people and programs: the web application, a reporting tool, analysts, support staff, the migration scripts, an administrator. They shouldn't all be able to do everything. The reporting tool has no business deleting orders, and support staff don't need to see payment details. SQL's privilege system controls who can read and change which objects, and row-level security controls which rows they see.
This article covers roles, granting and revoking privileges, using views and column privileges to limit what's visible, row-level security policies, and how to set up an application's database access safely. The examples use PostgreSQL, whose model is close to the SQL standard. Other databases are compared at the end.
Roles, users and groups
In PostgreSQL, every user and every group is a role:
- A role with the
LOGINattribute can connect, so it acts as a user.CREATE USER nameis shorthand forCREATE ROLE name LOGIN. - A role without
LOGINis used as a group: privileges are granted to it, and users become members withGRANT group TO user, orIN ROLE groupwhen the user is created. Members get the group's privileges.

Grant privileges to group roles that describe a job, such as reporting, support or web_app, and make people and programs members of them. When someone joins or leaves the team, you change one membership instead of hunting down dozens of individual grants.
Passwords and how users authenticate, by password, certificate, single sign-on or the operating system, are configured separately, in PostgreSQL's pg_hba.conf and the role's password. Use SCRAM password authentication or better. MD5 passwords are deprecated. Set a password with CREATE ROLE ana LOGIN PASSWORD '...', or change it with ALTER ROLE ana PASSWORD '...'. In psql, \password ana avoids putting the password in the history. MySQL uses CREATE USER 'ana'@'%' IDENTIFIED BY '...'.
GRANT and REVOKE
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A group role holds privileges; login roles (users) are members of it
CREATE ROLE reporting NOLOGIN;
CREATE ROLE ana LOGIN IN ROLE reporting;
GRANT SELECT ON products, orders TO reporting;
-- Act as ana, as if ana had logged in
SET ROLE ana;
SELECT current_user, COUNT(*) AS products FROM products;
SELECT COUNT(*) FROM customers; -- not granted
UPDATE products SET price = 1 WHERE product_id = 1; -- only SELECT was granted
RESET ROLE;
-- Ask the database what a role may do
SELECT t AS table_name,
has_table_privilege('ana', t, 'SELECT') AS can_select,
has_table_privilege('ana', t, 'UPDATE') AS can_update
FROM unnest(ARRAY['products', 'orders', 'customers']) AS t;
-- Tidy up: roles belong to the whole server, not to one database
DROP OWNED BY reporting, ana;
DROP ROLE ana, reporting;
current_user | products
--------------+----------
ana | 7
(1 row)
psql:/workspace/solution.sql:71: ERROR: permission denied for table customers
psql:/workspace/solution.sql:72: ERROR: permission denied for table products
table_name | can_select | can_update
------------+------------+------------
products | t | f
orders | t | f
customers | f | f
(3 rows)
GRANT privilege ON object TO role gives a privilege, and REVOKE privilege ON object FROM role removes it. The example creates the group reporting, grants it SELECT on products and orders, and makes ana a member. Then SET ROLE ana makes the session act as ana, which is a handy way to test permissions without logging in again:
- Reading
productsworks, through the group's privilege. - Reading
customersfails: nothing was granted on it. - Updating
productsfails: onlySELECTwas granted.
has_table_privilege asks the same questions without running anything, which is useful in audits and tests. Roles are shared by all databases on a server, which is why the example drops them at the end.
The main table privileges are:
| Privilege | Allows |
|---|---|
SELECT | reading rows, and referring to columns in UPDATE and DELETE conditions |
INSERT, UPDATE, DELETE | changing data |
TRUNCATE | emptying the table |
REFERENCES | creating a foreign key that references the table |
TRIGGER | creating triggers on the table |
ALL PRIVILEGES | all of the above |
Other objects have their own: USAGE on schemas and sequences, EXECUTE on functions, CONNECT on databases, CREATE on schemas and databases. A role needs USAGE on a schema to reach any table in it, as well as the table privilege.
Privileges are checked when a statement runs, not when the session starts: a REVOKE takes effect on the role's next statement.
WITH GRANT OPTION lets the receiver pass the privilege on to others. Use it sparingly: revoking later needs CASCADE to remove the privileges they granted in turn.
Columns and views
Privileges can be granted on individual columns:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Column privileges: support staff may see names and cities, nothing else
CREATE ROLE support NOLOGIN;
GRANT SELECT (customer_id, name, city) ON customers TO support;
SET ROLE support;
SELECT customer_id, name, city FROM customers WHERE customer_id <= 2 ORDER BY customer_id;
SELECT * FROM customers; -- includes referred_by
RESET ROLE;
-- REVOKE takes a privilege away again
REVOKE SELECT (city) ON customers FROM support;
SET ROLE support;
SELECT name, city FROM customers;
RESET ROLE;
DROP OWNED BY support;
DROP ROLE support;
customer_id | name | city
-------------+------------+-------
1 | Asha Rao | Pune
2 | Ben Okafor | Leeds
(2 rows)
psql:/workspace/solution.sql:68: ERROR: permission denied for table customers
psql:/workspace/solution.sql:74: ERROR: permission denied for table customers
support may read customer_id, name and city. Selecting those columns works, but SELECT * fails, because it includes referred_by, which wasn't granted. After REVOKE SELECT (city), a query that includes city fails too. Column privileges are precise, but they make SELECT * fail, which surprises tools and ORMs.
A view is often the cleaner way to expose part of a table, because it can limit the rows too:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A view can expose chosen rows and columns without granting the table
CREATE ROLE pune_team NOLOGIN;
CREATE VIEW pune_customers AS
SELECT customer_id, name FROM customers WHERE city = 'Pune';
GRANT SELECT ON pune_customers TO pune_team;
SET ROLE pune_team;
SELECT * FROM pune_customers ORDER BY customer_id;
SELECT COUNT(*) FROM customers;
RESET ROLE;
DROP OWNED BY pune_team;
DROP ROLE pune_team;
customer_id | name
-------------+----------
1 | Asha Rao
3 | Chen Wei
(2 rows)
psql:/workspace/solution.sql:70: ERROR: permission denied for table customers
pune_team can read the view, which shows Pune customers' IDs and names, but not the customers table itself. By default, a PostgreSQL view accesses its tables with the privileges of the view's owner, so granting the view is enough (article 56). The view becomes the interface: what's in it is what the team can see.
Default privileges and the PUBLIC role
Two details that cause surprises:
- New tables aren't covered by earlier grants.
GRANT SELECT ON ALL TABLES IN SCHEMA public TO reportinggrants on the tables that exist now. For tables created later, set default privileges:ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO reporting. Defaults apply to objects created later by the role that ran the command, or by the role named withFOR ROLE. PUBLICis a pseudo-role that includes every role. Some privileges are granted toPUBLICby default, such asCONNECTon databases andEXECUTEon functions. Since PostgreSQL 15, ordinary users can no longer create objects in thepublicschema by default, closing a long-standing hole. For tight control,REVOKE ... FROM PUBLICand grant explicitly.
Owners and superusers
The role that creates an object owns it. The owner always has every privilege on it, can grant them to others, and is the only role, besides superusers and members of the owning role, that can ALTER or DROP it.
A superuser bypasses every permission check, including row-level security. Superuser access is for administrators, never for applications: a single SQL injection bug (article 59) in an application connected as a superuser hands over the whole server, which in PostgreSQL can include running programs on the host. PostgreSQL's predefined roles grant specific powers without superuser status, such as pg_read_all_data, pg_monitor and pg_maintain.
Row-level security
Privileges control which tables a role can use. Row-level security (RLS) controls which rows it sees and changes, through policies:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Row-level security: each customer sees only their own orders
CREATE ROLE web_app NOLOGIN;
GRANT SELECT, INSERT ON orders TO web_app;
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY own_orders ON orders
USING (customer_id = current_setting('app.customer_id')::int)
WITH CHECK (customer_id = current_setting('app.customer_id')::int);
SET ROLE web_app;
SET app.customer_id = '1'; -- the application sets this after login
SELECT order_id, customer_id, status FROM orders ORDER BY order_id;
INSERT INTO orders VALUES (201, 1, DATE '2026-03-30', 'pending'); -- own order: allowed
INSERT INTO orders VALUES (202, 2, DATE '2026-03-30', 'pending'); -- someone else's: refused
SET app.customer_id = '2';
SELECT order_id, customer_id, status FROM orders ORDER BY order_id;
RESET ROLE;
-- The table owner (here a superuser) isn't subject to the policy
SELECT COUNT(*) AS all_orders FROM orders;
DROP OWNED BY web_app;
DROP ROLE web_app;
order_id | customer_id | status
----------+-------------+-----------
101 | 1 | shipped
103 | 1 | delivered
(2 rows)
psql:/workspace/solution.sql:76: ERROR: new row violates row-level security policy for table "orders"
order_id | customer_id | status
----------+-------------+---------
102 | 2 | shipped
(1 row)
all_orders
------------
7
(1 row)
ALTER TABLE orders ENABLE ROW LEVEL SECURITYturns RLS on. From then on, roles other than the owner see no rows unless a policy allows them.CREATE POLICY ... USING (condition)adds a filter to every query on the table: rows for which the condition isn't true are invisible, as if they didn't exist. Customer 1 sees orders 101 and 103, and customer 2 sees only 102.WITH CHECK (condition)applies to rows being inserted or updated. Customer 1 can create their own order 201, but not order 202 for customer 2.- The table's owner, here the superuser, isn't subject to the policy and sees all seven orders.
ALTER TABLE ... FORCE ROW LEVEL SECURITYapplies policies to the owner too, but superusers and roles withBYPASSRLSalways bypass them.
The policy compares customer_id with a session setting, app.customer_id, which the application sets after it authenticates the user. This is a common pattern for multi-tenant applications that connect through one database role: each request sets the current tenant or user, and the database guarantees that no query, however buggy, can read another tenant's rows. Two cautions:
- With connection pools, set it with
SET LOCALinside each transaction, so the value can't leak to the next request that uses the connection. - Anyone who can run arbitrary SQL as that role can also change the setting. The pattern protects against application bugs, not against users who can type their own queries. For those, give each user their own database role and write policies with
current_user.
Policies can be specific to commands (FOR SELECT, FOR UPDATE and so on) and to roles (TO role), and several policies combine with OR, or with AND if declared AS RESTRICTIVE. The filter is added to every query, so index the columns it uses.
Least privilege for applications
A sensible setup for an application database:
| Role | Purpose | Privileges |
|---|---|---|
owner role (NOLOGIN) | owns the schema and tables | everything, by ownership |
| migration user | runs schema changes | member of the owner role |
| application user | the running application | SELECT, INSERT, UPDATE, DELETE on its tables, USAGE on sequences |
| read-only user | reporting and analysts | SELECT, through views where needed |
| administrator | operations | superuser, used rarely and never by applications |
The application can read and write data but can't drop tables, change the schema, or read other applications' data. If it's compromised, the damage is limited to what its role can do. Each application and tool gets its own login, so the logs and pg_stat_activity show who did what.
Other databases
| PostgreSQL | MySQL | SQL Server | Oracle | |
|---|---|---|---|---|
| users and groups | roles, with and without LOGIN | accounts 'name'@'host', roles since 8.0 | server logins mapped to database users, database roles | users (each is also a schema), roles |
| row-level security | CREATE POLICY | none (use views) | security policies with predicate functions (2016+) | Virtual Private Database (DBMS_RLS) |
| column privileges | yes | yes | yes, plus DENY | yes |
| DDL in transactions | yes | no | yes | no |
SQL Server also has DENY, which blocks a privilege even if a role membership grants it. MySQL roles must be activated in a session with SET ROLE, or made default with SET DEFAULT ROLE, or set activate_all_roles_on_login.
Column-level privileges for changes
Privileges can be granted on specific columns for changes as well as for reading. GRANT UPDATE (stock) ON products TO warehouse lets the warehouse role change stock levels but not prices, and GRANT INSERT (name, email) ON signups TO web_form limits which columns an insert may supply, leaving the rest to their defaults. PostgreSQL and MySQL support column lists for INSERT, UPDATE, SELECT and REFERENCES, Oracle for INSERT, UPDATE and REFERENCES (use a view to limit the columns someone can read), and SQL Server for SELECT, UPDATE and REFERENCES.
What's current
- PostgreSQL 17 added the
MAINTAINprivilege and thepg_maintainrole, for runningVACUUM,ANALYZE,REINDEXand similar commands without owning the table. - PostgreSQL 18 deprecated MD5 password authentication, warning when such passwords are set, and added OAuth authentication.
- PostgreSQL 16 tightened
CREATEROLE: a role with it can now manage only the roles it created, unless granted more. - PostgreSQL 15 stopped granting
CREATEon thepublicschema to everyone.
Common questions
What's the difference between a user and a role? In PostgreSQL, nothing fundamental: a user is a role that can log in. Groups are roles that can't.
Why can't a new user see the tables I granted to their group?
Check that they're a member of the group, that the group has USAGE on the schema, and that the tables existed when you granted. Use ALTER DEFAULT PRIVILEGES for future tables.
Why does SELECT * fail when some columns are readable?
The role lacks SELECT on at least one column. List the permitted columns, or provide a view.
Should my application connect as the table owner or a superuser? No. Connect as a role with only the data privileges the application needs. Run migrations with a separate role.
Does row-level security slow queries down? It adds the policy's condition to every query. With an index on the columns it uses, the cost is usually small.
Is a view enough for security? A view limits what a role can see, as long as the role has no privileges on the underlying tables. For per-user rows in shared tables, row-level security is more robust.
Summary
- Roles are users (with
LOGIN) and groups (without). Grant to groups that describe jobs, and add members. GRANTandREVOKEcontrol privileges such asSELECT,INSERT,UPDATEandDELETEon tables, columns, schemas, sequences and functions.- Column privileges and views limit what's visible. Views can limit rows as well as columns.
- Earlier grants don't cover new tables: use
ALTER DEFAULT PRIVILEGES. - Owners and superusers bypass normal checks. Applications should use neither.
- Row-level security policies filter rows with
USINGand check new rows withWITH CHECK. - Follow least privilege: separate owner, migration, application and read-only roles.
Practice questions
Create a group role analyst that can read every existing table in the public schema and every table created there later by the current role, and make the existing user omar a member.
Answer
CREATE ROLE analyst NOLOGIN;
GRANT USAGE ON SCHEMA public TO analyst;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO analyst;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO analyst;
GRANT analyst TO omar;
A role has only the SELECT privilege on orders. Can it run DELETE FROM orders WHERE order_id = 101?
Answer
No: it fails with "permission denied". DELETE needs the DELETE privilege. A role with DELETE also needs SELECT on the columns its WHERE condition reads.
Write a row-level security policy so that a role store_staff sees only the customers rows whose city matches the session setting app.city.
Answer
ALTER TABLE customers ENABLE ROW LEVEL SECURITY;
CREATE POLICY same_city ON customers
FOR SELECT TO store_staff
USING (city = current_setting('app.city'));
GRANT SELECT ON customers TO store_staff;
Why shouldn't a web application connect to its database as a superuser?
Answer
A superuser bypasses every permission check and row-level security. Any bug that lets an attacker run SQL, such as SQL injection, would give them full control of every database on the server, and in PostgreSQL possibly of the host. A role limited to the data the application needs contains the damage.
Previous: Database Metadata: information_schema and the System Catalogs

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.