MySQL SELECT Database

Introduction

In this chapter, we will learn how to select a database in MySQL. Selecting a database allows you to perform operations on that database, such as creating tables, inserting data, and running queries. Let's explore how to select a database and work with it.

Selecting a Database

To select a database, we use the USE statement. This command tells MySQL to switch to the specified database so that any subsequent operations are performed on it.

Syntax

USE database_name;
  • database_name: The name of the database you want to select.

Example

USE mydatabase;

This example selects the database named mydatabase for use.

Full Example

Let's go through a full example where we create a database, select it, and then create a table within it.

  1. Create a Database:
CREATE DATABASE company;
  1. Select the Database:
USE company;
  1. Create a Table:
CREATE TABLE employees (
    id INT PRIMARY KEY AUTO_INCREMENT,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(100)
);
  1. Insert Data into the Table:
INSERT INTO employees (first_name, last_name, email) VALUES ('Rahul', 'Sharma', 'rahul.sharma@example.com');
INSERT INTO employees (first_name, last_name, email) VALUES ('Priya', 'Singh', 'priya.singh@example.com');
  1. Select Data from the Table:
SELECT * FROM employees;

Output

id first_name last_name email
1 Rahul Sharma rahul.sharma@example.com
2 Priya Singh priya.singh@example.com

Checking the Current Database

To check which database is currently selected, you can use the following command:

SELECT DATABASE();

Example

SELECT DATABASE();

Output

DATABASE()
company

Conclusion

Selecting a database in MySQL is a simple but crucial step in managing your data. Once a database is selected, you can perform various operations on it, such as creating tables and inserting data. This chapter covered how to select a database and provided a full example of creating and using a database.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare