Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - CREATE USER IF NOT EXISTS

Tags:

mysql

CREATE USER IF NOT EXISTS ...

A new user is created without a problem. An existing user returns that error, but the docs read that CREATE USER for MySQL > 5.7.6 supports it.

MySQL Version is

Ver 14.14 Distrib 5.7.11, for osx10.9 (x86_64) using  EditLine wrapper

Sample

<root:none> CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar';
--------------
CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar'
--------------

Query OK, 0 rows affected (0.00 sec)

<root:none> CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar';
--------------
CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar'
--------------

ERROR 1396 (HY000): Operation CREATE USER failed for 'foo'@'localhost'

Suggestions?

like image 932
Vishal Avatar asked Feb 14 '16 14:02

Vishal


1 Answers

CREATE USER IF NOT EXISTS throws an error if you use the IDENTIFIED BY clause and the user does exist. It does not throw an error and works as expected if you do not use the IDENTIFIED BY clause.

mysql> CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar';
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE USER IF NOT EXISTS 'foo'@'localhost' IDENTIFIED BY 'bar';
ERROR 1396 (HY000): Operation CREATE USER failed for 'foo'@'localhost'

mysql> CREATE USER IF NOT EXISTS 'foo'@'localhost';
Query OK, 0 rows affected, 1 warning (0.00 sec)

From 5.7.8, instead of using CREATE USER IF NOT EXISTS, you can use DROP USER IF EXISTS before calling CREATE USER with the IDENTIFIED BY clause.

mysql> DROP USER 'foo'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> DROP USER 'foo'@'localhost';
ERROR 1396 (HY000): Operation DROP USER failed for 'foo'@'localhost'

mysql> DROP USER IF EXISTS 'foo'@'localhost';
Query OK, 0 rows affected, 1 warning (0.00 sec)

The other option is to create the user first and then set the password after the user is created.

mysql> CREATE USER IF NOT EXISTS 'foo'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE USER IF NOT EXISTS 'foo'@'localhost';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> SET PASSWORD FOR 'foo'@'localhost' = 'bar';
Query OK, 0 rows affected (0.01 sec)
like image 60
Zubair Suri Avatar answered Sep 21 '22 02:09

Zubair Suri