Creating and Dropping Tables in SQL

Introduction

Tables are the foundational building blocks of a relational database, organizing data into rows and columns. Learning how to create and delete tables is a critical step in database design and management. In this guide, you’ll learn how to:

Naming a Table

Proper naming conventions improve the readability and maintainability of your database. Follow these guidelines:

Examples:

Writing SQL to Create Tables

Use the following syntax to create a table:

CREATE TABLE table_name (
  column_name data_type,
  column_name data_type,
  ...
  column_name data_type
);
      

Key rules:

Example: Creating a Table

Consider the following table for storing puppy data:

Column JavaScript Data Type Max Length SQL Data Type
name string 50 VARCHAR(50)
age_yrs number 3 digits, 1 decimal NUMERIC(3,1)
breed string 100 VARCHAR(100)
weight_lbs number INTEGER
microchipped Boolean BOOLEAN

The SQL to create this table:

CREATE TABLE puppies (
  name VARCHAR(50),
  age_yrs NUMERIC(3,1),
  breed VARCHAR(100),
  weight_lbs INTEGER,
  microchipped BOOLEAN
);
      

Adding a Primary Key

Every table should include a primary key, which uniquely identifies each row. It’s common to use an id column with the INTEGER PRIMARY KEY constraint. For example:

CREATE TABLE puppies (
  id INTEGER PRIMARY KEY,
  name VARCHAR(50),
  age_yrs NUMERIC(3,1),
  breed VARCHAR(100),
  weight_lbs INTEGER,
  microchipped BOOLEAN
);
      

Using NOT NULL Constraints

To ensure that a column cannot be left empty, use the NOT NULL constraint. For example:

CREATE TABLE puppies (
  id INTEGER PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  age_yrs NUMERIC(3,1),
  breed VARCHAR(100),
  weight_lbs INTEGER,
  microchipped BOOLEAN
);
      

This ensures that every puppy entry must have a name.

Dropping a Table

To delete a table and all its data, use the DROP TABLE statement:

DROP TABLE table_name;
      

Example:

DROP TABLE puppies;
      

Warning: Dropping a table is irreversible and will delete all data stored in it. Use this command cautiously, especially in production environments.

What You Learned

Mastering table creation and management is an essential skill for designing robust and efficient relational databases. Always plan your schema carefully before executing changes.