creacion-eliminacion-bases-datos

Creation and Deletion of Databases in SQL Server

  • 5 min

Every journey begins somewhere, and in SQL Server, our data universe begins by creating a Database.

Before we can create tables, procedures, or save a single byte of information, we need to define the database (that is, the container where everything will live).

Although SQL Server Management Studio (SSMS) allows us to do this with a “right-click”, we also need to know how to do it via code T-SQL.

Doing it with code allows us to automate deployments, copy to another server, backups, have total control over the physical configuration…

And honestly, you will have to do it sooner or later.

Basic Database Creation

The most common way to create a database is to use the CREATE DATABASE statement followed by the name we want to give it.

CREATE DATABASE MiEmpresa;
GO
Copied!

When we execute this command, SQL Server does the following:

  1. Copies the system database called model (which acts as a template).
  2. Creates the physical files in the server’s default location.
  3. Assigns the default sizes.

Remember that to execute database creation commands, you generally must be in the system database master.

Selecting the Database with USE

A very common mistake is to create the database and then immediately start creating tables… without having entered it!. And basically messing everything up.

If you don’t change the context, you are creating your tables inside the master database (the one created by default when installing SQL).

To avoid this, we always use the USE command:

USE GestionPedidos;
GO
-- Now everything we execute here will happen inside 'GestionPedidos'
Copied!

Deleting Databases

To delete a database, we use the DROP DATABASE statement. The basic syntax is:

DROP DATABASE GestionPedidos;
GO
Copied!

Be careful! This operation is destructive and irreversible (unless you have backups).

DROP DATABASE deletes the database, its tables, its users and physically deletes the .mdf and .ldf files from the hard drive.