Get the Current Date and Time using a PostgreSQL Function
Function to return the Current Date and Time
Write a PostgreSQL function to return the current timestamp.
Solution:
-- Create a function named current_datetime that returns a timestamp value
CREATE FUNCTION current_datetime() RETURNS TIMESTAMP AS $$
BEGIN
-- Return the current date and time using the NOW() function
RETURN NOW();
END;
-- Specify the language used in the function as PL/pgSQL
$$ LANGUAGE plpgsql;
Explanation:
- Purpose of the Query:
- Retrieves the current date and time.
- Real-World Application:
- Used in logging, auditing, and scheduling applications.
For more Practice: Solve these Related Problems:
- Write a PostgreSQL function that returns the current time in UTC format.
- Write a PostgreSQL function that returns the name of the current day (e.g., "Monday").
- Write a PostgreSQL function that returns the number of days remaining until the end of the current year.
- Write a PostgreSQL function that returns the first day of the current month.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous PostgreSQL Exercise: Function to Reverse a String.
Next PostgreSQL Exercise: Function to Get the Highest Salary in a Department.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics