Updating date field with min date from selected dates if they are >= to current_date, except when all dates are >= to current date - postgresql

I would like to update the contents of the Date1 column to reflect the oldest date in each row, unless the date has already passed (Date1 < current date), in which case i'd like Date1 to be populated with the 2nd oldest date in the row.
ID
Date 1
Date 2
Date 3
Date 4
001
01/14/2022
01/14/2022
01/15/2022
01/16/2022
002
04/15/2019
04/15/2019
01/10/2021
01/10/2021
I am currently using
update mytable t
set date1 = (
select min(date)
from (values (date2), (date3), (date4)) d(dt)
where dt >= current_date
)
The only problem I run into is when all available dates are prior to the current date. In this case it overwrites the value in the date1 column with null, which is not ideal. I'd like the query to leave the date1 field intact in these instances.

Figured it out:
update mytable t
set date1 = coalesce ((
select min(date)
from (values (date2), (date3), (date4)) d(dt)
where dt >= current_date
), date 1);

Related

Increment a date by a interval from a difference of dates - Postgres

Edited: Added information that date1 is a timestamp
I need to increment date but the interval is based on the difference between the date that I want to increment and another date on the table but preserving date1 hours and minutes. E.g.:
Create myTable
( id serial,
date1 timestamp,
date2 date
)
So, if date1 = '2020-01-10 10:30:00'and date2 = '2020-03-08' I need date1 to be '2020-03-08 10:30:00'
Update myTable set date1 = date1+interval (date2-date1)
The syntax demands single quotes between the value (i.e: date + interval '30 days'). How to wrap the result from (date2-date1) in single quotes? I tried many ways without success:
Update myTable set date1 = date1+interval chr(39)||cast((date2-date1) as varchar)|| ' days'|| chr(39)
Update myTable set date1 = date1+interval $$||cast((date2-date1) as varchar)|| ' days'||$$
Update myTable set date1 = date1+interval ''||cast((date2-date1) as varchar)|| ' days'||''
How to I do this properly?
What you want is to set the date part of date1 to date2 and keep the time part:
update myTable
set date1 = date2 + date1::time;
See the demo.

How to identify invalid dates in postgres table field?

I have a table in PostgreSQL that has two date fields ( start and end ). There are many invalid dates both date fields like 0988-08-11,4987-09-11 etc.. Is there a simple query to identify them? The data type of the field is DATE. Thanks in advance.
Values in a date column ARE valid per definition. The year 0988 = 988 is a valid historic date as well as the year 4987 which is far in the future.
To filter out dates which are too historic or too far in the future you simply make this query:
SELECT
date_col
FROM
table
WHERE
date_col < /* <MINIMUM DATE> */
OR date_col > /* <MAXIMUM DATE> */
For date ranges (your minimum and maximum date) you could use the daterange functionality:
https://www.postgresql.org/docs/current/static/rangetypes.html
https://www.postgresql.org/docs/current/static/functions-range.html
Example table:
start_date end_date
2015-01-01 2017-01-01 -- valid
200-01-01 900-01-01 -- completely too early
3000-01-01 4000-01-01 -- completely too late
0200-01-01 2000-01-01 -- begin too early
2000-01-01 4000-01-01 -- end too late
200-01-01 4000-01-01 -- begin too early, end too late
Query:
SELECT
start_date,
end_date
FROM
dates
WHERE
daterange('1900-01-01', '2100-01-01') #> daterange(start_date, end_date)
Result:
start_date end_date
2015-01-01 2017-01-01
demo:db<>fiddle
Those are valid dates, but if you have business rules that state they are not valid for your purpose, you can delete them based on those rules:
For example, if you don't want any dates prior to 1900 or after 2999, this statement would delete the records with those dates:
DELETE FROM mytable
WHERE
start_date < '1900-01-01'::DATE OR
start_date >= '2999-01-01'::DATE OR
end_date < '1900-01-01'::DATE OR
end_date >= '2999-01-01'::DATE;
If you want to replace the dates with the lowest/highest acceptable dates instead of deleting the entire record, you could do something like this:
UPDATE mytable
SET
start_date = least('2999-01-01'::DATE, greatest('1900-01-01'::DATE, start_date)),
end_date = least('2999-01-01'::DATE, greatest('1900-01-01'::DATE, end_date))
WHERE
start_date < '1900-01-01'::DATE OR
start_date >= '2999-01-01'::DATE OR
end_date < '1900-01-01'::DATE OR
end_date >= '2999-01-01'::DATE;

