Showing posts with label where. Show all posts
Showing posts with label where. Show all posts

Wednesday, May 28, 2008

Using DELETE to delete rows from an SQL Database - Tutorial

Using DELETE to remove a row from your SQL Database is simple. You basically tell the delete command the name of the table, and you help it find which row to delete. Let us delete "John Smith" from our database, because he is planning to move out of the country and no longer will use our website.

DELETE FROM Persons WHERE Name='John Smith', Level='Level 3'

And that will delete any John Smith that we have in our database, so long as John also has a Level 3. Be very careful to specify your full deletion requirements. You don't want to accidentally delete the wrong people, or an entire table's worth of information! 'DELETE FROM Persons' or 'DELETE * FROM Persons' would both, in most cases delete all the information in the table. It still leaves the table structure, so it is useful if you need to start with fresh people and the same types of information.

UPDATE information in a database - SQL Tutorial

Updating information in a database is simple also. Last time you can see that we left off Jack's age. We found out it was his 23rd birthday last month, so now we can add this to the database. We'll do that simply by using an UPDATE statement to update his information.

UPDATE Persons SET Age=23 WHERE Name='Jack Smith'

If you're scared of there being two Jack Smiths, you might also add , Level='Level 8 to that statement. If you have two Level 8 Jack Smiths, then you really aught to learn a little about creating ids, so that you can only update the correct Jack.

Searching through database with SELECT... WHERE

SELECT Name FROM Persons WHERE Age < 18

Let's say your website is now only for people 18 and older. You need to find everyone in your database that is under 18, so you can remove them or something. First, you use a select statement to return the information of all people under 18. How? With a WHERE age < 18. This returns anybody who's age is less than 18. You can also find other things, for example if you just want people named "John Smith" do this:

SELECT Name,Age,Level FROM Persons WHERE Name='John Smith'