This tutorial will show how to insert values into table within a database. In SQL, there are two ways to insert data into a table:  one row at a time and multiple rows at a time. This tutorial will show examples of both. Both examples use the INSERT INTO statement, which is used to insert new records in a table.

Setting Up

In these examples, we will be using a table called SportsTeams in a database called Sports. Both of these play an important role in specifying exactly where to insert the values. With that said, if you do not have both of these created, please do so.

The SportsTeams table has three columns: Name, City, and SportsTeam. Each column will be of the varchar data type and will not accept null values. To create a table within a database, simply specify a database with the USE statement and use the CREATE TABLE statement to define a name and columns for the table.

First Example

In this example we will insert a single value into the SportsTeams table. This query will use the USE statement to specify the use of the Sports database in this query. We then use the INSERT INTO statement to specify what table and which columns to insert values into. Last but not least, we use the VALUES statement to specify new data to be added for each column. 

Execute the query and it should complete successfully.

Second Example

This example will differ from the first one in that it will insert multiple values in a single query instead of only one. The query is similar to the previous one in that is specifies a database and table to insert values into. To be able to add multiple values, we remove the VALUES statement in favor of the SELECT statement. The SELECT statement is used to select data from a database. Next we use the UNION statement which prevents duplicates from being added to the table. The rest is just a rinse and repeat process until you are finished adding data into the table.

Execute the query and it should complete successfully.

Output

If you run a query to view all data entries in the table, you will see all values inserted in both examples in the table. As you can see, the Giants value from the first example and the rest of the values in the second example are in the table.

Both ways add values but depending on your situation, one might be more useful than the other. If you only need to add one value into a table, use example one, but if you need to add multiple values, then example two is the one to use.

Thanks for reading and make sure to download the source files to get a better understanding of how the code works.

Download Source Files