MySQL INSERT

The INSERT statement in MySQL is used to add new records (rows) into a table. It is a fundamental component of database manipulation and is commonly used to populate tables with data. Here is the basic syntax for the INSERT statement:

Syntax

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

Let’s break down the components of this syntax:

INSERT INTO table_name: This part specifies the name of the table where you want to insert data.

(column1, column2, column3, …): Here, you list the columns into which you want to insert data. If you’re inserting data into all columns, you can omit this part.

VALUES (value1, value2, value3, …): This part contains the actual values you want to insert into the specified columns. The values should be in the same order as the columns listed.

Example

Here’s a simple example to illustrate:

Suppose you have a table called employees with columns employee_id, first_name, last_name, and salary. To insert a new employee, you might use an INSERT statement like this:

INSERT INTO employees (employee_id, first_name, last_name, salary)
VALUES (1, 'John', 'Doe', 50000);

This inserts a new record with an employee_id of 1, first_name of ‘John’, last_name of ‘Doe’, and a salary of 50000 into the employees table.

You can also use the INSERT statement without specifying column names if you’re providing values for all columns, like this:

INSERT INTO employees
VALUES (1, 'John', 'Doe', 50000);

It’s important to ensure that the data types of the values match the data types of the corresponding columns. Additionally, be cautious about inserting data into columns with constraints, such as primary keys, unique constraints, or foreign keys, to maintain data integrity within the database.