Tutorial

How to Create and Insert a Table in MySQL: A Beginner’s Guide

Published on May 23, 2025
author

Sr Technical Writer

How to Create and Insert a Table in MySQL: A Beginner’s Guide

Introduction

MySQL is a powerful relational database management system (RDBMS) used widely in web applications, e-commerce platforms, and various backend development projects. This tutorial provides an easy-to-follow guide for beginners on how to create tables and insert data into those tables using MySQL.

Prerequisites

Before you begin, ensure you have the following:

For installation, you can refer to the MySQL Installation Guide.

MySQL Table Syntax

Create Table Syntax

The syntax for creating a table in MySQL with a primary key is as follows:

CREATE TABLE table_name (
    column1_name data_type PRIMARY KEY,
    column2_name data_type,
    ...
);

Role of a Primary Key:

A primary key is a column or set of columns in a table that uniquely identifies each row in the table. It ensures that no two rows have the same value(s) in the primary key column(s), which helps to maintain data integrity and prevent duplicate records. In the context of the example below, the id column serves as the primary key, ensuring each user has a unique identifier.

Example with Primary Key:

CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(255),
    email VARCHAR(255)
);

MySQL Table Syntax without Primary Key

The syntax for creating a table in MySQL without a primary key is as follows:

CREATE TABLE table_name (
    column1_name data_type,
    column2_name data_type,
    ...
);

Most Common MySQL Commands Table

Here’s a table summarizing the MySQL commands used in this tutorial, including their syntax, usage, and examples:

Command Syntax Description Example
CREATE DATABASE CREATE DATABASE database_name; Creates a new database CREATE DATABASE mydatabase;
USE USE database_name; Selects the database to use for the current session USE mydatabase;
CREATE TABLE CREATE TABLE table_name (column1_name data_type, column2_name data_type, ...); Creates a new table in the database CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255));
INSERT INTO INSERT INTO table_name (column1_name, column2_name, ...) VALUES (value1, value2, ...); Inserts new records into a table INSERT INTO users (name, email) VALUES ('John Doe', '<john@example.com>');
SELECT SELECT column1_name, column2_name, ... FROM table_name; Retrieves data from a database table SELECT * FROM users;
UPDATE UPDATE table_name SET column1_name = value1, column2_name = value2, ... WHERE condition; Updates existing records in a table UPDATE users SET name = 'Jane Doe' WHERE id = 1;
REPLACE REPLACE INTO table_name (column1_name, column2_name, ...) VALUES (value1, value2, ...); Inserts new records into a table, or replaces existing records if a unique key constraint is violated REPLACE INTO users (id, name, email) VALUES (1, 'Jane Doe', 'jane.doe@example.com');
DROP TABLE DROP TABLE IF EXISTS table_name; Deletes a table from the database DROP TABLE IF EXISTS users;
DROP DATABASE DROP DATABASE IF EXISTS database_name; Deletes a database DROP DATABASE IF EXISTS mydatabase;

Step 1 - Create a Database

To begin, you need to create a new database where your table will be stored. This is done using the CREATE DATABASE statement, followed by the name of the database you want to create. In this example, we’re creating a database named mydatabase.

CREATE DATABASE mydatabase;

Once the database is created, you need to switch to it using the USE statement. This ensures that any subsequent operations are performed within the context of the newly created database.

USE mydatabase;

By executing these two statements, you have successfully created a new database and set it as the active database for your current session.

Step 2 - Create a Table

To create a table in MySQL, you use the CREATE TABLE statement followed by the name of the table you want to create. In this example, we’re creating a table named users. The table definition is enclosed in parentheses and consists of four columns: id, name, email, and registration_date.

Here’s a breakdown of each column:

CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100),
    email VARCHAR(255) UNIQUE,
    registration_date DATE
);
  • id: This column is defined as an integer (INT) and is set as the primary key of the table using PRIMARY KEY. The AUTO_INCREMENT attribute means that each time a new record is inserted into the table, the value of id will automatically increase by 1, starting from 1. This ensures that each record has a unique identifier.

  • name and email: These columns are defined as variable-length strings using VARCHAR. The number in parentheses specifies the maximum length of the string that can be stored in each column. For name, the maximum length is 100 characters, and for email, it’s 255 characters. The UNIQUE attribute for email ensures that each email address in the table is unique and cannot be duplicated.

  • registration_date: This column is defined as a DATE type, which is used to store dates. It will hold the date when each user registered.

By executing this CREATE TABLE statement, you have successfully created a new table named users with the specified columns and their properties.

Step 3 - Insert Data into the Table

To insert data into the users table, you will use the INSERT INTO statement. This statement is followed by the table name, users, and the columns where you want to insert data, which are name, email, and registration_date. The VALUES keyword is then used to specify the actual values to be inserted into these columns.

In this example, the values being inserted are:

  • name: ‘John Doe’
  • email: ‘john@example.com
  • registration_date: ‘2025-01-10’

Here’s the SQL statement to implement this:

INSERT INTO users (name, email, registration_date)
VALUES ('John Doe', 'john@example.com', '2025-01-10');

By executing this statement, a new record will be added to the users table with the specified values.

Inserting Multiple Rows

When you need to insert multiple rows into a table, using a single INSERT INTO statement with multiple VALUES clauses can be more efficient than executing separate INSERT INTO statements for each row. This approach reduces the number of database interactions, which can improve performance and reduce the load on the database server.

Here’s an example of how to insert multiple rows into the users table in a single statement:

INSERT INTO users (name, email, registration_date)
VALUES
('Jane Smith', 'jane@example.com', '2025-01-11'),
('Emily Johnson', 'emily@example.com', '2025-01-12');

In this example, two rows are inserted into the users table with a single INSERT INTO statement. The VALUES clause is repeated for each row, separated by commas. This approach allows you to insert multiple rows in a single operation, making it more efficient than executing separate INSERT INTO statements for each row.

Step 4 - Verify the Data

After inserting data into the users table, it’s essential to verify that the data has been successfully inserted and is accurate. This step ensures that the data is consistent with the expected output and helps in identifying any potential issues early on.

To verify the data insertion, you can use the SELECT statement to retrieve all the records from the users table. The SELECT * syntax retrieves all columns (*) from the specified table (users). This allows you to view the entire dataset and confirm that the expected data is present.

Here’s the SQL statement to verify the data:

SELECT * FROM users;

When you execute this statement, you should see the following output:

Output
+----+------------+-------------------+----------------+ | id | name | email | registration_date | +----+------------+-------------------+----------------+ | 1 | John Doe | john@example.com | 2025-01-10 | | 2 | Jane Smith | jane@example.com | 2025-01-11 | | 3 | Emily Johnson | emily@example.com | 2025-01-12 | +----+------------+-------------------+----------------+

Step 5 - Update Data

Updating existing records in a database is a crucial operation that allows you to modify data that has already been inserted. This process is essential for maintaining data accuracy and consistency over time. In this step, we will demonstrate how to update a specific record in the users table using the UPDATE statement.

To update existing records, use the UPDATE statement followed by the table name, the SET clause to specify the column(s) to update, and the WHERE clause to specify the condition for which records to update. Here’s an example of how to update the email address of a user with id equal to 1:

UPDATE users SET email = 'john.doe@example.com' WHERE id = 1;

After executing the UPDATE statement, it’s essential to verify that the data has been successfully updated. To do this, use the SELECT statement to retrieve the updated record(s). The SELECT * syntax retrieves all columns (*) from the specified table (users). This allows you to view the entire dataset and confirm that the expected data is present.

Here’s the SQL statement to verify the update:

SELECT * FROM users;

When you execute this statement, you should see the following output, indicating that the email address of the user with id equal to 1 has been successfully updated:

Output
+----+------------+-------------------+----------------+ | id | name | email | registration_date | +----+------------+-------------------+----------------+ | 1 | John Doe | john.doe@example.com | 2025-01-10 | | 2 | Jane Smith | jane@example.com | 2025-01-11 | | 3 | Emily Johnson | emily@example.com | 2025-01-12 | +----+------------+-------------------+----------------+

