Empty result when using mySQL WEEK() to find dates in current week - mysql

We are using the following statement to select dates of birth which occur in the current week:
SELECT * FROM tbl_user WHERE WEEK(dob,1) = WEEK(CURDATE(),1) ORDER BY id DESC
Our 'dob' column has the type DATE and contains 1 record where dob is 1972-07-09. However, when we run our query (today is 2014-07-07) we get an empty result.
Any ideas why?? Does WEEK() only work on columns with type DATETIME?
Thanks in advance for an help!

SELECT WEEK('1972-07-09',1); //result= 27
SELECT WEEK('2014-07-07',1); //result=28
For Example :
SELECT WEEK('2014-01-18',1); //result=3
Your where condition does not satisfy that why It's return false and Empty Result.
Check Manual here

2014-07-07 is week 28 and 1972-07-09 is week 27. 27 is not equals 28 so you get no result.
You can check this with that query:
select week('2014-07-07',1),week('1972-07-09',1) from tbl_user ;

SELECT WEEK('1972-07-09',1);
result: 27
SELECT WEEK('2014-07-07',1);
result: 28
In this case your condition WHERE WEEK(dob,1) = WEEK(CURDATE(),1) is False. That's why you get an empty result.

Your definition of week is not the same as MySQLs. For a better and more efficient result you should instead decide on the min and max range you wish to find and select that which allows you to define when your week starts and ends.
SELECT *
FROM tbl_user
-- min range == 00:00:00 on the first day of week
WHERE dob >= ADDDATE(CURRENT_DATE, INTERVAL 1-DAYOFWEEK(CURRENT_DATE) DAY)
-- max range == 00:00:00 on the first day of next week
AND dob < ADDDATE(CURRENT_DATE, INTERVAL 8-DAYOFWEEK(CURRENT_DATE) DAY)
ORDER BY id DESC
The start and end date can be adjusted as needed, but because you aren't applying a function to the dob field you will avoid a table scan.

Related

MYSQL: How to get rows till specific month's end from very start

I'm working on a project for a Fuel Pump. Here is my table for the records:
I want to display rows from very start (2019-07-03) till the end of the specific month (e.g 2019-09-29) . How could i do achieve this?
A simple WHERE clause will do the trick
SELECT id, date, total_amount, total_paid
FROM table
WHERE date <= LAST_DAY(CURDATE())
CURDATE() will return current date i.e. 2019-09-08
LAST_DAY() will return the last date of current month i.e. 2019-09-30
WHERE clause will return all rows with date <= 2019-09-30
Update
If you want to filter records based on user input which is month and year ( 2019-09 ) then either it can done by appending '-01' at scripting side or using CONCAT at MySQL level,
WHERE date <= LAST_DAY(CONCAT('2019-09', '-01'))
I think this will work. You can change dates accordingly.
Select *
From table
Where date>='2019-07-03' AND date<='2019-09-29'

SQL for Selecting Current Month in a Date Field and then only if Current date in greater that a certain date

