Notes

`CREATE TABLE` Query in DBMS (MySQL) [ English ]

< Prev Next >

Introduction

In a Database Management System (DBMS), data is stored in the form of tables. A table consists of rows and columns where each column represents a field (attribute) and each row represents a record.

Before storing any data in a database, it is necessary to create a table structure that defines the columns, their data types, and constraints. The CREATE TABLE command is used to create a new table in the selected database.

Definition

The CREATE TABLE query is a Data Definition Language (DDL) command used to create a new table in a database with specified columns, data types, and constraints.

Syntax

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
    ...
);

Where:

How It Works

When the CREATE TABLE command is executed:

  1. The DBMS checks whether the selected database exists.
  2. A new table structure is created in the database.
  3. Column names and their data types are stored in the system catalog (metadata).
  4. The table becomes ready to store records.

Example

First select the database:

USE student_db;

Now create a table:

CREATE TABLE students (
    id INT,
    name VARCHAR(50),
    age INT,
    course VARCHAR(50)
);

This command creates a table named students with four columns:

Column Data Type Description
id INT Stores student ID
name VARCHAR(50) Stores student name
age INT Stores student age
course VARCHAR(50) Stores course name

Example of Table Structure

id name age course
1 Rahul 20 BCA
2 Anita 21 BBA

Each row represents a record, and each column represents a field.

Using IF NOT EXISTS

To avoid errors if a table already exists, MySQL provides the IF NOT EXISTS option.

Syntax

CREATE TABLE IF NOT EXISTS table_name (
    column1 datatype,
    column2 datatype
);

Example

CREATE TABLE IF NOT EXISTS courses (
    course_id INT,
    course_name VARCHAR(50)
);

Common Data Types Used in Tables

Data Type Description
INT Stores integer numbers
VARCHAR(n) Stores variable-length text
CHAR(n) Stores fixed-length text
DATE Stores date values
FLOAT Stores decimal numbers

Key Points

Summary

The CREATE TABLE command is used to define the structure of a table in a database. It specifies the table name, column names, and data types. After creating a table, users can store and manage data using SQL commands such as INSERT, SELECT, UPDATE, and DELETE.

< Prev Next >