MySQL & MariaDB error 1046: No database selected
No database selected (5.6.51) The statement uses a table name without a database, and the connection has no default database. Name one when connecting, run USE, or write db.table.
| MySQL | MariaDB | |
|---|---|---|
| Symbol | ER_NO_DB_ERROR | ER_NO_DB_ERROR |
| SQLSTATE | 3D000 | 3D000 |
| Type | Server error | Server error |
| Versions | every release since 5.0 active | every release since 5.5 active |
What it means
An unqualified name like orders is looked up in the connection’s default database. A connection opened without one (no database in the connection string, no USE) has nowhere to look, so every unqualified table reference fails with 1046.
Why it happens
mysql -u app -pwith no database argument, followed bySELECT * FROM orders.- A connection string or DSN without the database part (
mysql://app@db/instead ofmysql://app@db/shop). - Importing a dump made with
--all-databasesor--databasesworks because it containsUSEstatements. A dump of a single database made without--databasesdoesn’t, so importing it without naming a target database gives 1046. SELECT DATABASE();returnsNULLwhen this is the problem.
How to fix it
- Name the database when connecting:
mysql -u app -p shop < dump.sql. - Or start the script with
USE shop;. - Or qualify the names:
SELECT * FROM shop.orders. This also avoids surprises when a pooled connection’s default database was changed by earlier code.
Reproduce it yourself
These steps are the exact test our harness runs. Use a scratch server, never production.
Connect with
mysql -u root -pand create a scratch database:CREATE DATABASE demo; USE demo;In a shell on the database host:
mysql -uroot -p -e 'SELECT * FROM t'
You get: ERROR 1046 (3D000) at line 1: No database selected(11.8.9)
Verified fixes
Name the database on the command line (or USE it, or qualify the table)
CREATE TABLE t (a INT); INSERT INTO t VALUES (1);mysql -uroot -p -N demo -e 'SELECT a FROM t'
Tested on
| Step | MySQL | MariaDB | |||||||
|---|---|---|---|---|---|---|---|---|---|
| 5.6 | 5.7 | 8.0 | 8.4 | 9 | 10.6 | 10.11 | 11.4 | 11.8 | |
| Connect without naming a database, then use an unqualified table name repro | ✓ 1046 | ✓ 1046 | ✓ 1046 | ✓ 1046 | ✓ 1046 | ✓ 1046 | ✓ 1046 | ✓ 1046 | ✓ 1046 |
| Name the database on the command line (or USE it, or qualify the table) fix | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |