A MySQL add user and grant example

MySQL “users” FAQ: How do I add a new user to a MySQL or MariaDB database (i.e., how do I create a MySQL user account, and then grant database permissions to that new user account)?

Back to top

Solution: MySQL add user and grant syntax

The following MySQL commands show an example of what I did recently to (a) create a new MySQL database and then (b) add a new MySQL user account to work with that database. I have verified this approach with both MAMP and using MySQL on Linux servers.

Back to top

Step 1: Log into the database

First, from your command-line prompt, log into my MySQL database server with the mysql command line client:

unix> mysql -u root -p
(here I enter 'my_root_password' to get through the mysql prompt)
Back to top

Step 2: Create the database (if needed)

Next, create a new database with the MySQL create database command, specifying the name of the database (my_database) after that command:

mysql> create database my_database;
Back to top

Step 3: Create the new MySQL user account

Then create a new MySQL user account, giving the user account all the privileges it needs to “own” this database with the MySQL grant command. Note that I assign both the username and password when I add the new user account:

mysql> GRANT ALL PRIVILEGES 
       ON my_database.* 
       TO 'my_user'@'localhost'
       IDENTIFIED BY 'my_password' 
       WITH GRANT OPTION;

If you want something you can copy and paste, this grant command example is a little easier to work with:

GRANT ALL PRIVILEGES 
ON my_database.* 
TO 'my_user'@'localhost'
IDENTIFIED BY 'my_password' 
WITH GRANT OPTION;

You can put that entire MySQL grant command on one line; I just put it on multiple lines here so it would be easier to read. (It seems a little unusual, but using grant is how you create a MySQL user account.)

Update: Please see the Comments section below for an additional “add user” example that uses the grant command.

Back to top

Note about this MySQL user account and “localhost”

It's important to note when I create this MySQL user, I'm giving the user access to this MySQL database from the computer system known as "localhost". This works fine when you're accessing this database with this new MySQL user account from the local computer system, but if you're going to access this database from another computer system, you'll need to specify the IP address of that remote system here instead of "localhost".

Back to top

More information

For more information on how to add/create a MySQL user, and also how to remove a MySQL user, see the following URLs on the MySQL website:

Back to top