PostgreSQL PRIVILEGES
Whenever a database object is created, an owner is assigned to it, usually the person who executed the create statement.
For most types of objects, the initial state is that only the owner (or a superuser) can modify or delete the object. To allow other roles or users to use it, privileges must be granted to that user.
In PostgreSQL, privileges are divided into the following types:
- SELECT
- INSERT
- UPDATE
- DELETE
- TRUNCATE
- REFERENCES
- TRIGGER
- CREATE
- CONNECT
- TEMPORARY
- EXECUTE
- USAGE
Depending on the object type (table, function, etc.), apply the specified privilege to that object.
To assign privileges to a user, you can use the GRANT command.
GRANT syntax
The basic syntax of the GRANT command is as follows:
GRANT privilege [, ...]
ON object [, ...]
TO { PUBLIC | GROUP group | username }
- privilege - Value can be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL.
- object - The name of the object to grant access to. Possible objects are: table, view, sequence.
- PUBLIC - Indicates all users.
- GROUP group - Grants privileges to a user group.
- username - The name of the user to grant privileges to. PUBLIC is a shorthand representing all users.
In addition, we can use the REVOKE command to cancel privileges. REVOKE syntax:
REVOKE privilege [, ...]
ON object [, ...]
FROM { PUBLIC | GROUP groupname | username }
Example
To understand privileges, create a user:
runoobdb=# CREATE USER runoob WITH PASSWORD 'password';
CREATE ROLE
Message CREATE ROLE indicates that a user "runoob" has been created.
Example
Create the COMPANY table (Download the COMPANY SQL file ), with the following data:
runoobdb# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
Now assign privileges to the user "runoob":
runoobdb=# GRANT ALL ON COMPANY TO runoob;
GRANT
Message GRANT indicates that all privileges have been assigned to "runoob".
Now revoke the privileges of the user "runoob":
runoobdb=# REVOKE ALL ON COMPANY FROM runoob;
REVOKE
Message REVOKE indicates that the user's privileges have been revoked.
You can also delete the user:
runoobdb=# DROP USER runoob;
DROP ROLE
Message DROP ROLE indicates that the user "runoob" has been deleted from the database.