← Back to SQL, page 22

sql-0439 · Medium mid

Analysts need access to order data but must not see customers' personal details. How can the database enforce that?

Give analysts a role without access to the base tables and grant SELECT on views that omit or mask personal columns (for example a hashed customer id and only the country). PostgreSQL also supports column-level privileges and row-level security. Separate analytics copies with masked data are a further option.

Full answer

Approaches:

  • Views: CREATE VIEW analytics.orders AS SELECT o.id, md5(o.customer_id::text || :salt) AS customer_key, c.country, o.total FROM orders o JOIN customers c ... and grant SELECT on the view only.
  • Column privileges: GRANT SELECT (id, country, created_at) ON customers TO analyst; blocks other columns.
  • Row-level security: restrict rows, for example to the analyst's region.
  • Masked copies: a nightly job copies data into an analytics database with personal fields removed or tokenised, so mistakes in the primary's grants cannot leak data.

Hashing ids keeps joins possible across tables without revealing identities, but small groups can still identify people; aggregate thresholds (no groups under 10 people) reduce that risk. Audit which roles can read raw personal data and review it regularly. The statements shown are illustrative and were not run here.

Key points

  • Grant views, not base tables
  • Column privileges restrict fields
  • Row-level security restricts rows
  • Masked analytics copies isolate risk
  • Small groups can still identify people

Common mistakes

  • Granting SELECT on all tables to analysts
  • Assuming hashing alone guarantees anonymity

Follow-ups

  • How would you mask email addresses but keep domains?
  • How does pseudonymisation differ from anonymisation?

Tips

  • Name views and privileges together