MySQL: How to Select Database via Terminal/Command Line


If you have connected to a MySQL database using the Command Line on Windows or Terminal on macOS/Linux and want to run queries against a particular schema/database, you can make use of the "USE" statement.


The syntax for the USE statement in MySQL is as follows:

USE db_name

Using the USE statement, you can switch to a particular database before running queries against it.


For example, to switch to the "myDb" database, you can use the following command:
    mysql> USE myDb;
    
    Database changed

    If you do not provide the correct database name, or the database does not exist you will get ERROR 1049 (42000),

    mysql> USE prodDb;
    
    ERROR 1049 (42000): Unknown database 'prodDb'

    The database name cannot be provided on a new line, if you just make use of the USE statement, you will get an error.

    mysql> USE
    ERROR: USE must be followed by a database name

    If you do not want to switch to a particular database, you can also prefix the table name in your query with the database name.

    For example:
    Select * from myDb.employee where name='Sam';

MySql switch current database

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap