The SQL INSERT statement allows you to insert data into your tables. While, it is certainly possible that a website won’t require and INSERT Statement, it isn’t very likely. Giving the user the ability to put fresh data into your tables is extremely useful if done correctly. The SELECT statement doesn’t need as much caution as the next three statements because you aren’t actually mutating the data.
You may be thinking what could INSERT possibly hurt? I mean it only puts new data in a table, it doesn’t delete anything. You would be correct, but if you gave me the chance, I could change your mind very quickly. Ever heard of spam? Think about an INSERT query that repeats itself over and over, while you squirm around trying to figure out why your database has so much duplicated data that it is virtually useless. While in coding you should always be careful, be extra careful for the rest of these tutorials involving INSERT, UPDATE, and DELETE statements. All warnings aside, let’s get to it:
Here is our table before do the insert:
id | username | password | birthday |
---|---|---|---|
1 | bobdole32 | secretP | 1984-06-01 |
INSERT INTO table_name(username, password, birthday) VALUES( ‘rustyMeerkat’,’digholes’, ‘1995-09-15’)
Don’t freak out. I know it’s a lot different than the SELECT, but it is still really easy. INSERT INTO signals SQL that we are putting new stuff in a table. Of course, table_name is the name of our table. Now, it gets weird. In pseudo code, it is (column_name, column_name, column_name). We just put our column names separated by a comma. Then, we use the keyword VALUES followed by parentheses. Inside the parentheses, we have various values. The order of these values is directly related to the way we put in the columns. For instance, we will be inserting the value ‘rustyMeerkat’ into the username column, ‘digholes’ into the password column, etc. Don’t worry much about the birthday and the date looking value. Dates are a real pain unless they are done right, which we’ll get into later.
But, why is there only 3 values when we have 4 columns? Typically, a good table design will have an ID column. This should also be set to “auto_increment” which tells the database to add one each time. This gives us unique IDs for every record. This unique id will save your life whenever you run into duplicate data situations. Next!