Users are both added and removed from groups in PostgreSQL through the ALTER GROUP
SQL command. Here is the syntax for the ALTER GROUP command:
ALTER GROUP
groupname
{ ADD | DROP } USER
username
[, ... ]
The
groupname
is the name of the group to be modified, while the
username
is
the name of the user to be added or removed, depending on whether the ADD
or DROP keyword is specified.
Suppose that Booktown hires two new sales associates, David and Ben, and gives them usernames david and ben, respectively.
Example 10-14 uses the ALTER GROUP command adds these new users to
the sales group.
Example 10-14. Adding a user to a group
booktown=#
ALTER GROUP sales ADD USER david, ben;
ALTER GROUP
The ALTER GROUP server message returned in Example 10-14
indicates that the users david and ben were successfully
added to the sales group. Example 10-15 demonstrates another
query to the pg_ group table to verify the addition of those new users to the group. Note
that there are now four system IDs in the
grolist column for the sales group.
Example 10-15. Verifying user addition
booktown=#
SELECT * FROM pg_group WHERE groname = 'sales';
groname | grosysid | grolist
---------+----------+-----------------------
sales | 1 | {7019,7018,7017,7016}
(1 row)
Suppose that some time later David is transferred from sales to accounting. In order to maintain the correct group
association, and to make sure that David does not have any rights granted exclusively to the
sales group, his user (david) should be removed from
that group; Example 10-16 achieves this.
Example 10-16. Removing a user from a group
booktown=#
ALTER GROUP sales DROP USER david;
ALTER GROUP
The ALTER GROUP message returned from Example 10-16
indicates that the david user was successfully removed from the
sales group.
To complete his transition to the accounting department, David must then have his user added to the
accounting group. The following statements use similar syntax as the statements in
Example 10-14 and Example 10-15. The net effect is that the
david user is added into the accounting group. This means
that any special rights granted to this group will be implicitly granted to david for as long as he
is a member of the group.
booktown=#
ALTER GROUP accounting ADD USER david;
ALTER GROUP
booktown=#
SELECT * FROM pg_group;
groname | grosysid | grolist
------------+----------+------------------
sales | 1 | {7016,7017,7019}
accounting | 2 | {7018}
(2 rows)