Exercise Solutions: MySQL, Part 1¶
Create¶
Here is an example of how the query tab might look after adding different records:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | INSERT INTO seeds (crop, encourages, use_by)
VALUES ("Agastache", "bees & hummingbirds", 2020);
INSERT INTO seeds (crop, encourages, use_by)
VALUES ("Broccoli", "health", 2019);
INSERT INTO seeds (crop, use_by)
VALUES ("Sun Gold Tomato", 2022);
INSERT INTO seeds (crop, encourages, use_by)
VALUES ("Zinnia", "bees", 2020);
INSERT INTO seeds (crop)
VALUES ("Rutabaga");
INSERT INTO seeds (crop, use_by)
VALUES ("Sun Gold Tomato", 2024);
INSERT INTO seeds (crop, encourages, use_by)
VALUES ("Green Beans", "Cucumber", 2020);
|
Read¶
Open up a new query tab for the SQL commands you code in this section.
Use
SELECT ... FROM ...to list all of the data for all of the columns in theseedstable.SELECT * FROM seeds;
List the
cropanduse_bydata, and useORDER BYto organize the information in DECREASING order by year.- Bonus: For entries with matching
use_byvalues, order first by year and then alphabetically by crop name.
SELECT crop, use_by FROM seeds ORDER BY use_by DESC, crop ASC;
- Bonus: For entries with matching
Update¶
Update a single record based on its
seed_id.- The first entry we added in the Create section has
seed_id= 1. UseUPDATE ... SET ... WHEREto change theuse_bydate for this entry to 2024. - Use a single
UPDATEstatement to change two columns for the entry withseed_id= 4.
UPDATE seeds SET use_by = 2024 WHERE seed_id = 1;
- The first entry we added in the Create section has
With a single
UPDATEcommand, set theexpiredvalue totruefor all entries that have ause_byof this year or earlier.UPDATE seeds SET expired = true WHERE use_by <= 2019;
Delete¶
Delete a single record from the table. Be sure to use its
seed_idrather than any other column value in theWHEREclause.DELETE FROM seeds WHERE seed_id = 4;
