Inserting the data

Previously, we talked about reading data (the SELECT query) and updating data (the UPDATE query.) Now we’re going to insert data into our database!

Now, to insert data, we need to use what we learned with the SELECT query because it is a major part of what is used to insert the data, as seen below.

INSERT INTO [SampleData] (FirstName, LastName, DateOfBirth)
SELECT FirstName, LastName, DateOfBirth FROM [SampleTable] WHERE LastName = ‘Wilkie’;

You should be fairly familiar with this piece of code as most of it is exactly like the SELECT query we learned earlier!  The only thing we did was add the INSERT INTO portion which tells the database that we want to insert data into one table – in this case, SampleData . In this case, we are going to insert the data from our SELECT query – the values in the fields FirstName, LastName, and DateOfBirth – into the fields named FirstName, LastName, and DateOfBirth as shown between parenthesis.

Now, if there are any other fields in the table SampleData , they will be populated with any default values that the table has been created with. If there are no defaults, then those fields will have the non-value of NULL.

For those of you unfamiliar with NULL , it is a very special value that means that no value exists. Not that the value is nothing, but that there is no value. For example, let’s say Jill asks Sam how many Doctor Who DVDs he owns. Up until the moment he says an answer, Jill has no idea what the answer may be. This value would be best characterized as NULL because there literally is no answer to the question.

Now, if you are just putting values into a table that do not come from another table in any way, shape, or form, then you can use the below code:

INSERT INTO [SampleData] (FirstName, LastName, DateOfBirth)
VALUES (‘Jill’, ‘Smith’, ‘6/6/1992’)

For the most part, I tend to go with the SELECT statement instead of the VALUES term, but it is, as always, up to the reader to decide which one you like better and in which circumstances.

So, now we’ve covered reading data, updating data, and inserting data. What do you think we’ll cover next time? Take your guesses and come back next week to see if you’re right!


2 thoughts on “Inserting the data

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s