w3resource

Assigning a Role to a User in PostgreSQL


Assign a User to a Role

Write a PostgreSQL query to grant the role data_admin to the user alen_king.

Solution:

-- Assign a user to a role
GRANT data_admin TO alen_king;

Explanation:

  • Purpose of the Query:
    • Assigns alen_king to the data_admin role.
  • Key Components:
    • GRANT data_admin: Gives role permissions.
    • TO alen_king: Applies to the specific user.
  • Real-World Application:
    • Used in role-based access control (RBAC).

Notes:

  • Use SET ROLE data_admin; for alen_king to activate role permissions.

For more Practice: Solve these Related Problems:

  • Write a PostgreSQL query to assign the role reporting_team to the user jane_doe if they are not part of it already.
  • Write a PostgreSQL query to grant the role analytics_specialist to a user only if they meet the required department criteria.
  • Write a PostgreSQL query to assign multiple roles (editor and moderator) to the user content_manager with a single statement.
  • Write a PostgreSQL query to grant a role to a user and immediately revoke a different conflicting role within a transaction.


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous PostgreSQL Exercise: Change a User’s Password.

Next PostgreSQL Exercise: List All Users and Roles.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.