I came across a function in sqlite that I need to convert to postgres syntax. It’s date(date, '-'||strftime('%w',date)||' days').
Can anyone help me convert this sqlite segment to postgres?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This SQLite:
Is, AFAIK, subtracting the day-in-the-week number days (i.e. 0 for Sunday, 1 for Monday, …) from
dateand then converting the result back to adate; see the date function reference for details.I think the equivalent for PostgreSQL would be:
where
dis your date; subtracting an integer from a date subtracts that number of days. Ifdis a timestamp, then you might need to add some casting. There isdate_trunc('week', 'd')as well but that starts numbering the days from Monday so you’d be off by one with that.Here’s a quick breakdown of the SQLite with the
datevariable replaced bydto avoid confusion with thedate()function:First of all,
||is the standard SQL string concatenation operator. Thestrftimefunction is a general purpose date and time formatter that comes from POSIX; the%wformat specifier means “day of the week as a number with Sunday being day zero”; so thestrftimecall gives you 0 for Sunday, 1 for Monday, and so on up to 6 for Saturday. Ifdis a Tuesday, then thestrftimecall will yield 2 and the whole thing ends up as:The modifiers for the SQLite
datefunction have various forms but'-2 days'means just what you’d think: subtract two days fromd. The overall result is that you getdtruncated to the week (where Sunday is considered to be the first day of the week).On the PostgreSQL side:
we can start with
extract;extractis used to extract specific parts of a date or time anddowmeans “day of the week as a number with Sunday being day zero”. Sound familiar? Then the::intcasts the DOW number to an integer and is needed because the DOW actually comes out as a double precision value and there is no operator defined for subtracting a double from a date in PostgreSQL; the cast can also be written in the standard form ascast(x as int). When you subtract an integer from a date in PostgreSQL, you subtract that many days; you can be more explicit by saying things like- interval '3 days'but that would just add more noise in this case so I opted for simplicity. If it is Tuesday, then our PostgreSQL version looks like:and that’s the same as:
And after the subtraction we’d be back on Sunday. There’s also
date_truncin PostgreSQL but that would truncate to Monday not Sunday.