Calculate Days Between Two Dates using a PostgreSQL Function
Function to Get the Number of Days Between Two Dates
Write a PostgreSQL function that calculates the number of days between two given dates.
Solution:
-- Create a function named days_between that takes two dates as input and returns an integer
CREATE FUNCTION days_between(start_date DATE, end_date DATE) RETURNS INT AS $$
BEGIN
-- Calculate the difference in days between the end_date and start_date
RETURN end_date - start_date;
END;
-- Specify the language used in the function as PL/pgSQL
$$ LANGUAGE plpgsql;
Explanation:
- Purpose of the Query:
- Calculates the difference in days between two dates.
- Real-World Application:
- Used in event planning, payroll processing, and analytics.
For more Practice: Solve these Related Problems:
- Write a PostgreSQL function that calculates the number of weekdays between two given dates.
- Write a PostgreSQL function that calculates the number of months between two given dates.
- Write a PostgreSQL function that finds how many days have passed since January 1, 2000.
- Write a PostgreSQL function that determines if a given date falls on a weekend.
Go to:
- Comprehensive Guide to writing PL/pgSQL Functions in PostgreSQL Exercises Home. ↩
- PostgreSQL Exercises Home ↩
PREV : Function to return the Current Date and Time.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
