How to insert rows into table ?
Inserting rows into a table is a fundamental operation in SQL and is typically accomplished using the `INSERT INTO` statement. Here’s a detailed description of how to insert rows into a table:
1. **Basic Syntax:**
– The basic syntax for inserting rows into a table is:
“`sql
INSERT INTO table_name (column1, column2, …)
VALUES (value1, value2, …);
“`
2. **Table Name:**
– Specify the name of the table into which you want to insert the data.
3. **Column Names:**
– Optionally, you can specify the column names into which you’re inserting data.
– If you omit column names, you must provide values for all columns in the same order they were defined in the table.
4. **Values:**
– Provide the values for each column in the corresponding order.
– Ensure that the data types of the values match the data types of the columns.
5. **Inserting Multiple Rows:**
– You can insert multiple rows in a single `INSERT INTO` statement by providing multiple sets of values separated by commas.
– Example:
“`sql
INSERT INTO employees (first_name, last_name, hire_date)
VALUES (‘John’, ‘Doe’, ‘2024-05-01’),
(‘Jane’, ‘Smith’, ‘2024-04-15’),
(‘David’, ‘Johnson’, ‘2024-03-20’);
“`
6. **Inserting Rows with NULL Values:**
– If a column allows NULL values and you want to insert a NULL, simply omit the value for that column in the `VALUES` list.
– Example:
“`sql
INSERT INTO employees (first_name, last_name, hire_date, department_id)
VALUES (‘Michael’, ‘Brown’, ‘2024-06-10’, NULL);
“`
7. **Inserting Rows with Expressions:**
– You can use expressions, functions, or even subqueries to provide values for columns.
– Example:
“`sql
INSERT INTO employees (first_name, last_name, hire_date, age)
VALUES (‘Sarah’, ‘Wilson’, ‘2024-07-20’, YEAR(CURRENT_DATE()) – YEAR(‘2024-07-20’));
“`
8. **Inserting Rows with DEFAULT Values:**
– If a column has a default value defined, you can omit it from the `VALUES` list to use the default value.
– Example:
“`sql
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(50),
enrollment_date DATE DEFAULT CURRENT_DATE()
);
INSERT INTO students (student_id, name)
VALUES (1, ‘Alice’);
“`
9. **Inserting Rows from Another Table:**
– You can insert rows into a table from the result of a query on another table using the `INSERT INTO … SELECT` statement.
– Example:
“`sql
INSERT INTO new_table (column1, column2, …)
SELECT column1, column2, …
FROM existing_table
WHERE condition;
“`
By following these guidelines, you can effectively insert rows into a table in SQL, whether you’re inserting single rows, multiple rows, or rows based on the result of a query. Always ensure that the data being inserted conforms to the table’s schema and constraints to maintain data integrity.
