0

A set of data is uploaded by my colleague and I have to filter the data by date. Unfortunately my colleague used reserved words of year and month for uploading the data so the data in database looks like this:

babyname     year  month  gender
-----------  ----  -----  ------
Sarah        2018  2      f
Jack         2016  5      m
James        2017  7      m
Susan        2017  1      f

I am going to filter baby girls name who were born from or after April 2017. I wrote following query but it does not filter the data by date at all:

SELECT * FROM babytable
WHERE
gender='f' 
AND
(("year"=2017 AND "month">3) OR "year"=2018);

Would you please let me know what is my mistake. Many Thanks

3
  • 1
    The query correctly returns Sarah - what exactly is your question? Correctly quoting column names that use (non-reserved) keywords as you did will not change the result: rextester.com/PJGVS72570 Commented Sep 17, 2018 at 14:30
  • Your query returns Sarah, as expected! Commented Sep 17, 2018 at 14:34
  • 2
    You can simplify and do where gender = 'f' and ("year", "month") >= (2017,4). Commented Sep 17, 2018 at 14:36

2 Answers 2

1

No need to make the column names into strings, your WHERE gender = 'f' condition has the correct format. Try:

SELECT * FROM babytable
WHERE
gender='f' 
AND
((year=2017 AND month>3) OR year=2018);
Sign up to request clarification or add additional context in comments.

4 Comments

Syntax error... YEAR and MONTHS are reserved words, so these columns need to be delimited.
@jarlh: no, they don't need to be quoted. They are keywords, but they non-reserved keywords: rextester.com/PJGVS72570
@a_horse_with_no_name, they aren't? Sorry for jumping to conclusions. (According to the ANSI/ISO SQL spec they are reserved.)
1

demo: db<>fiddle

SELECT 
    * 
FROM 
    births 
WHERE
    gender = 'f' 
    AND ((year = 2017 AND month > 4) OR (year > 2017))

Alternatively you could convert the year and month columns into dates before comparing:

SELECT 
    * 
FROM 
    births 
WHERE
    gender = 'f' 
    AND to_date(year || '-' || month, 'YYYY-MM') > '2017-04-30'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.