Create User in MySQL if It Does Not Exist

MySQL does not support create user if not exists syntax as it does with create table and create procedure. This is pretty weird, as it just boils down to checking whether single row exists in the `mysql`.`user` table.

Fortunately, there is a simple work-around for this. The MySQL’s grant statement creates the user you’re granting some rights to – which you typically do right after you’ve created the user – if the user does not exist (as long as the no_auto_create_user is not set).

Also, the grant statement allows you to provide the password for the user, making the create user statement pretty much useless.

To make sure the user exists, identified with password, and granting all rights on the database when connecting from localhost, use

grant all on `database`.* to 'user'@'localhost' identified by 'password';

3 responses to “Create User in MySQL if It Does Not Exist

  1. Pingback: Create User in MySQL if It Does Not Exist | Sin William Senjaya's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s