This section describes how to grant users the SELECT, INSERT, UPDATE, or full permissions for tables.
1 2 3 4 5 6 | GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | TRIGGER | ANALYZE | ANALYSE } [, ...] | ALL [ PRIVILEGES ] } ON { [ TABLE ] table_name [, ...] | ALL TABLES IN SCHEMA schema_name [, ...] } TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; |
Assume there are users u1, u2, u3, u4, and u5 and five schemas named after these users. Their permission requirements are as follows:
User |
Type |
GRANT Statement |
Query |
Insert |
Update |
Delete |
||
---|---|---|---|---|---|---|---|---|
u1 |
Owner |
- |
√ |
√ |
√ |
√ |
||
u2 |
Read-only user |
|
√ |
x |
x |
x |
||
u3 |
INSERT user |
|
x |
√ |
x |
x |
||
u4 |
UPDATE user |
NOTICE:
The UPDATE permission must be granted together with the SELECT permission, or information leakage may occur. |
√ |
x |
√ |
x |
||
u5 |
Super user |
|
√ |
√ |
√ |
√ |
Perform the following steps to grant and verify permissions:
1 2 3 4 5 | CREATE USER u1 PASSWORD '{password}'; CREATE USER u2 PASSWORD '{password}'; CREATE USER u3 PASSWORD '{password}'; CREATE USER u4 PASSWORD '{password}'; CREATE USER u5 PASSWORD '{password}'; |
1 | CREATE TABLE u1.t1 (c1 int, c2 int); |
1 2 | INSERT INTO u1.t1 VALUES (1,2); INSERT INTO u1.t1 VALUES (1,2); |
1 | GRANT USAGE ON SCHEMA u1 TO u2,u3,u4,u5; |
1 | GRANT SELECT ON u1.t1 TO u2; |
1 2 3 | SELECT * FROM u1.t1; INSERT INTO u1.t1 VALUES (1,20); UPDATE u1.t1 SET c2 = 3 WHERE c1 =1; |
1 2 3 | GRANT INSERT ON u1.t1 TO u3; -- Allow u3 to insert data. GRANT SELECT,UPDATE ON u1.t1 TO u4; -- Allow u4 to modify the table. GRANT ALL PRIVILEGES ON u1.t1 TO u5; -- Allow u5 to query, insert, modify, and delete table data. |
1 2 3 | SELECT * FROM u1.t1; INSERT INTO u1.t1 VALUES (1,20); UPDATE u1.t1 SET c2 = 3 WHERE c1 =1; |
1 2 3 | SELECT * FROM u1.t1; INSERT INTO u1.t1 VALUES (1,20); UPDATE u1.t1 SET c2 = 3 WHERE c1 =1; |
1 2 3 4 | SELECT * FROM u1.t1; INSERT INTO u1.t1 VALUES (1,20); UPDATE u1.t1 SET c2 = 3 WHERE c1 =1; DELETE FROM u1.t1; |
1 | SELECT * FROM pg_class WHERE relname = 't1'; |
Check the relacl column in the command output. rolename=xxxx/yyyy indicates that rolename has the xxxx permission on the table and the permission is obtained from yyyy.
The following figure shows the command output.