117

I have a query to check mysql users list for create new user.

IF (SELECT EXISTS(SELECT 1 FROM `mysql`.`user` WHERE `user` = '{{ title }}')) = 0 THEN
    CREATE USER '{{ title }}'@'localhost' IDENTIFIED BY '{{ password }}'
END IF;

But i get this error:

ERROR 1064 (42000) at line 3: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF (SELECT EXISTS(SELECT 1 FROM `mysql`.`user` WHERE `user` = 'cms_localhost')) = 0 ' at line 1
0

2 Answers 2

319

In 5.7.6 and above, you should be able to use CREATE USER

CREATE USER IF NOT EXISTS 'user'@'localhost' IDENTIFIED BY 'password';

Note that the 5.7.6 method doesn't actually grant any permissions.


If you aren't using a version which has this capability (something below 5.7.6), you can do the following:

GRANT ALL ON `database`.* TO 'user'@'localhost' IDENTIFIED BY 'password';

This will create the user if it doesn't exist


Note, if you are on MySQL 8, the GRANT ALL method will not create a user.

15
  • 4
    Does this change the password if the user did exist and had a different password?
    – m3z
    Oct 13, 2014 at 14:41
  • 5
    Nevermind - answered my own question - yes it does - but it doesn't replace the user if the Host is different
    – m3z
    Oct 13, 2014 at 14:46
  • 1
    @m3z technically, if you have user who can log in on two different hosts, they are not the same user. They can have different permissions, different passwords, and everything.
    – Ascherer
    Oct 13, 2014 at 21:32
  • 1
    Use 'user'@'%' to create this user for all hosts.
    – roundar
    Feb 7, 2015 at 20:50
  • 1
    Yes @roundar, however that leaves security holes. Be aware.
    – Ascherer
    Feb 7, 2015 at 21:55
-4

I use

SELECT EXISTS (SELECT DISTINCT user FROM mysql.user WHERE user = "username") as is_user

should return 1 if exists or 0 if it does not

1
  • 2
    the question is not about how to check, but how to create
    – VladL
    May 15, 2015 at 8:37

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.