Problem with BETWEEN dates

Asked

Viewed 1,338 times

1

I need a light for a question, I have a data filtering system (search) where I have to search for two Initial and Final dates. Since I have these two columns in the database, then when I run the search I choose which column I want to filter. Both columns are of the type date

Then my sql got more or less like this:

SELECT * FROM negocio WHERE data_inicial BETWEEN '2017-01-01' AND '2017-01-30' ORDER BY data_inicial DESC

However in the results it does not only return dates within the selected period, for example it returns date data 2017-02-20 and empty field that does not yet have its date set.


CREATE TABLE negocio (
  negocio_id int(11) NOT NULL auto_increment,
  data_inicial date default NULL,
  data_final date default NULL,
  PRIMARY KEY  (negocio_id)
);

As I said are the fields, but the question is to return the dates within the period selected by the user. In case the user can select whether to search in data_inicial or data_final and in which order he would like to display the data.

  • The query you use is the same as the question?

  • Your dates are saved with hours:minutes:seconds in the bank or not?

  • 1

    Can you paste the table structure here? Sometimes it’s a field with a different name.

  • The query is in a period of 30 days as corrected in question :( I will post the table below

  • The date 2017-02-20 is the column being filtered? If chosen data_inicial then that date is coming in this field?

  • Yes the date 2017-02-20 is in the same filtered column. Correct returning the date in this field.

Show 1 more comment

1 answer

4


You have 2 date fields, the BETWEEN will take the break in data_inicial the way you are doing it. If you want the interval between initial and final date, do it this way:

SELECT * FROM `negocio` WHERE data_inicial >= '2017-01-01' and data_final <= '2017-01-30' ORDER BY data_inicial DESC
  • Yes, that was my first option but it’s not what I need at the moment. The goal here is to know which businesses are due(data_final) in a given period or which were contracted in a given month(data_inicial). Plus your example me a light I can test. SELECT * FROM negocio WHERE data_inicial >= '2017-01-01' and data_inicial <= '2017-01-30' ORDER BY data_inicial DESC

Browser other questions tagged

You are not signed in. Login or sign up in order to post.