Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only date/month part from a date in postgres SQL

Tags:

Hello All I have a table in my pg admin database.There is an employee table in this table.Having the field:- 1)name 2)date_of_birth

Now the scenario is that I want to know the birth day for current date and upcoming 20 days For example if current date is 28-Jan-2013 then

1)from_date=28-Jan-2013
2)to_date=16-feb-2013

I want to select all the records from the table for which the date_of_birth

lies between 28-Jan and 16-feb
like image 653
Suri Avatar asked Jan 29 '13 19:01

Suri


People also ask

How do I sort by month name in PostgreSQL?

The TO_DATE(birthday_month, 'Month') function converts a full month name to a date in the ' 0001-MM-01 ' format. For example, you get ' 0001-12-01 ' for December. You can now use the EXTRACT(MONTH FROM date) function to extract the month from this date value.

What is epoch in PostgreSQL?

Posted on 8th September 2022. YES, you can convert EPOCH to Timestamp by merely switching to the present Timestamp in PostgreSQL DBMS. EPOCH time is nothing but the number of seconds from 00:00:00 UTC on 1 January 1970. Till date, without adding the extra leap year days, this is considered.

What is Date_part?

Extracts the specified date or time part from a date, time, or timestamp. Alternatives: EXTRACT , HOUR / MINUTE / SECOND , YEAR* / DAY* / WEEK* / MONTH / QUARTER.


2 Answers

Try this:

SELECT *
FROM   bdaytable
WHERE  bdate >= '2013-01-28'::DATE
AND    bdate <= '2013-02-16'::DATE;

You may also try overlaps:

SELECT *
FROM bdaytable
WHERE (bdate, bdate) 
OVERLAPS ('2013-01-28'::DATE, '2013-02-16'::DATE);

with extract, month, day:

SELECT *
FROM   bdaytable
WHERE  Extract(month from bdate) >= Extract(month from '2013-01-28'::DATE)
AND    Extract(month from bdate) <= Extract(month from '2013-02-16'::DATE)
AND    Extract(day from bdate) >= Extract(day from '2013-01-28'::DATE)
AND    Extract(day from bdate) <= Extract(day from '2013-02-16'::DATE);

Incorporating Now() and interval to make the query dynamic with current date:

SELECT *
FROM   bdaytable
WHERE  Extract(month from bdate) >= Extract(month from Now())
AND    Extract(month from bdate) <= Extract(month from Now() + Interval '20 day')
AND    Extract(day from bdate) >= Extract(day from Now())
AND    Extract(day from bdate) <= Extract(day from Now() + Interval '20 day');
like image 68
bonCodigo Avatar answered Oct 14 '22 09:10

bonCodigo


select *
from employee
where 
    to_char(date_of_birth, 'MMDD') between 
    to_char(current_date, 'MMDD') and to_char(current_date + 20, 'MMDD')
like image 32
Clodoaldo Neto Avatar answered Oct 14 '22 11:10

Clodoaldo Neto