I am having table with column registration year with values like ‘2017-2019’ and ‘2014-2016.
If my input value is 2018 then what will be my SQL query to get that record which is in between ‘2017-2019’.
id | registration_year |
---|---|
1 | 2014-2016 |
2 | 2017-2019 |
above is DB table and my input is 2018. Then it should return id 2.
What will be my sql query.
Thanks in advance
5
Answers
Honestly now would be a good time to change your table design. Consider this version, which stores the registration start and end years in different columns:
With this properly designed table in place, now you only need a simple range comparison:
I agree with TB’s answer where you should redesign your table structure. Here’s a solution with the current structure.
To retrieve the record that matches the input year (2018) with the registration year ranges in the SQL table, you can use the following SQL query with the
BETWEEN
operator:If you always, or almost always, start and end together then rather than a string define the column as a integer range. This still results in a single column. Then query with the range containment operator (<@). So: (See demo)
A note on demo result. When queried the
registration
column will appear as[2017,2020)
. This is correct for your data values (row 2). That is because when queried Postgres always responds as contains the lower bound but does not contain the upper bound. However you will notice that row was created as contains lower bound and contains upper bound.