0
0
PostgreSQLquery~30 mins

Exception handling (BEGIN-EXCEPTION-END) in PostgreSQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Errors in PostgreSQL with BEGIN-EXCEPTION-END
📖 Scenario: You are managing a small bookstore database. Sometimes, when adding new books, errors can happen, like trying to add a book with a duplicate ID. You want to handle these errors gracefully so the database stays safe and you get a clear message about what went wrong.
🎯 Goal: Build a simple PostgreSQL function that tries to insert a new book into the books table. Use BEGIN-EXCEPTION-END blocks to catch errors like duplicate IDs and handle them by returning a friendly message.
📋 What You'll Learn
Create a books table with columns id (integer primary key) and title (text).
Write a function called add_book that takes book_id and book_title as inputs.
Use a BEGIN-EXCEPTION-END block inside the function to try inserting the book.
Catch the unique_violation exception when a duplicate id is inserted.
Return a message indicating success or the error caught.
💡 Why This Matters
🌍 Real World
Handling errors in database operations is important to keep data safe and provide clear feedback to users or applications.
💼 Career
Database developers and administrators often write functions with exception handling to make systems robust and user-friendly.
Progress0 / 4 steps
1
Create the books table
Create a table called books with two columns: id as an integer primary key and title as text.
PostgreSQL
Need a hint?

Use CREATE TABLE with id INTEGER PRIMARY KEY and title TEXT.

2
Start the add_book function
Write the first line of a function called add_book that takes two parameters: book_id as integer and book_title as text. The function should return text.
PostgreSQL
Need a hint?

Use CREATE OR REPLACE FUNCTION with parameters and RETURNS TEXT. Start the BEGIN block.

3
Add the insert and exception block
Inside the BEGIN block of add_book, write an INSERT statement to add the book to books. Then add an EXCEPTION block to catch unique_violation errors and return the message 'Duplicate book ID'.
PostgreSQL
Need a hint?

Use INSERT INTO inside BEGIN. Add EXCEPTION WHEN unique_violation THEN to catch duplicates.

4
Complete the function with success message
Make sure the function add_book returns 'Book added successfully' when the insert works without errors.
PostgreSQL
Need a hint?

Return the success message right after the insert statement inside BEGIN.