PostgreSQL allows more than one function to have the same name, so long as the arguments are different. If more than one function has the same name, we say those functions are overloaded. When a function is called, PostgreSQL determines the exact function is being called based on the input arguments.
Let’s take a look at the following get_rental_duration() function applied to the sample dvdrental database.
CREATE OR REPLACE FUNCTION get_rental_duration(p_customer_id INTEGER)
RETURNS INTEGER AS $$
-- get the rate based on film_id
SELECT INTO rental_duration SUM( EXTRACT( DAY FROM return_date - rental_date))
The get_rental_function accepts p_customer_id as the argument. It returns the sum of duration (in days) that a specific customer rented DVDs. For example, we can get the rental duration of the customer with customer id 278, we call the get_rental_duration function as follows:
It returns the following:
Suppose, we want to know the rental duration of a customer from a specific date up to now. We can add one more parameter p_from_date to the get_rental_duration() function, or we can develop a new function with the same name but have two parameters as follows:
CREATE OR REPLACE FUNCTION get_rental_duration(p_customer_id INTEGER, p_from_date DATE)
RETURNS INTEGER AS $$
-- get the rental duration based on customer_id and rental date
SELECT INTO rental_duration
SUM( EXTRACT( DAY FROM return_date + '12:00:00' - rental_date))
WHERE customer_id= p_customer_id AND
rental_date >= p_from_date;
This function has the same name as the first one except that it has two parameters. We say the function is overloaded by the get_rental_duration(integer, date) function. The following statement gets the rental duration of the customer with customer id 278 since July 1st, 2005:
SELECT get_rental_duration(278, '2005-07-01');
It will result in the following:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!