Introduction
In this chapter, we will learn how to create a database in SQL. Creating a database is the first step in organizing and storing your data. This chapter will guide you through the process of creating a new database, including the syntax and examples.
Creating a Database
To create a new database, you use the CREATE DATABASE
statement. This statement creates a new database with the specified name.
Syntax
CREATE DATABASE database_name;
database_name
: The name of the database you want to create. This name should be unique within the database server.
Example
CREATE DATABASE mydatabase;
This example creates a new database named mydatabase
.
Using the New Database
After creating a database, you need to select it for use. This is done with the USE
statement.
Syntax
USE database_name;
Example
USE mydatabase;
This example selects the mydatabase
database for use.
Full Example
Let's go through a full example where we create a database and then use it to create a table.
Step-by-Step
- Create the Database:
CREATE DATABASE company;
- Use the Database:
USE company;
- Create a Table:
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100)
);
Full Example Script
CREATE DATABASE company;
USE company;
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100)
);
Checking the Database
You can check if the database has been created and list all databases on the server using the SHOW DATABASES
statement.
Example
SHOW DATABASES;
This statement will list all databases available on the server, including the newly created company
database.
Deleting a Database
If you need to delete a database, you can use the DROP DATABASE
statement. Be cautious when using this command, as it will permanently delete the database and all its data.
Syntax
DROP DATABASE database_name;
Example
DROP DATABASE company;
This example deletes the company
database.
In this next chapter, you will learn more about DROP DATABASE
statement.
Conclusion
Creating a database is the foundational step in managing your data with SQL. This chapter covered how to create, use, and delete databases. By understanding these basic operations, you can start organizing your data effectively.
Comments
Post a Comment
Leave Comment