Skip to main content

Inserting Data into Tables

MySQL is a powerful relational database management system often used to manage the data from websites and applications. One of the most common operations in MySQL is inserting data into tables. In this tutorial, we will go over how to insert data into tables in MySQL.

Prerequisites

Before we start, ensure that you have MySQL installed and a database to work with. You should also have a basic understanding of SQL and how to use the MySQL command-line interface.

Create a Table

Before we can insert data into a table, we first need to have a table. Let's create a simple 'users' table by executing the following SQL query:

CREATE TABLE users (
id INT AUTO_INCREMENT,
username VARCHAR(50),
password VARCHAR(50),
PRIMARY KEY(id)
);

This SQL statement creates a new table named 'users' with three columns: 'id', 'username', and 'password'. The 'id' column is an integer that automatically increments whenever a new row is added.

Basic Insert

The basic syntax for inserting data into a table in MySQL is as follows:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...);

Let's insert a new user into our 'users' table:

INSERT INTO users (username, password)
VALUES ('testuser', 'testpassword');

This SQL statement inserts a new row into the 'users' table with the username 'testuser' and the password 'testpassword'. The 'id' column is automatically incremented by MySQL.

Insert Multiple Rows

You can also insert multiple rows at once in MySQL. Here's the syntax:

INSERT INTO table_name (column1, column2, column3,...)
VALUES
(value1, value2, value3,...),
(value4, value5, value6,...),
...

Let's insert two more users:

INSERT INTO users (username, password)
VALUES
('user2', 'pass2'),
('user3', 'pass3');

This SQL statement inserts two new rows into the 'users' table.

Conclusion

Inserting data into tables is a fundamental operation in MySQL. The INSERT INTO statement is used to add new rows of data to a table. You can insert one row at a time, or multiple rows at once.

This tutorial is an introduction to inserting data into tables in MySQL. Practice these concepts to become proficient in them. In the next tutorial, we'll cover how to update and delete data in MySQL.