Instruction
Good job! Now, it's time to review what we've learned in this part:
- We covered and practiced the syntax of
CREATE FUNCTION. We focused on scalar functions (the most simple kind of user-defined functions that return a single value). - Basic PL/pgSQL syntax consists of:
- Declaring variables (
DECLAREkeyword). - Declaring constants (
CONSTANTkeyword). - Assignments (we can assign a default value to a declared variable).
- Conditional instructions (if-then, if-then-else, if-then-elsif).
- Loops (
WHILE,FOR). - Raising exceptions using the
RAISE EXCEPTIONorRAISE NOTICEkeywords. - Handling exceptions to recover from exceptions by using a
BEGINblock with theEXCEPTIONclause.
- Declaring variables (
- We also explained and practiced function parameters:
IN,OUT,INOUT,VARIADIC, andDEFAULT. - Postgres allows us to define more than one function with the same name, so long as the arguments are not the same. We say those functions are overloaded.
Let's go through the final recap exercises.
Exercise
Create a function with a signature of get_count_of_emp_since(month integer, year integer) that returns the number of employees who joined the company after a given month.
The function will return a number (integer type) of employees who joined during or after a given month and year.
Stuck? Here's a hint!
-
Create a variable that will store the date created from the
monthandyeararguments. To do so, use a regular string concatenation:d := year || '-' || month || '-01';
-
Use the
date_trunc('time_part', timestamp)function to get the month in which a given employee started the job, like so:date_trunc('month', start_date) -
Compare those two values. Remember: the
start_datehas to be greater than or equal tod.



