How to create a table in MySQL with example code

To create a table in MySQL we need to use CREATE TABLE syntax. in this post, we will learn how can we create a table in MySQL with examples of code.

create table in sql

Syntax of creating a table in MySQL.

you already know that to create a table in MySQL we need to use CREATE TABLE syntax but to define the column name we need to use the datatype. Also to define the default value or to define the primary key and foreign keys we need to use some keywords.

MySQL Create Table

CREATE TABLE table_name(
   Column_name_1 data_type,
   Column_name_2 data_type,
   Column_name_3 data_type,
   Column_name_4 data_type,
   Column_name_5 data_type
);
The basic structure of creating table in MySQL.

Create a student table in MySQL.

Suppose we want to create a student table with name ID email phone number and age attributes. so in this case our.

  • ✅ The table name will be students.
  • ✅ ID will be the primary key and auto-increment.
  • ✅ Name is required and varchar data type but not unique.
  • ✅ Email is required, unique, and varchar data type.
  • ✅ Phone number is also a varchar data type and unique but not required always.
  • ✅ Finally, the about column will be text datatype.

Example Code

CREATE TABLE students(
   id INT NOT NULL AUTO_INCREMENT,
   Name  VARCHAR(100) NOT NULL,
   Email VARCHAR(255) UNIQUE NOT NULL,
   Phone VARCHAR(255) UNIQUE NULL,
   About TEXT NULL,
   PRIMARY KEY ( id )
);
Here student id is our primary key and it will increment automatically.
Still you face problems, feel free to contact with me, I will try my best to help you.