Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Insert Example

I switch between Oracle and SQL Server occasionally, and often forget how to do some of the most trivial tasks in SQL Server. I want to manually insert a row of data into a SQL Server database table using SQL. What is the easiest way to do that?

For example, if I have a USERS table, with the columns of ID (number), FIRST_NAME, and LAST_NAME, what query do I use to insert a row into that table?

Also what syntax do I use if I want to insert multiple rows at a time?

like image 611
n00b Avatar asked Nov 14 '12 20:11

n00b


People also ask

What is insert command in SQL with example?

INSERT INTO Syntax It is possible to write the INSERT INTO statement in two ways: 1. Specify both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...

What is insert in SQL Server?

The INSERT INTO Statement in SQL allows you to insert one or more rows into an existing table, either from another existing table, or by specifying the VALUES you want to insert. This article will explore how the statement works and provide a number of examples.

What is insert with example?

Techopedia Explains Insert INSERT INTO table_name VALUES (val1, val2, val3…). An example is: INSERT INTO Employee VALUES (1, John, 23); INSERT INTO table_name (column1, column2) VALUES (val1, val2, val3…). An example is: INSERT INTO Employee (Eid, Name, Age) VALUES (1, John, 23);

How do you insert a row in SQL Server?

If you want to add data to your SQL table, then you can use the INSERT statement. Here is the basic syntax for adding rows to your SQL table: INSERT INTO table_name (column1, column2, column3,etc) VALUES (value1, value2, value3, etc); The second line of code is where you will add the values for the rows.


1 Answers

To insert a single row of data:

INSERT INTO USERS VALUES (1, 'Mike', 'Jones'); 

To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.

INSERT INTO USERS (FIRST_NAME, LAST_NAME) VALUES ('Stephen', 'Jiang'); 

To insert multiple rows of data in SQL Server 2008 or later:

INSERT INTO USERS VALUES (2, 'Michael', 'Blythe'), (3, 'Linda', 'Mitchell'), (4, 'Jillian', 'Carson'), (5, 'Garrett', 'Vargas'); 

To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:

INSERT INTO USERS (FIRST_NAME, LAST_NAME) SELECT 'James', 'Bond' UNION ALL SELECT 'Miss', 'Moneypenny' UNION ALL SELECT 'Raoul', 'Silva' 

Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.

like image 174
n00b Avatar answered Oct 02 '22 14:10

n00b