To insert a new record in SQL, you use the INSERT INTO
statement. There are
two common ways to write this statement:
- Specify columns and values:
sql
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
You list the columns you want to insert data into, followed by the corresponding values. The values must match the data types and order of the columns specified.
- Insert values without specifying columns:
sql
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
This inserts values into all columns in the table in the order they are defined. You must provide a value for every column, or the statement will fail unless defaults or auto-increment are defined.
Example
To insert a new customer record into a "Customers" table:
sql
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
If the table has an auto-increment primary key like CustomerID
, you don't
need to specify it; it will be generated automatically
Additional notes
- You can insert data into only some columns; unspecified columns will get default or NULL values if allowed.
- You can insert multiple rows at once by separating each row's values with commas.
- To insert data from another table, use
INSERT INTO ... SELECT ...
syntax.
This is the basic and widely supported method to insert new records into SQL tables