Practical Usage

Inserting data for a blog, CRM, or e-commerce site

In the context of a blog, CRM (Customer Relationship Management), or e-commerce site, inserting data into a database is a crucial operation. For instance, when a user registers on a blog or e-commerce site, their information needs to be stored in a database for future reference. Similarly, in a CRM system, customer data is inserted into the database to manage interactions and relationships. This process is essential for building a robust and scalable backend infrastructure.

Here’s an example of how to insert user registration data into a database using PHP and MySQL:

<?php
// Assuming $conn is a valid MySQL connection
if (isset($_POST['register'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password']; // Assuming password is hashed for security

    $query = "INSERT INTO users (name, email, password) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("sss", $name, $email, $password);
    $stmt->execute();
    $stmt->close();
}
?>

You can refer to this tutorial on how to install LAMP stack on Ubuntu to learn how to install PHP and MySQL on Ubuntu.

Integration with backend workflows

The ability to insert data into a database seamlessly integrates with various backend workflows. For example, in a web application, user registration data is typically inserted into a database using server-side languages like PHP, Python, or Node.js. This data is then used to authenticate users, manage their profiles, and provide personalized experiences. In a CRM system, data insertion is critical for tracking customer interactions, managing sales pipelines, and generating insights for business growth.

Here’s an example of how to insert customer interaction data into a database using Node.js and MySQL:

const mysql = require('mysql');

// Assuming db is a valid MySQL connection
const insertCustomerInteraction = (customerID, interactionType, interactionDate) => {
    const query = "INSERT INTO customer_interactions (customer_id, interaction_type, interaction_date) VALUES (?, ?, ?)";
    db.query(query, [customerID, interactionType, interactionDate], (error, results, fields) => {
        if (error) throw error;
        console.log('Customer interaction inserted successfully');
    });
};

You can also refer to this tutorial on how to install Linux, Nginx, MySQL, PHP (LEMP stack) on Ubuntu to learn how to install Node.js and MySQL on Ubuntu.

Common errors

Table already exists

When attempting to create a table that already exists in the database, MySQL will throw an error. To avoid this, you can use the IF NOT EXISTS clause in your CREATE TABLE statement. Here’s an example:

CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL
);

Incorrect data types

Using incorrect data types for columns can lead to errors or unexpected behavior. For instance, trying to insert a string into an integer column will result in an error. Ensure that the data types of your columns match the type of data you’re inserting.

Example of incorrect data type usage:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    age VARCHAR(3) NOT NULL // Incorrect data type for age, should be INT
);

INSERT INTO users (name, email, age) VALUES ('John Doe', 'john.doe@example.com', 'twenty-five'); // This will result in an error due to incorrect data type for age

Corrected example:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    age INT NOT NULL // Correct data type for age
);

INSERT INTO users (name, email, age) VALUES ('John Doe', 'john.doe@example.com', 25); // Correct insertion with the right data type for age

Syntax errors

Syntax errors can occur due to incorrect SQL syntax, such as missing or mismatched parentheses, incorrect use of keywords, or incorrect column names. To avoid syntax errors, ensure that your SQL statements are correctly formatted and follow the MySQL syntax guidelines.

Example of syntax error:

