GRANT
GRANT is an SQL command that gives database access permissions to users or roles. The type of permissions can range from the ability to SELECT data from a table, to the ability to UPDATE or DELETE records. Additionally, GRANT can give the power to CREATE, ALTER, or DROP tables and other database structures. Thus, GRANT serves as a crucial command in database security and administration.
Example
GRANT SELECT, UPDATE ON database_name.table_name TO 'username'@'localhost';
Output
Query OK, 0 rows affected (0.00 sec)
Explanation
The GRANT statement assigns SELECT and UPDATE privileges on the specified table in the stated database to the mentioned user. If the statement is executed successfully, MySQL will return a message indicating that the query has been executed correctly.
Example
CREATE ROLE new_user;GRANT SELECT ON table_name TO new_user;
Output
The output would not provide any visible results, but upon listing privileges for new_user
, you can see the SELECT privilege that has been granted.
\du new_user
This would display the following:
List of roles Role name | Attributes | Member of-----------+---------------+----------- new_user | | {}
And on more detailed check for the privileges:
\dp table_name
Output can be something like:
Schema | Name | Type | Access privileges | Column privileges | Policies-----------+----------+-------+-------------------+-------------------+---------- public | table_name | table | new_user=r | |
Explanation
In the given SQL commands, a role new_user
is created and then the SELECT privilege is granted on table_name
to this user. This allows the new_user
to run SELECT queries on table_name
. The output section does not display any specific outputs, as the GRANT command does not produce a visible output. However, the privileges for the new_user
after the execution of the GRANT command can be verified using the \du
and \dp
commands.
Example
CREATE LOGIN CreateUser WITH PASSWORD = 'Password123';CREATE USER CreateUser FOR LOGIN CreateUser;GRANT SELECT ON YourTable TO CreateUser;
Output
The command(s) completed successfully.
Explanation
In the example above, a new SQL Server login and user, both named ‘CreateUser’, are first created. Afterward, the permission to perform the SELECT operation on ‘YourTable’ is granted to the ‘CreateUser’. This enables ‘CreateUser’ to retrieve data from ‘YourTable’.
Example
GRANT SELECT, UPDATEON employeeTO user1;
Output
Query OK, 0 rows affected
Explanation
This SQL command grants the permissions ‘SELECT’ and ‘UPDATE’ on the table ‘employee’ to ‘user1’. The output shows that the query executed successfully.
Example
GRANT ALL PRIVILEGES ON database_name.table_name TO 'username'@'localhost';
Output
This action does not return an output in SQLite, as it just modifies privileges.
Explanation
The code grants all privileges on a specific table table_name
in a specific database database_name
to a user username
. User username
can access the database from the localhost
.