How do you insert multiple rows into a table with a single SQL statement?

Instruction: Using PostgreSQL and a departments table with department_id integer PRIMARY KEY and department_name text NOT NULL, insert departments (10, Engineering), (20, Support) and (30, Operations) in one statement. Assume those IDs do not exist.

Context: This question assesses the candidate's efficiency in data manipulation, specifically the ability to insert multiple records into a table with a single command.

Updated

Official answer

Assume a PostgreSQL table departments(department_id integer PRIMARY KEY, department_name text NOT NULL) and that IDs 10, 20 and 30 are available:

INSERT INTO departments (department_id, department_name)
VALUES
  (10, 'Engineering'),
  (20, 'Support'),
  (30, 'Operations');

The explicit column list makes each tuple's meaning clear. This is one statement inserting three rows; in this ordinary PostgreSQL INSERT, a constraint violation rejects the statement rather than silently inserting only the valid rows.

Use the database driver's bound parameters for application-supplied values. Do not concatenate untrusted text into SQL. For a very large load, compare bounded batches or a bulk-loading facility such as COPY; statement size and resource use are not unlimited.

Source

PostgreSQL: INSERT.

Related Questions