I am looking to build a filter component where
my search comes like b_cycle_type = '1st Day Of The Month'
and in the database b_cycle_type
is stored as -1,0,1,2,3,4,5
How can I prepare postgres statement
I am trying:
SELECT "customers".*
FROM "customers"
WHERE (CASE customers.b_cycle_type
WHEN -1 THEN 'Last day of the month'
WHEN 0 THEN 'Align with first'
ELSE to_char(customers.b_cycle_type, '99th') || ' Day Of The Month'
END = '27th Day Of The Month')
It’s not returning any results.
2
Answers
This part
to_char(customers.b_cycle_type, '99th')
actually results in' 27th'
(to_char Docs [*6th from the bottom]) so to combat this I would use the TRIM function.Example
You can avoid the raw SQL but it’s not pretty
But:
b_cycle_type
column is a date, you should define the column as adate
type, not a numerical type. It will enable you to do simplywhere extract('day' from b_cycle_type) = 27
. It’ll also take care of validating all data anyone tries to insert into the table, without having to maintain custom triggers and constraints.smallint
or evendecimal(2,0)
. Also, save the actual date it corresponds to, as a separate column, in order to be able to easily account for months with different lengths, as well as leap years when February is longer."customers"
table structure, whenever you deal with the data from the table, you should make sureb_cycle_type
is between -1 and 31, and within possible number of days for a given month in a given year.