How do you use the CREATE USER statement to create a new database user?
Posted by CarolTh
Last Updated: July 06, 2024
The CREATE USER statement in SQL is used to create a new database user account. The specific syntax for this command can vary depending on the database system you are using (e.g., MySQL, PostgreSQL, Oracle, SQL Server). Below are examples for creating a new user in MySQL and PostgreSQL:
MySQL Example
In MySQL, you can create a new user with the following syntax:
CREATE USER 'username'@'host' IDENTIFIED BY 'password';
- username: The desired username for the new user. - host: The host from which the user can connect (e.g., 'localhost', '%' for any host). - password: The password for the new user. Example of Creating a User:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'userpassword';
Granting Privileges
After creating a user, you often need to grant specific permissions:
GRANT ALL PRIVILEGES ON database_name.* TO 'newuser'@'localhost';
PostgreSQL Example
In PostgreSQL, the syntax is slightly different:
CREATE USER username WITH PASSWORD 'password';
Example of Creating a User:
CREATE USER newuser WITH PASSWORD 'userpassword';
Granting Privileges
Similar to MySQL, you need to grant the user access rights:
GRANT ALL PRIVILEGES ON DATABASE database_name TO newuser;
Notes:
- Make sure you have the necessary administrative privileges to create a user. - Choose a strong, secure password for the user account. - After creating the user, you may wish to limit or specify the permissions according to the principle of least privilege. - Always refer to the official documentation for the specific SQL database you are using for the most accurate and detailed options available.