Sub topic 9
Inserting Rows
Prerequisites and the INSERT statement
Assume PostgreSQL is running, you are connected with psql, and the firstdb database contains the books table from the previous chapter:
idis an identity column and primary key.titleandauthorare required text columns.published_yearis an optional integer column.
An SQL row is one record in a table. The INSERT statement adds one or more rows. Name the columns you intend to fill, then provide values in the same order.
INSERT INTO books (title, author, published_year)
VALUES
('Dune', 'Frank Herbert', 1965),
('Neuromancer', 'William Gibson', 1984),
('Emma', 'Jane Austen', 1815);The database generates each id automatically because the statement does not include that column. The result should report that three rows were inserted.
How values map to columns
The first value goes into title, the second goes into author, and the third goes into published_year.
title author published_year
Dune Frank Herbert 1965
Neuromancer William Gibson 1984
Emma Jane Austen 1815The text values use single quotation marks. The year values are integers, so they do not need quotation marks.
You can insert one row at a time:
INSERT INTO books (title, author, published_year)
VALUES ('The Left Hand of Darkness', 'Ursula K. Le Guin', 1969);You can also omit an optional column. PostgreSQL stores NULL, which means “no value,” when the column has no default value.
INSERT INTO books (title, author)
VALUES ('The City & the City', 'China Miéville');The id column should usually be omitted from inserts. PostgreSQL assigns the next identity value and avoids accidental duplicate primary keys.
Seeing inserted rows
Run a query to confirm the data:
SELECT id, title, author, published_year
FROM books
ORDER BY id;The identity values are assigned by PostgreSQL. Do not assume they begin at a particular number if rows were previously inserted or deleted.
You can ask PostgreSQL to return the new row immediately with RETURNING:
INSERT INTO books (title, author, published_year)
VALUES ('Kindred', 'Octavia E. Butler', 1979)
RETURNING id, title;This is useful when application code needs the generated id.
The insertion flow is:
Common errors
A missing required value causes an error because title and author are NOT NULL:
INSERT INTO books (title)
VALUES ('Untitled book');A text value placed in an integer column can also fail. Check the column list and value order when PostgreSQL reports a type error.
Exercise
Write an INSERT statement that adds a book titled "Solaris" by "Stanisław Lem", published in 1961, without specifying the generated id.
Show answer
INSERT INTO books (title, author, published_year) VALUES ('Solaris', 'Stanisław Lem', 1961);