What would be nice would be a "create user if not exists" much like
you can do a "create table if not exists". Unfortunately MySQL doesn't
let you do this.

There are a few ways round this.

One is to create a stored procedure which can query to determine
whether the user exists and create the account if not.

Another is to drop the user and recreate. This might be viable in
some scenarios, but I do not like this approach.

The approach I prefer is to use grant - because grant will create the
user if the account does not already exist. So:

grant select on myDB.* to brian@localhost identified by 'his_password';

will create the account "brian@localhost" if that account does not already exist and grant
select to that account for all tables in the "myDB" database.

If you are writing scripts then using the grant approach is the most
elegant.

One gotcha to be aware of: If "NO_AUTO_CREATE_USER" is set then grant
will not create new users.

These notes have been tested against MySQL 5, and may apply to other versions as well.

About the author: Brian Cryer
is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.