Using INSERT INTO
INSERT INTO is used to insert new row in table. :
INSERT INTO Syntax
There are two ways to use INSERT INTO. In first case, we need to specify column names:
INSERT INTO some_table (column1, [column2, column3... ]) VALUES (value1, [value2, value3...])
The number of columns and values must be the same, or error is returned. You don't need to list all table columns, but you need to provide a value for every listed. Is some column is expected, default value will be used. In case that default value is not exist and value of that column can't be null, then you must specify a value in INSERT INTO or you'll get an error.
Also, it is possible to insert new record to table without specifying column names:
INSERT INTO some_table VALUES (value1, [value2, value3...])
INSERT INTO Simple Example
Let say you have table Customers and you need to store a data about new customer. This SQL will insert a new record to table:
INSERT INTO Customers (FirstName, LastName, Phone, Email) VALUES ('John', 'Doe', '(206) 555-9857', 'john@example.com')
Insert multiple records with INSERT INTO
In case when you need to insert multiple records to table you can simply repeat INSERT INTO statements for each new row, or use this syntax to insert multiple rows at once:
INSERT INTO some_table (column1, column2, column3,...)
VALUES (value1, value2, value3,...),
(value4, value5, value6,...),
(value7, value8, value9,...)
...
Also, you can insert multiple records by selecting rows from some other table (copy selected records from table to table):
INSERT INTO UK_Customers
SELECT First_Name, Last_Name
FROM Customers
WHERE CountryCode = 'UK'
INSERT INTO Risks
INSERT INTO inserts new value to database. Those values are often taken from user. In common case, user will fill online form with some data in text boxes or other controls and click a button to save it to database. You need to be very careful when accept any input from user. Validate every input and take care of SQL injection attacks. The safest way to protect your SQL from SQL injection attacks is to use parameters instead of building SQL from string.
Related articles:
1. SQL Queries For Paging In ASP.NET