PostgreSQL
DATE functions
In PostgreSQL, DATE functions are used to manipulate and query date values. These functions are crucial for working with date and time data effectively. They allow you to perform operations such as calculating differences between dates, extracting specific components of dates, and formatting dates in various ways. For beginners, understanding these functions can simplify many common tasks involving date data.
Here are some key DATE functions in PostgreSQL:
CURRENT_DATE and CURRENT_TIMESTAMPCURRENT_DATEreturns the current date.CURRENT_TIMESTAMPreturns the current date and time.
SELECT CURRENT_DATE; SELECT CURRENT_TIMESTAMP;DATE_TRUNCDATE_TRUNCtruncates a date or time to a specified level of precision, such as year, month, or day.
SELECT DATE_TRUNC('month', CURRENT_DATE) AS start_of_month; SELECT DATE_TRUNC('year', CURRENT_DATE) AS start_of_year;AGEAGEcalculates the interval between two dates or between a date and the current date.
SELECT AGE(CURRENT_DATE, '2000-01-01') AS age_of_date;DATE_PARTDATE_PARTextracts a specific part (like year, month, or day) from a date.
SELECT DATE_PART('year', CURRENT_DATE) AS current_year; SELECT DATE_PART('month', CURRENT_DATE) AS current_month;TO_CHARTO_CHARformats a date or time value into a string according to a specified format.
SELECT TO_CHAR(CURRENT_DATE, 'YYYY-MM-DD') AS formatted_date; SELECT TO_CHAR(CURRENT_TIMESTAMP, 'Day, DD Month YYYY') AS formatted_timestamp;- Example Usage with Banking Tables
- Suppose you have a table
transactionswith atransaction_datecolumn. You can use these functions to query and format date-related data.
-- Find transactions from the current month SELECT * FROM transactions WHERE DATE_TRUNC('month', transaction_date) = DATE_TRUNC('month', CURRENT_DATE); -- Calculate age of transactions SELECT transaction_id, AGE(CURRENT_DATE, transaction_date) AS transaction_age FROM transactions;These functions can help you effectively manage and analyze date data in PostgreSQL, making it easier to handle various date-related tasks.
- Suppose you have a table
To gain complete access, login with gmail or outlook, no need of signup. click here
TEST CODE
Get total order counts for a given year and month.
SELECT EXTRACT(YEAR FROM order_date), EXTRACT(MONTH FROM order_date)
count(*) as monthly_order_count
FROM act_order
GROUP BY EXTRACT(YEAR FROM order_date), EXTRACT(MONTH FROM order_date);Identify the top five hours with the highest order volume within a 24-hour period.
SELECT EXTRACT( HOUR FROM order_date)
count(*) as order_count
FROM act_order
GROUP BY EXTRACT( HOUR FROM order_date)
ORDER BY count(*) DESC
LIMIT 5;Obtain the count of male customers categorized by age, and within that subset, select the top three.
SELECT EXTRACT(YEAR FROM CURRENT_DATE) - birth_year as age
count(*) as customer_count
FROM org_client
WHERE gender= 'M'
GROUP BY EXTRACT(YEAR FROM CURRENT_DATE) - birth_year
ORDER BY EXTRACT(YEAR FROM CURRENT_DATE) - birth_year DESC
LIMIT 3;

Comments Not Found