Chapter 5. Controlling Access to your data

Table of Contents
Restricting users to certain records or certain fields with views
Preventing users from updating data with views
Letting users update views
Grant privileges on all tables in one go

Restricting users to certain records or certain fields with views

The accounts team don't need to see unfilled orders and the sales team don't need to see bank details. You want to enforce this.

Solution

Create one view for each group of users, and deny them access to the underlying table(s) ref-view ref-deny.

Discussion

You can create alternative views of your database with CREATE VIEW <viewname> AS SELECT.... To a user this appears to be a table, but you can control what underlying data shows through. The SELECT query can be anything you like - it can involve JOINs, UNIONs or GROUP BY if you want. So, if the accounts department only needs to see completed orders:

CREATE VIEW accts_orders AS SELECT * FROM orders WHERE ord_delivered IS NOT NULL;
   

You then need to make sure that accounts has access to this view and not to the underlying table:

GRANT ALL ON accts_orders TO accounts;
REVOKE ALL ON orders FROM accounts;
   

You will need to be a superuser (postgres) or the owner of the database objects to do this. Possible permissions are: SELECT, INSERT, UPDATE, DELETE, RULE, ALL.