GRANT

Data Control Language

DCL (Data Control Language) decides who can do what in a database. It has two main commands: GRANT gives a permission and REVOKE takes it away.

Permissions are called privileges. Common ones are SELECT, INSERT, UPDATE, DELETE, EXECUTE (run a procedure), CREATE and ALL PRIVILEGES.

The GRANT Statement

GRANT privilege_list
ON object_name
TO user_or_role
[WITH GRANT OPTION];
  • privilege_list: one or more privileges, separated by commas.
  • object_name: the table, view, procedure or whole database/schema.
  • WITH GRANT OPTION: the receiver may pass the privilege on to others.

Examples

-- MySQL: create a user and let it read two tables
CREATE USER 'report_user'@'%' IDENTIFIED BY 'Str0ng!Passw0rd';
GRANT SELECT ON shopdb.Orders    TO 'report_user'@'%';
GRANT SELECT ON shopdb.Customers TO 'report_user'@'%';

-- PostgreSQL: let an app user read and write orders
GRANT SELECT, INSERT, UPDATE ON Orders TO app_user;

-- Only some columns (MySQL, PostgreSQL, SQL Server)
GRANT SELECT (CustomerID, CustomerName, Country) ON Customers TO intern;

-- Everything on a database (MySQL), use with care
GRANT ALL PRIVILEGES ON shopdb.* TO 'admin_user'@'localhost';

Checking Privileges

-- MySQL
SHOW GRANTS FOR 'report_user'@'%';

-- PostgreSQL (psql)
\dp Orders

-- SQL Server
SELECT * FROM fn_my_permissions('Orders', 'OBJECT');

Note: SQLite is a file-based database without users, so DCL commands do not exist there. Access is controlled by file permissions.