Home » Mysql » Using % for host when creating a MySQL user

Using % for host when creating a MySQL user

Posted by: admin November 1, 2017 Leave a comment

Questions:

My MySQL database needs two users: appuser and support.
One of the application developers insists that I create four accounts for these users:

[email protected]'%'
[email protected]'localhost'
[email protected]'%'
[email protected]'localhost'

For the life of me I can’t figure out why he thinks we need this. Wouldn’t using the wildcard as the host take care of the ‘localhost’?

Any ideas?

(Using MySQL 5.5 here)

Answers:

The percent sign means all ip’s so localhost is superfluous … There is no need of the second record with the localhost .

EDIT

Actually there is, ‘localhost’ is special in mysql, it means a connection over a unix socket (or named pipes on windows I believe) as opposed to a TCP/IP socket. using % as the host does not include ‘localhost’

Questions:
Answers:

As @nos pointed out in the comments of the currently accepted answer to this question, the accepted answer is incorrect.

Yes, there IS a difference between using % and localhost for the user account host when connecting via a socket connect instead of a standard TCP/IP connect.

A host value of % does not include localhost for sockets and thus must be specified if you want to connect using that method.

Questions:
Answers:

If you want connect to [email protected]'%' from localhost use mysql -h192.168.0.1 -uuser -p.

Questions:
Answers:

Going to provide a slightly different answer to those provided so far.

If you have a row for an anonymous user from localhost in your users table ''@'localhost' then this will be treated as more specific than your user with wildcard’d host 'user'@'%'. This is why it is necessary to also provide 'user'@'localhost'.

You can see this explained in more detail at the bottom of this page.

Questions:
Answers:

The percent symbol means: any host, including remote and local connections.

The localhost allows only local connections.

(so to start off, if you don’t need remote connections to your database, you can get rid of the [email protected]’%’ user right away)

So, yes, they are overlapping, but…

…there is a reason for setting both types of accounts, this is explained in the mysql docs:
http://dev.mysql.com/doc/refman/5.7/en/adding-users.html.

If you have an have an anonymous user on your localhost, which you can spot with:

select Host from mysql.user where User='' and Host='localhost';

and if you just create the user [email protected]’%’ (and you not the [email protected]’localhost’), then when the appuser mysql user
connects from the local host, the anonymous user account is used (it has precedence over your [email protected]’%’ user).

And the fix for this is (as one can guess) to create the [email protected]’localhost’ (which is more specific that the local host anonymous user and will be used if your appuser connects from the localhost).