Learn SQL the Hard Way – Exercise 8 Deleting Using Other Tables

Here is my work for Exercise 8 Deleting Using Other Tables.

Exercise 8 code
Exercise 8 code

In this exercise, we learn how to delete rows by creating a temporary table through SELECT and using WHERE IN or WHERE NOT IN the temporary table.
Extra Credit

  • Practice writing SELECT commands and then put them in a DELETE WHERE IN to remove those records found. Try deleting any dead pets owned by you.

    I added two more pets for myself. Then deleted any pets that were dead.
    I added two more pets for myself. Then deleted any pets that were owned by me and dead. (Only Paws fits the bill.)

    Goodbye Paws :(
    Goodbye Paws 😦
  • Do the inverse and delete people who have dead pets.
    I added a Tabby cat and a new person Charlie Brown. Charlie Brown owns Mr. Whiskers the tabby cat who is unfortunately dead. 😦 I then delete any people who own dead pets, only Charlie Brown fits the bill and is deleted. Finally, I delete the relationship from the person_pet table.

    Deleting any person who owns dead pets.
    Deleting any person who owns dead pets.

    Goodbye Charlie Brown, you were here and gone so quickly...
    Goodbye Charlie Brown, you were here and gone so quickly…
  • Do you really need to delete dead pets? Why not just remove their relationship in person_pet and mark them dead? Write a query that removes dead pets from person_pet.
    Since I didn’t have any dead pets left, I first added Mr. Jingles as my dead pet. (I added him as a pet, and then added our relationship in the person_pet table.) Initially the person_pet table shows that I own three pets, Mr. Jingles, Drogon, and Jaws. Nobody owns Mr. Whiskers.
    I then deleted any dead pets from person_pet. The person_pet relationship between me and Mr. Jingles is removed from the table.

    Deleting any dead pets from person_pet
    Deleting any dead pets from person_pet
    I am no longer connected to Mr. Jingles.
    I am no longer connected to Mr. Jingles.

    This exercise is a good brain workout, like solving mini puzzles!

 

Advertisements

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