UPDATE Query

The SQL statement UPDATE is a crossbreed between INSERT and DELETE. It doesn’t exactly do either of them, but it has similar properties of each. UPDATE searches for whatever record or records that satisfy its WHERE condition. Then the update statement overwrites each record’s columns that it was told to. The way the developers created the SQL update statement was brilliant and much better than the INSERT statement. Remember INSERT had those two separate lines in parentheses. Take a look at how much better UPDATE looks:

Updating SQL Records

Our table before:

id username password birthday
1 bobdole32 secretP 1984-06-01
2 rustyMeerkat digholes 1995-09-15
Example
UPDATE table_name
SET username = ‘rustyNails’, password=’hammers’
WHERE username = ‘rustyMeerkat’
Result
id username password birthday
1 bobdole32 secretP 1984-06-01
2 rustyNails hammers 1995-09-15

Boom! You just changed a username and password. A highly insecure way to do it, but for our purposes, it will do. First, we start off by declaring the state with UPDATE to tell SQL were going to change some existing data. Next, we use the keyword SET followed by a column name set to a value. Then, you can use a comma and repeat that for as many columns as you want to update in those records.

Oddly enough, we tell SQL which records to update at the very end with our WHERE condition. Dreams and hearts have been broken by this organization. Don’t ever, ever, ever leave off the WHERE at the end unless you want to update every record. That was one of the saddest few seconds of my life. I left off the where statement at work while putting it into production, and watched in slow motion as the data was overwritten. Luckily, we have an pretty awesome backup system. Please never ever do it and always remember to back up your data before attempting data changing queries.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.