Insert multiple rows of data into a table

Question

In the previous exercise, you learned how to add a facility. Now you're going to add multiple facilities in one command. Use the following values:

  • facid: 9, Name: 'Spa', membercost: 20, guestcost: 30, initialoutlay: 100000, monthlymaintenance: 800.
  • facid: 10, Name: 'Squash Court 2', membercost: 3.5, guestcost: 17.5, initialoutlay: 5000, monthlymaintenance: 80.

Expected Results

facidnamemembercostguestcostinitialoutlaymonthlymaintenance
0Tennis Court 152510000200
1Tennis Court 25258000200
2Badminton Court015.5400050
3Table Tennis0532010
4Massage Room 1358040003000
5Massage Room 2358040003000
6Squash Court3.517.5500080
7Snooker Table0545015
8Pool Table0540015
9Spa2030100000800
10Squash Court 23.517.5500080

Your Answer

Your Results

Loading database...

Answers and Discussion

insert into cd.facilities
    (facid, name, membercost, guestcost, initialoutlay, monthlymaintenance)
    values
        (9, 'Spa', 20, 30, 100000, 800),
        (10, 'Squash Court 2', 3.5, 17.5, 5000, 80);

VALUES can be used to generate more than one row to insert into a table, as seen in this example. Hopefully it's clear what's going on here: the output of VALUES is a table, and that table is copied into cd.facilities, the table specified in the INSERT command.

While you'll most commonly see VALUES when inserting data, Postgres allows you to use VALUES wherever you might use a SELECT. This makes sense: the output of both commands is a table, it's just that VALUES is a bit more ergonomic when working with constant data.

Similarly, it's possible to use SELECT wherever you see a VALUES. This means that you can INSERT the results of a SELECT. For example:

insert into cd.facilities
    (facid, name, membercost, guestcost, initialoutlay, monthlymaintenance)
    SELECT 9, 'Spa', 20, 30, 100000, 800
    UNION ALL
        SELECT 10, 'Squash Court 2', 3.5, 17.5, 5000, 80;

In later exercises you'll see us using INSERT ... SELECT to generate data to insert based on the information already in the database.