Get startedGet started for free

Writing do statements

Commonly when cleaning data, we'll get data that will have bad dates in it. This would cause an exception and halt our SQL statement; however, by using a DO function with an exception handler, our statement will run to completion. Let's see how we can handle that type of exception with the patients table and the created_on column. This will also give us a chance to use a DO style function.

This exercise is part of the course

Transactions and Error Handling in PostgreSQL

View Course

Exercise instructions

  • Create a DO function to initiate catching an exception.
  • BEGIN a transaction where you INSERT the row (a1c = 5.8, glucose = 89, fasting = TRUE, and created_on = '37-03-2020 01:15:54') into patients.
  • Add an EXCEPTION handler, that inserts 'bad date' in the detail column of the errors table in case of an error.
  • Specify the 'plpgsql' language .

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

-- Create a DO $$ function
____ ____
-- BEGIN a transaction block
BEGIN 
    INSERT INTO patients (a1c, glucose, fasting, created_on) 
    VALUES (____, ____, ____, '37-03-2020 01:15:54');
-- Add an EXCEPTION
___
-- For all all other type of errors
WHEN others THEN 
    INSERT INTO errors (msg, detail) 
    VALUES ('failed to insert', '____');
END;
-- Make sure to specify the language
$$ language '____';

-- Select all the errors recorded
SELECT * FROM errors;
Edit and Run Code