SQL Tutorial › Getting Started › Create Database & Table

Create Database and Create Table in SQL

BeginnerLesson 4 of 6912 min read11 queries run on MySQL 8.4

Before you can store data you need a database to hold your tables and a table with the right columns. This lesson creates a school database and a students table from scratch, inspects the result, and shows the shortcuts every developer uses: IF NOT EXISTS and CREATE TABLE ... AS SELECT.

Advertisement
In this lesson
  • Create and select a database with CREATE DATABASE and USE
  • Define a table with columns, data types and a primary key
  • Inspect a table with DESCRIBE and SHOW TABLES
  • Copy query results into a new table with CREATE TABLE AS SELECT

CREATE DATABASE

A database (MySQL also calls it a schema) is a named container for tables. Create one and check that it exists:

MySQL
CREATE DATABASE school;SHOW DATABASES;
ResultMySQL 8.4
mysql> CREATE DATABASE school
Query OK, 1 row affected
mysql> SHOW DATABASES
Database
information_schema
mysql
performance_schema
school
sys
5 rows in set
How this query works, step by step
  1. CREATE DATABASE school creates an empty database called school.
  2. MySQL answers Query OK, 1 row affected: it reports one database created.
  3. SHOW DATABASES lists it next to the four system databases that every server has.

Running it twice fails, because the name is taken:

MySQL
CREATE DATABASE school;CREATE DATABASE school;
ResultMySQL 8.4
mysql> CREATE DATABASE school
Query OK, 1 row affected
mysql> CREATE DATABASE school
ERROR 1007 (HY000): Can't create database 'school'; database exists

Add IF NOT EXISTS to make the statement safe to re-run. MySQL then skips it with a warning instead of an error:

MySQL
CREATE DATABASE school;CREATE DATABASE IF NOT EXISTS school;
ResultMySQL 8.4
mysql> CREATE DATABASE school
Query OK, 1 row affected
mysql> CREATE DATABASE IF NOT EXISTS school
Query OK, 1 row affected, 1 warning
Tip

Set the character set when you create a database that stores names or text in several languages: CREATE DATABASE school CHARACTER SET utf8mb4; In MySQL 8.4 utf8mb4 is already the default.

USE: select the database

Tables always live inside a database. USE makes one the current database, so you can write students instead of school.students:

MySQL
CREATE DATABASE school;USE school;SELECT DATABASE() AS current_db;
ResultMySQL 8.4
mysql> CREATE DATABASE school
Query OK, 1 row affected
mysql> USE school
Query OK, 0 rows affected
mysql> SELECT DATABASE() AS current_db
current_db
school
1 row in set
How this query works, step by step
  1. USE school switches the session to the school database.
  2. DATABASE() returns the name of the current database, so the result is school.

CREATE TABLE syntax

MySQL
CREATE TABLE table_name (  column1 datatype [constraints],  column2 datatype [constraints],  ...  [table constraints]);

Each column needs a name and a data type (see SQL Data Types). Constraints such as NOT NULL and PRIMARY KEY add rules the data must follow.

Create a table