How to select specific dates in PostgreSQL?

My table:
create table example
(
code varchar(7),
date date,
CONSTRAINT pk_date PRIMARY KEY (code)
);
Dates:
insert into example(code, date)
values('001','2016/05/12');
insert into example(code, date)
values('002','2016/04/11');
insert into example(code, date)
values('003','2017/02/03');
My problem: how to select the previous dates to six month from today ?
In MySQL I can use PERIOD_DIFF,but, in PostgreSQL?
You can try INTERVAL instruction :
SELECT date
FROM example
WHERE date < CURRENT_DATE + INTERVAL '6 months'
AND date > CURRENT_DATE;
You will get the dates from today to six months.

count data in current month - not 30 days back Postgres statment

Ive this query which return data for 30 days from current date , need to modify it to return data for current month only not 30 days from current date
SELECT count(1) AS counter FROM users.logged WHERE createddate >=
date_trunc('month', CURRENT_DATE);
any tips how to tweak this query , at based on Postgres
regards
Something like this should work.
SELECT count(1) AS counter
FROM users.logged
WHERE date_trunc('month', createddate) = date_trunc('month', current_date);
It is already supposed to return the values in current month. Truncation does the conversion 10 Nov 2013 14:16 -> 01 Nov 2013 00:00 and it will return the data since the beginning of this month. The problem seems to be something else.
Ive this query which return data for 30 days from current date , need to modify it to return data for current month only not 30 days from current date
That's incorrect. Your query:
SELECT count(1) AS counter FROM users.logged WHERE createddate >= date_trunc('month', CURRENT_DATE);
returns all dates >= Nov 1st 00:00:00, in other words what you say that you want already. Or then, you've simplified your query and left out the more important bits — those that are broken. If not:
It might be that you've dates in the future and that you're getting incorrect counts as a result. If so, add an additional criteria in the where clause:
AND created_date < date_trunc('month', CURRENT_DATE) + interval '1 month'
It might also be that your sample data has a bizarre row with a time zone such that it looks like the timestamp is from this month but the date/time arithmetics land it last month.
This is will give you data for the current month only. I try to extract month and year. The last step is you can compare created date against current date-time.
SELECT count(1) AS counter
FROM users.logged
WHERE
EXTRACT(MONTH FROM createddate) = EXTRACT(MONTH FROM current_date)
AND EXTRACT(YEAR FROM createddate) = EXTRACT(YEAR FROM current_date);

How do I convert a date ( YYYY-MM-DD ) into a month number in postgresql?

I got a table:
CREATE TABLE TRANSACTION (
transaction_date date,
id_transaction int,
PRIMARY KEY (id_transaction)
);
and I want to compare the month of 'transaction_date' field with a number of month.
SELECT *
FROM TRANSACTION T
WHERE month = transaction_date;
but I don't know how to make this conversion.
You can use EXTRACT(MONTH FROM transaction_date)
SELECT *
FROM transaction
WHERE EXTRACT(MONTH FROM transaction_date) = 1;
sqlfiddle demo
As per the documentation:
EXTRACT (field FROM source)
The extract function retrieves subfields such as year or hour from
date/time values. source must be a value expression of type timestamp,
time, or interval.
SELECT *
FROM TRANSACTION T
WHERE EXTRACT(MONTH FROM TIMESTAMP transaction_date) = month;
month should be an integer between 1 (January) and 12 (December).