0
0
PostgreSQLquery~20 mins

INSERT with RETURNING clause in PostgreSQL - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PostgreSQL INSERT Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What does this INSERT with RETURNING output?
Given the table users(id SERIAL PRIMARY KEY, name TEXT, age INT), what is the output of this query?

INSERT INTO users (name, age) VALUES ('Alice', 30) RETURNING id, name;
PostgreSQL
INSERT INTO users (name, age) VALUES ('Alice', 30) RETURNING id, name;
A[{"name": "Alice", "age": 30}]
B[{"id": 1, "name": "Alice"}]
CNo output, just inserts the row
DSyntax error
Attempts:
2 left
💡 Hint
The RETURNING clause returns the specified columns of the inserted row.
📝 Syntax
intermediate
2:00remaining
Which INSERT with RETURNING syntax is correct?
Choose the correct syntax to insert a row and return the generated id and age from table people(id SERIAL, age INT).
AINSERT INTO people (age) VALUES (25) RETURNING id, age;
BINSERT INTO people (age) VALUES (25) RETURN id, age;
CINSERT INTO people (age) VALUES (25) RETURNING (id, age);
DINSERT INTO people (age) VALUES (25) OUTPUT id, age;
Attempts:
2 left
💡 Hint
The keyword is RETURNING without parentheses.
optimization
advanced
2:00remaining
Why use INSERT with RETURNING instead of separate SELECT?
You want to insert a new product and get its generated id immediately. Which is the main advantage of using INSERT ... RETURNING id over inserting then running a separate SELECT to get the id?
AIt returns all columns by default without specifying.
BIt automatically commits the transaction.
CIt locks the entire table to prevent other inserts.
DIt reduces the number of queries and avoids race conditions.
Attempts:
2 left
💡 Hint
Think about efficiency and data consistency.
🔧 Debug
advanced
2:00remaining
What error does this INSERT with RETURNING cause?
Given table orders(order_id SERIAL PRIMARY KEY, amount INT NOT NULL), what error occurs with this query?

INSERT INTO orders (amount) VALUES (NULL) RETURNING order_id;
ASyntax error near RETURNING
BERROR: duplicate key value violates unique constraint
CERROR: null value in column "amount" violates not-null constraint
DNo error, returns order_id
Attempts:
2 left
💡 Hint
Check the NOT NULL constraint on amount.
🧠 Conceptual
expert
3:00remaining
How does RETURNING behave with multi-row INSERT?
Consider this query inserting multiple rows:

INSERT INTO employees(name, salary) VALUES ('John', 5000), ('Jane', 6000) RETURNING id, name;

What will the RETURNING clause output?
AA result set with two rows, each containing the id and name of the inserted employees.
BAn error because RETURNING cannot be used with multiple rows.
CNo output because RETURNING works only for single-row inserts.
DOnly the id and name of the first inserted row.
Attempts:
2 left
💡 Hint
RETURNING returns data for all inserted rows.