INSERT INTO users (name, email, age VALUES ('John Doe', 'john.doe@example.com', 25); // Missing closing parenthesis

Corrected example:

INSERT INTO users (name, email, age) VALUES ('John Doe', 'john.doe@example.com', 25); // Correctly formatted SQL statement

Difference between INSERT, INSERT IGNORE, and REPLACE

When working with MySQL, it’s essential to understand the differences between INSERT, INSERT IGNORE, and REPLACE statements. Each of these statements serves a unique purpose in managing data insertion into tables. Here’s a detailed explanation of each statement, along with examples and a comparison table at the end.

INSERT

The standard INSERT statement inserts a new row into a table. If the row already exists, it will throw an error. This is the most common method of inserting data into a table.

INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com');

INSERT IGNORE

INSERT IGNORE is similar to INSERT, but it ignores the error if the row already exists. This can be useful when you want to insert a row only if it doesn’t already exist. If the row already exists, the statement will silently ignore the insertion attempt.

INSERT IGNORE INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com');

REPLACE

REPLACE works similarly to INSERT, but if the row already exists, it replaces the existing row with the new data. This statement is particularly useful when you need to update existing data or ensure that duplicate rows are not inserted.

REPLACE INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com');

Comparison Table

Here’s a comparison table to help you understand the key differences between INSERT, INSERT IGNORE, and REPLACE:

Statement Behavior if Row Exists Error Handling
INSERT Throws an error Raises an error
INSERT IGNORE Ignores the insertion Silently ignores the error
REPLACE Replaces the existing row Raises an error if the row does not exist

When deciding which statement to use, consider the following:

  • Use INSERT when you want to ensure that a row is inserted only if it doesn’t already exist, and you want to handle errors explicitly.
  • Use INSERT IGNORE when you want to insert a row only if it doesn’t already exist, and you don’t care about handling errors.
  • Use REPLACE when you want to ensure that a row is inserted or updated if it already exists, and you want to handle errors explicitly.

By understanding the differences between these statements, you can choose the most appropriate method for your data insertion needs and ensure data integrity in your MySQL database.

How to use prepared statements

Prepared statements are a secure way to execute SQL statements with dynamic inputs, protecting against SQL injection attacks by separating code from data. In PHP, use mysqli or PDO to prepare and execute statements. Here’s a concise example using mysqli:

<?php
// Prepare an SQL statement to insert a new user into the 'users' table
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
// Bind the parameters to the SQL statement, specifying the types of the variables
$stmt->bind_param("ss", $name, $email);
// Assign values to the variables
$name = 'Jane Doe';
$email = 'jane.doe@example.com';
// Execute the prepared statement
$stmt->execute();
// Close the prepared statement
$stmt->close();
?>

For in-depth information on prepared statements, please refer to the How To Use Stored Procedures in MySQL and PHP documentation for mysqli or PDO usage.

FAQs

1. Can I create a table without defining a primary key?

Yes, you can create a table without defining a primary key. However, it’s highly recommended to define a primary key for each table to ensure data integrity and facilitate efficient data retrieval. Here’s an example of creating a table without a primary key:

CREATE TABLE users (
  name VARCHAR(255),
  email VARCHAR(255)
);

2. How do I insert multiple rows in one query?

You can insert multiple rows in one query using the following syntax:

INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com'), ('Jane Doe', 'jane.doe@example.com');

3. What’s the difference between CHAR and VARCHAR in MySQL?

CHAR and VARCHAR are both character data types in MySQL, but they differ in how they store and handle data.

CHAR is a fixed-length string that always occupies the same space, padding with spaces if necessary. For example, CHAR(10) will always store 10 characters, even if the actual data is shorter.

VARCHAR, on the other hand, is a variable-length string that only occupies the space needed to store the actual data. It’s more efficient for storing strings of varying lengths.

Here’s an example of using both CHAR and VARCHAR:

CREATE TABLE users (
  name CHAR(10),
  email VARCHAR(255)
);

4. How do I copy and create a new table in MySQL?

You can copy and create a new table in MySQL using the following syntax:

CREATE TABLE new_users SELECT * FROM users;

This will create a new table new_users with the same structure and data as the users table.

5. How to create a database in MySQL?

To create a database in MySQL, use the following command:

CREATE DATABASE mydatabase;

This will create a new database named mydatabase.

Conclusion

In this tutorial, you have learned how to create and insert a table in MySQL using simple SQL commands. You have also covered some common errors and how to avoid them. This is just the beginning of your MySQL journey. To further enhance your skills, consider exploring these additional tutorials:

These tutorials will help you master more advanced MySQL concepts and improve your database management skills.

Continue building with DigitalOcean Gen AI Platform.

About the author(s)

Anish Singh Walia
Anish Singh WaliaSr Technical Writer
See author profile
Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.