This is a Makers Bite. Bites are designed to train specific skills or tools. They contain an intro, a demonstration video, some exercises with an example solution video, and a challenge without a solution video for you to test your learning. Read more about how to use Makers Bites.
Learn to write INSERT SQL queries to create new records.
We use the INSERT query to create new records into a table. The general syntax is:
INSERT INTO [table name]
( [list of columns] )
VALUES( [list of values] );In the list of columns, we can choose to specify only the columns we need to insert values for.
For the sake of simplicity, it's best to always specify all columns to insert, except for the id column, as it is configured to be generated automatically by PostgreSQL.
Run the following in the psql REPL:
-- We don't specify the value for the `id`
-- column, the database will automatically pick one.
INSERT INTO artists
(name, genre)
VALUES('Massive Attack', 'Alternative');Here's a video demonstration. Make sure you attempt the exercise before watching the solution.
INSERTa new record inalbumswith title 'Mezzanine', and release year 1998.- We forgot to link this new record with the correct artist. Use an
UPDATEquery to update theartist_idof that new album with Massive Attack (it should have theidvalue 5).
Insert a new artist of your choice, and a new album related to that artist (here's an idea, if you can't pick one).
Then run a SELECT query to check the new artist is now in the table.