Basic SQL - UPDATE
13 May 2009 @ 11:02AM

Updated: 25 Jan 2010 @ 01:06PM
So far we've learned how to insert new rows and select them. So now we'll see how to update them.


A Simple Update

Here's an example of a simple update. I write the keyword UPDATE, mention the table name and then SET lets SQL know where my updates are starting at. In this case I'm setting the firstName to Jim, the lastName to Jobs, the email to jim@job.com, and I have a WHERE clause specifying to do these changes where userid=2. What if I'd omitted the WHERE clause? I would have set the firstName, lastName, and emailAddress on every single row on the table. And there is no undo. Thus it's VERY important you be careful with what you're doing when you're using an UPDATE statement. You can see that this update affected 1 row. You may find it helpful to write a select using the where clause of your update statement so you can see what rows will be affected before destroying something. Here the select might look like SELECT * FROM users WHERE userid=2. If you're expecting to update 1 row, you hit execute, and rows affected reads more than 1, get ready to restore a backup.


Another Simple Update

Here's another update. I just disallowed access to everyone with a last name of Clinton. Bill, Hillary, and George need to find another website to hang out on. As you can see, this affected 3 rows. As with SELECTs, you can make a more complicate WHERE clause. However, the basic structure of the update remains the same.

Next, let's find out how to delete a row with the DELETE command.
Comments (0)