SQL
The CREATE DATABASE
statement is used to create a new database. A database is a structured collection of data that is organized and stored for easy retrieval and management.
The basic syntax for creating a database is as follows:
CREATE DATABASE database_name;
CREATE DATABASE
: The SQL command to create a new database.database_name
: The name you want to give to your new database. Make sure to choose a meaningful and descriptive name.Let’s start by creating a simple database. For the purpose of this tutorial, we’ll work with a basic structure:
Database Name: StudentDB
CREATE DATABASE StudentDB;
Output:
Query OK, 1 row affected
In SQL, we can use the SHOW DATABASES
command or the SHOW SCHEMAS
command, depending on the specific database management system (DBMS).
SHOW DATABASES;
This command will display a list of all the databases on the MySQL or MariaDB server.
\l
This command shows a list of all databases in PostgreSQL.
SELECT name FROM sys.databases;
This SQL query retrieves the names of all databases in Microsoft SQL Server.
ATTACH DATABASE 'path/to/database/file' AS dbname;
This command in SQLite allows you to attach a database file, and you can see the attached databases using the following:
PRAGMA database_list;
Dropping a database means permanently deleting it from the database management system (DBMS). We have to be extremely careful when using the DROP DATABASE
command, as it irreversibly removes all data and objects associated with the specified database.
DROP DATABASE [IF EXISTS] database_name;
IF EXISTS
: Optional clause to avoid an error if the database does not exist.database_name
: The name of the database you want to drop.Example:
DROP DATABASE IF EXISTS SchoolDB;
DROP DATABASE [IF EXISTS] database_name;
Example:
DROP DATABASE IF EXISTS SchoolDB;
USE master;
DROP DATABASE [IF EXISTS] database_name;
Example:
USE master;
DROP DATABASE IF EXISTS SchoolDB;
SQLite does not have a direct DROP DATABASE
command. Instead, you can delete the database file from the file system.
-- In SQLite, you can also use the following pragma to detach a database:
ATTACH DATABASE 'path/to/database/file' AS dbname;
-- Then, you can drop tables or manipulate the database as needed.
-- After that, you can detach the database:
DETACH DATABASE dbname;