This sql with mysql db does not work:
SELECT *
FROM `house1_rent_2014`
WHERE MONTH( `FIRST_OF_MONTH` ) = MONTH( NOW() )
AND DATE_ADD(MONTH(`FIRST_OF_MONTH`,INTERVAL 15 DAY) <= CURDATE();
what I want to do is get all the current month vales from the column FIRST_OF_MONTH (that works OK by itself) and then add the additional test if it's a current month value of course in the date field and today's date is greater than the 15th of the current month then select that. In other words a field has 2014-09-01 (again, I only want date fields with the current month) if today is 9/15 or later then select it.
I'm getting mixed up w/syntax and perhaps proper logic. Grateful for help
The syntax you have is way more convoluted than it needs to be, and I think the specification is overly confusing too.
"get all the current month vales from the column FIRST_OF_MONTH"
Did you want to return values from September of last year too? (The MONTH() function only returns the month value (1 thru 12), and doesn't include the year, which seems a bit odd.
To get rows for the "current month", we'd typically do something like this:
WHERE t.first_of_month >= DATE_FORMAT(NOW(),'%Y-%m-01')
AND t.first_of_month < DATE_FORMAT(NOW(),'%Y-%m-01') + INTERVAL 1 MONTH
Predicates on a "bare column" allow MySQL to make effective use of an index, in this case, a range scan of an index with leading column of first_of_month. If we wrap those columns in a function, then MySQL has to evaluate the function on every row on the table.
"then add the additional test if it's a current month value of course in the date field and today's date is greater than the 15th of the current month then select that."
You already have a predicate that checks for dates in the "current month", there's no need to repeat that.
This predicate will evaluate to TRUE if the current date is after the 15th, and will return FALSE if the current date is the 15th or earlier.
AND DATE(NOW()) > DATE_FORMAT(NOW(),'%Y-%m-15')
Examples
If we have these rows in the table:
row first_of_month
--- --------------
1 2014-09-30
2 2014-10-02
3 2014-10-14
4 2014-10-16
5 2014-10-31
6 2014-11-01
If we run a query with these predicates:
WHERE t.first_of_month >= DATE_FORMAT(NOW(),'%Y-%m-01')
AND t.first_of_month < DATE_FORMAT(NOW(),'%Y-%m-01') + INTERVAL 1 MONTH
AND DATE(NOW()) > DATE_FORMAT(NOW(),'%Y-%m-15')
If DATE(NOW()) returns '2014-10-11', then the third predicate will evaluate to FALSE, and no rows will be returned.
If DATE(NOW()) returns '2014-10-16', then all of the rows with first_of_month in the current month are returned, that is, rows 2 thru 5 in the example data.
If DATE(NOW()) returns '2014-11-07', then third predicate is false, and no rows are returned.
If DATE(NOW()) returns '2014-09-25', the query will return row 1 in the example data.

MySQL - Using a date range vs functions

I needed to know how many users registered during June and July, this is the first query I wrote:
select count(*) from users where created_at>="2013-06-01" and created_at<="2013-07-31"
Result: 15,982
select count(*) from users where year(created_at)=2013 and month(created_at) in (6,7)
Result: 16,278
Why do they return a different result? Could someone explain? Or am I missing something?
Thanks.
Both query should be equivalent, except that the first one is able to make use of an index and it should be faster, and except the case in which created_at is not a DATE but is a TIMESTAMP.
If created_at is a timestamp, you should write your first query this way:
select count(*) from users
where created_at>='2013-06-01' and created_at<'2013-08-01'
otherwise your first query will exclude all records created on 31th of July, after midnight, eg. 2013-07-31 00:00:00 will be included while 2013-07-31 09:15:43 will be not.
The reason is that your date values do not include the last day: The date constants are converted to a timestamp at midnight. You are querying between these values:
2013-06-01 00:00:00
2013-07-31 00:00:00
So only the first second of the last day is included.
Try this:
select count(*)
from users
where created_at>="2013-06-01"
and created_at<="2013-07-31 23:59:59"
Or more simply make less than the next day:
select count(*)
from users
where created_at>="2013-06-01"
and created_at<"2013-08-01" -- < 1st day of next month

MySQL Time and Date query problems

I want to make a query which returns me some values between two dates and two times...
The DATE and TIME values are in different columns, DATE is called FECHA and TIME is called HORAIN
I have 4 possible values with just a DATE query:
Value 1 has Date 2012-05-07 time 02:45:00
Value 2 has Date 2012-05-07 time 12:00:00
Value 3 has Date 2012-05-08 time 04:35:00
Value 4 has Date 2012-05-08 time 07:30:00
What I want to get, is the results from 07:00:00 to 23:59:59 from the first day, and values from 00:00:00 to 06:59:59 from the second day (so an interval from 07 AM to 06:59 AM)
This is my query, which is returning NO VALUES... It must return me VALUE 2 and VALUE 3, because it matches my desired requirements
SELECT * FROM mytable
WHERE
(DATE(fecha)>='2012-05-07' AND TIME(horain)>='07:00:00')
AND
(DATE(fecha)<='2012-05-08' AND TIME(horain)<='06:59:59');
What am I doing wrong? :(
You can fetch result using Concat(). It concatenating two fields value.so You can concatenate fecha with horain field value and then search for results like given below .
SELECT * FROM `mytable` WHERE (Concat(`fecha`, ' ', `horain`, '') <= '2012-05-08 06:59:59') AND (Concat(`fecha`, ' ', `horain`, '') >= '2012-05-07 07:00:00')
Concat() function take 4 parameter.
Value1
String from which concatenate value1 to value2
Value2
String want to concatenate in last
Hopefully it will be helpful for you
thanks.
Try to debug it one step at a time - eliminate as much restrictions and see if you get records - when you get them, add one condition at a time:
start with:
SELECT * FROM mytable
continue with:
SELECT * FROM mytable
WHERE
DATE(fecha)>='2012-05-07'
and so on, until you find the condition that cuts out all your records and see why that is happening
Try SELECT * FROM mytable WHERE FECHA >= 2012-05-07 AND horain >= 07:00:00)
AND FECHA <= 2012-05-08 AND horain <= 06:59:59 );
The time and date are checked separately
If we restructure your where clause and leave out the date part you get:
SELECT * FROM mytable
WHERE TIME(horain)>='07:00:00' AND
TIME(horain)<='06:59:59'
This will never give you a result since both can never be true.
what you can do, is combine the date and time fields
SELECT * FROM mytable
WHERE
concat(fecha,' ',horain) as date BETWEEN '2012-05-07 07:00:00' AND '2012-05-08 06:59:59';

mysql get current date and row date

Is it possible to do sql query on what day is today and get the row of today for date column?
So let say today is july 25th, i have database table sales, column name date, date = sales transaction date in timestamp.
i need all row that the sales date is same with current date and also is it possible set value as gmt+5?
This will get you all the rows for today's date:
SELECT * FROM sales
WHERE DATE(NOW()) = DATE(DATE_ADD(sales_transaction, INTERVAL 5 HOUR))
ORDER BY sales_transaction
As for GMT +5, Do you mean all rows with a sales date +5 hours or today +5 hours?
EDIT: Updated to add 5 hours to sales date. For a column called date, I would use the back-ticks to indicate it's a column name. e.g. SELECT `date`` FROM sales
I can't figure out how to work the back-ticks on the date field. But you should get the idea. Wrap your column names with `
Give some time and Check out Date Time Function of mySQL
SELECT * FROM tablename WHERE salesdate = '1998-1-1';
If your date is stored in GMT timezone
Select *
FROM tablename
WHERE DATE_ADD(NOW(), INTERVAL 5 HOUR) = salesdate
SELECT * FROM `sales` WHERE DAYOFMONTH(FROM_UNIXTIME(date)) = DAYOFMONTH(DATE(now()))
seems working.
Thank you for all of your replies.