0

Basically this question was asked in an interview and I couldn't answer.

The tables employee is as follows:

  id |  name | start_date | end_date

    1      A     2015-01-09   2018-03-23
    2      B     2012-07-21   2019-01-22
    3      C     2013-04-07    null
              -
          -
          -

Now I have to find the id,name of all employees who worked during the year 2017.

Can you please help me.

3 Answers3

2

You may try something like this:

SELECT id FROM employee
WHERE YEAR(start_date) <= 2017 AND (end_date IS NULL OR YEAR(end_date) >= 2017)

hope this query doesn't require explanation, because it's pretty clear)

cn007b
  • 16,596
  • 7
  • 59
  • 74
1

This is just the overlapping range problem, which can be handled by this query:

SELECT id, name
FROM employees
WHERE
    ('2017-01-01' <= end_date OR end_date IS NULL) AND
    '2017-12-31' >= start_date;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Not sure why we would need to check for the `end_date` though. – Darshan Mehta Feb 18 '19 at 14:52
  • @DarshanMehta Have a look at the comment under your answer. – Tim Biegeleisen Feb 18 '19 at 14:53
  • Yep, corrected it now, and deleted as it became the copy of your answer :) – Darshan Mehta Feb 18 '19 at 14:54
  • Looks correct but just curious as to the reasoning behind having the criteria before the field names? i.e. why '2017-01-01' <= end_date as opposed to end_date >= '2017-01-01' . Both are the same but it just looks strange, wondering if there is a reason for it? – ChrisCarroll Feb 18 '19 at 15:03
  • @ChrisCarroll I based my answer off [this accepted answer](https://stackoverflow.com/questions/2545947/check-overlap-of-date-ranges-in-mysql) and did not bother to rearrange things. You may do that if you want. – Tim Biegeleisen Feb 18 '19 at 15:12
  • @TimBiegeleisen that's fine, as I said I knew it wasn't any different but I just found it strange to look at, was afraid I was missing something. thanks – ChrisCarroll Feb 18 '19 at 15:36
0

I think this will do,

select * from employee where start_date >= '2017-01-01' and end_date <= '2017-12-31'
Santosh
  • 874
  • 11
  • 21