Sample Video Frame

Created by Zed A. Shaw Updated 2024-10-08 04:45:56

Exercise 10: Updating Complex Data

In the previous exercise you did a simple UPDATE that changed just one row. In this exercise you'll use sub-select queries again to update the pet table using information from the person and person_pet tables.

View Source file ex10.sql Only

SELECT * FROM pet;

UPDATE pet SET name = 'Zed''s Pet' WHERE id IN (
    SELECT pet.id 
    FROM pet, person_pet, person 
    WHERE 
    person.id = person_pet.person_id AND
    pet.id = person_pet.pet_id AND
    person.first_name = 'Zed'
);

SELECT * FROM pet;

This is how you update one table based on information from another table. There're other ways to do the same thing, but this way is the easiest to understand for you right now.

What You Should See

As usual, I use my little code.sql to reset my database and then output nicer columns with sqlite3 -header -column -echo.

View Source file ex10.sh-session Only

$ sqlite3 mydata.db < code.sql
# ... output cut ...
$ sqlite3 -header -column -echo mydata.db < ex10.sql 
SELECT * FROM pet;
id          name        breed       age         dead      
----------  ----------  ----------  ----------  ----------
0           Fluffy      Unicorn     1000        0         
1           Gigantor    Robot       1           0         

UPDATE pet SET name = "Zed's Pet" WHERE id IN (
    SELECT pet.id 
    FROM pet, person_pet, person 
    WHERE 
    person.id = person_pet.person_id AND
    pet.id = person_pet.pet_id AND
    person.first_name = "Zed"
);

SELECT * FROM pet;
id          name        breed       age         dead      
----------  ----------  ----------  ----------  ----------
0           Zed's Pet   Unicorn     1000        0         
1           Zed's Pet   Robot       1           0         
$

Study Drills

Portability Notes

We have to use sub-select queries to do this because SQLite3 doesn't support the FROM keyword in the SQL language. In other databases you can do traditional joins in your UPDATE just like you would with SELECT.

Previous Lesson Next Lesson

Register for Learn SQL the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.