Fix 'No database selected' error in MySQL

June 30, 2022  ‐ 1 min read

When trying to run an SQL query in MySQL you may receive a 'No database selected' error message.

mysql> SELECT * FROM posts;
ERROR 1046 (3D000): No database selected

What this error means is that you tried to run a query but didn't specify on which database. Since MySQL servers can contain multiple databases.

A first way of getting around this error is by prefixing the table name by the database name. Thus, if my database is called blog and the table I wish to query posts I would be able to run the following query.

mysql> SELECT * FROM blog.posts;

If we plan to run multiple queries then it is probably more convenient to specify which database to use, using the USE statement. When we do so there is no need anymore to prefix each table name with the database name.

mysql> USE blog;
Database changed
mysql> SELECT * FROM posts;

If you are blanking on the database name in your MySQL server you can list the databases using the SHOW statement.

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| blog               |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0,00 sec)