MySQL
CREATE DATABASE school;USE school;CREATE TABLE students (  student_id INT PRIMARY KEY,  full_name  VARCHAR(60) NOT NULL,  email      VARCHAR(100) UNIQUE,  birth_date DATE,  grade      INT DEFAULT 1);DESCRIBE students;
ResultMySQL 8.4
mysql> CREATE DATABASE school
Query OK, 1 row affected
mysql> USE school
Query OK, 0 rows affected
mysql> CREATE TABLE students (
Query OK, 0 rows affected
mysql> DESCRIBE students
FieldTypeNullKeyDefaultExtra
student_idintNOPRINULL
full_namevarchar(60)NONULL
emailvarchar(100)YESUNINULL
birth_datedateYESNULL
gradeintYES1
5 rows in set
How this query works, step by step
  1. CREATE TABLE students (...) creates the table with five columns.
  2. student_id INT PRIMARY KEY: a whole number that must be unique and not empty. It identifies each student.
  3. full_name VARCHAR(60) NOT NULL: text up to 60 characters that must always be filled.
  4. email VARCHAR(100) UNIQUE: two students cannot share an email.
  5. birth_date DATE stores a calendar date, and grade INT DEFAULT 1 gets the value 1 when an insert leaves it out.
  6. DESCRIBE students shows each column’s type, whether it accepts NULL (Null), its key (PRI = primary key, UNI = unique) and its default.

Insert rows and read them back

A new table is empty. Add three rows with INSERT and read them:

SQL
CREATE TABLE students (  student_id INT PRIMARY KEY,  full_name  VARCHAR(60) NOT NULL,  grade      INT DEFAULT 1);INSERT INTO students (student_id, full_name, grade) VALUES  (1, 'Aarav Patel', 3),  (2, 'Diya Menon', 2);INSERT INTO students (student_id, full_name) VALUES (3, 'Kabir Ali');SELECT * FROM students;
ResultMySQL 8.4
mysql> CREATE TABLE students (
Query OK, 0 rows affected
mysql> INSERT INTO students (student_id, full_name, grade) VALUES
Query OK, 2 rows affected
mysql> INSERT INTO students (student_id, full_name) VALUES (3, 'Kabir Ali')
Query OK, 1 row affected
mysql> SELECT * FROM students
student_idfull_namegrade
1Aarav Patel3
2Diya Menon2
3Kabir Ali1
3 rows in set
How this query works, step by step
  1. CREATE TABLE makes an empty students table.
  2. The first INSERT adds two rows in one statement: 2 rows affected.
  3. The second INSERT leaves out grade, so Kabir gets the default value 1.
  4. SELECT * shows all three rows.

CREATE TABLE IF NOT EXISTS

Creating a table that already exists is an error:

MySQL
CREATE TABLE departments (dept_id INT);
ResultMySQL 8.4
ERROR 1050 (42S01): Table 'departments' already exists

Setup scripts use IF NOT EXISTS so they can run again safely. The existing table is left untouched, and MySQL raises a note you can read with SHOW WARNINGS:

MySQL
CREATE TABLE IF NOT EXISTS departments (dept_id INT);SHOW WARNINGS;
ResultMySQL 8.4
mysql> CREATE TABLE IF NOT EXISTS departments (dept_id INT)
Query OK, 0 rows affected, 1 warning
mysql> SHOW WARNINGS
LevelCodeMessage
Note1050Table 'departments' already exists
1 row in set

SHOW TABLES and DESCRIBE

MySQL
SHOW TABLES;
ResultMySQL 8.4
Tables_in_company
customers
departments
employees
order_items
orders
products
6 rows in set
MySQL
DESCRIBE products;
ResultMySQL 8.4
FieldTypeNullKeyDefaultExtra
product_idintNOPRINULL
product_namevarchar(50)NONULL
categoryvarchar(30)YESNULL
priceintYESNULL
stockintYESNULL
5 rows in set
How this query works, step by step
  1. SHOW TABLES lists every table in the current database (company).
  2. DESCRIBE products (or DESC products) shows the columns of one table. product_id is the primary key, and product_name does not allow NULL.

CREATE TABLE AS SELECT

CREATE TABLE ... AS SELECT creates a new table and fills it with the result of a query. It is a quick way to save a report or make a backup copy before you change data:

MySQL
CREATE TABLE high_earners ASSELECT emp_id, first_name, salaryFROM employeesWHERE salary >= 100000; SELECT * FROM high_earners;
ResultMySQL 8.4
mysql> CREATE TABLE high_earners AS
Query OK, 3 rows affected
mysql> SELECT * FROM high_earners
emp_idfirst_namesalary
100Meera250000
101Asha125000
105Vikram105000
3 rows in set
How this query works, step by step
  1. The SELECT finds employees earning 100,000 or more: three rows.
  2. CREATE TABLE high_earners AS creates a table with the same three columns and copies those rows in.
  3. The new table is independent: later changes to employees do not change it.
Watch out

CREATE TABLE ... AS SELECT copies columns and data, but not the primary key, indexes or foreign keys. To copy the structure exactly, use CREATE TABLE new_table LIKE old_table; and then INSERT INTO new_table SELECT * FROM old_table;.

Exercise: Create a courses table

Create a table courses with course_id (whole number, primary key), title (text up to 80 characters, required) and fee (whole number, default 0). Insert two courses, one without a fee, and show all rows.

Expected resultMySQL 8.4
mysql> CREATE TABLE courses (
Query OK, 0 rows affected
mysql> INSERT INTO courses (course_id, title, fee) VALUES (1, 'SQL for Tester…
Query OK, 1 row affected
mysql> INSERT INTO courses (course_id, title) VALUES (2, 'Intro to Databases')
Query OK, 1 row affected
mysql> SELECT * FROM courses
course_idtitlefee
1SQL for Testers4999
2Intro to Databases0
2 rows in set
Hint 1

Use INT PRIMARY KEY, VARCHAR(80) NOT NULL and INT DEFAULT 0.

Hint 2

Leave fee out of the column list in the second insert.

Quick quiz

1. What does USE school; do?

2. A column is defined as grade INT DEFAULT 1. What does an insert that leaves out grade store?

3. Which statement copies a query result into a new table?

4. What does IF NOT EXISTS change?

CREATE TABLE FAQ

What is the difference between a database and a schema in MySQL?

In MySQL they are the same thing: CREATE SCHEMA is a synonym for CREATE DATABASE. In PostgreSQL and SQL Server a schema is a namespace inside a database.

How do I see the structure of a table in MySQL?

Use DESCRIBE table_name; for a column list, or SHOW CREATE TABLE table_name; for the full CREATE TABLE statement including indexes and foreign keys.

How do I copy a table in SQL?

CREATE TABLE copy AS SELECT * FROM original; copies columns and data. CREATE TABLE copy LIKE original; copies the exact structure with indexes but no rows.

How do I create a table only if it does not exist?

Write CREATE TABLE IF NOT EXISTS table_name (...). If the table exists, MySQL leaves it unchanged and issues a note instead of an error.

Leave a Comment