Recently I've used whereBetween to get the date range of both dates but the result is not inclusive in same date. So I come out with this query.
SELECT *
FROM student
WHERE cast(created_at as date) BETWEEN '2019-07-21' AND '2019-07-21'
Now, since I'm just new in laravel. How can I adopt this query to laravel?
Here is my code in laravel:
$student = $this->student
->whereBetween('created_at', ['2019-07-21', '2019-07-21'])
->select('*')
->get()
I dont know how to add cast in whereBetween. Can somebody help me?
I suggest avoiding using the my MySQL CAST() construct and insted include the edge times in both dates. The query will perform better as well.
$student = $this->student
->whereBetween('created_at', ["$from 00:00:00", "$to 23:59:59"])
// If working with Carbon instances
// ->whereBetween('created_at', [$from->format('Y-m-d 00:00:00', $to->format('Y-m-d 23:59:59'])
->select('*')
->get()
You may actually phrase your current query using date literals, and completely avoid the cast to date:
SELECT *
FROM student
WHERE created_at >= '2019-07-21' AND created_at < '2019-07-22'
Laravel code:
$student = $this->student
->where('created_at', '>=', '2019-07-21')
->where('created_at', '<', '2019-07-22')
->select('*')
->get();
Note that this approach leaves the WHERE clause sargable, meaning that an index on the created_at column can be used.
Easy Solution
$student = $this->student
->whereBetween(DB::raw('date(created_at)'), ['2019-07-21', '2019-07-21'])
->select('*')
->get()
Related
I am trying to return the number of years someone has been a part of our team based on their join date. However i am getting a invalid minus operation error. The whole getdate() is not my friend so i am sure my syntax is wrong.
Can anyone lend some help?
SELECT
Profile.ID as 'ID',
dateadd(year, -profile.JOIN_DATE, getdate()) as 'Years with Org'
FROM Profile
MySQL Solution
Use the DATE_DIFF function
The DATEDIFF() function returns the time between two dates.
DATEDIFF(date1,date2)
http://www.w3schools.com/sql/func_datediff_mysql.asp
This method only takes the number of days difference. You need to convert to years by dividing by 365. To return an integer, use the FLOOR method.
In your case, it would look like this
SELECT
Profile.ID as 'ID',
(FLOOR(DATEDIFF(profile.JOIN_DATE, getdate()) / 365)) * -1 as 'Years with Org'
FROM Profile
Here's an example fiddle I created
http://sqlfiddle.com/#!9/8dbb6/2/0
MsSQL / SQL Server solution
The DATEDIFF() function returns the time between two dates.
Syntax: DATEDIFF(datepart,startdate,enddate)
It's important to note here, that unlike it's MySql counterpart, the SQL Server version takes in three parameters. For your example, the code looks as follows
SELECT Profile.ID as 'ID',
DATEDIFF(YEAR,Profile.JoinDate,GETDATE()) as difference
FROM Profile
http://www.w3schools.com/sql/func_datediff.asp
Looks like you're using T-SQL? If so, you should use DATEDIFF:
DATEDIFF(year, profile.JOIN_DATE, getdate())
Using the method from this answer, you can get your result with the following query :
SELECT
Profile.ID as 'ID',
YEAR(getdate()) - YEAR(profile.JOIN_DATE) - (DATE_FORMAT(getdate(), '%m%d') < DATE_FORMAT(profile.JOIN_DATE, '%m%d')) as 'Years with Org'
FROM Profile
If this is MS SQL:
SELECT
Profile.ID as 'ID',
DATEDIFF(YEAR,Profile.JoinDate,GETDATE())
FROM Profile
I have an already existing an working Oracle SQL that compares two dates:
SELECT * FROM table1 WHERE startDate <= TO_DATE(:startDate, 'YYYY-MM-DD');
$startDate = DateTime::createFromFormat('Ymd', 20160108);
As I said, this works fine.
I am trying to generate this query (or one that has the same results) with Doctrine's Query Builder, but I can't get it to work. This is what I did so far:
$startDate = DateTime::createFromFormat('!Ymd', 20160108);
$queryBuilder = $connection->createQueryBuilder();
$queryBuilder->select('*');
$queryBuilder->from('table1');
$queryBuilder->where('startDate <= ' . $queryBuilder->createNamedParameter($startDate, \Doctrine\DBAL\Types\Type::DATETIME));
The above produces this output:
SELECT * FROM table1 WHERE startDate <= :dcValue1;
(:dcValue = '2016-01-08 00:00:00')
And Oracle complains with ORA-01861.
On an SQLite platform, this works fine. Any idea on how to this properly so that it works on both platforms?
when casting a character string to date it must match the NLS date format, or be explicitely formatted. If your code must run on a DB where you cannot be sure what the default session format for dates will be, be explicit. As a general rule, I'd say always be explicit!
SELECT * from table1 where start_Date <= TO_DATE(:dcValue1,'yyyy-mm-dd hh24:mi:ss');
Within your query builder, try something like this, although you will need to escape the single quotes in the format mask. I believe in DBAL that is done by doubling up the quote, but you will need to verify that :
$queryBuilder = $connection->createQueryBuilder();
$queryBuilder->select('*');
$queryBuilder->from('table1');
$queryBuilder->where('startDate <= TO_DATE(' . $queryBuilder->createNamedParameter($startDate, \Doctrine\DBAL\Types\Type::DATETIME) . ' ,''yyyy-mm-dd hh24:mi:ss'')');
Little late to the party,
I am assuming $startDate is a valid Date Object.
$startDate = $startDate->format('d-M-y h:i:s');
$queryBuilder->where('startDate <= ' . $startDate);
Hope this helps some one.
Thanks.
How to compare current date to given date in MySQL I am using like that code but it's not working.
<%
rs=st.executeQuery("select approcode,approemail,appromon,approvemon,approtue,approvetue,approwed,approvewed,approthr,approvethr,approfri,approvefri,approsat,approvesat,commen,months,SUM(nol) from `pushkalit`.`approval`WHERE (CONVERT( `approcode` USING utf8 ) LIKE '%"+user+"%') AND appromon=DATE(now()) OR approtue=DATE(now()) OR approwed=DATE(now()) ");
// i have given in mysql, appromon varchar(30).....so on dateformat have dd/MM/yyyy
%>
You can compare it like
DATE(NOW()) = DATE(duedate)
Will compare only the date part.
you should try this to simple code asL:
SELECT * FROM myTable WHERE DATE(myDate) = DATE(NOW())
See DATE_FORMAT()
SELECT
approcode, approemail, appromon, approvemon, approtue,approvetue, approwed, approvewed, approthr, approvethr, approfri, approvefri, approsat, approvesat, commen, months, SUM(nol)
FROM `pushkalit`.`approval`
WHERE (CONVERT(`approcode` USING utf8) LIKE '%"+user+"%')
AND ( appromon = DATE_FORMAT(NOW(), "%d/%m/%Y")
OR approtue = DATE_FORMAT(NOW(), "%d/%m/%Y")
OR approwed = DATE_FORMAT(NOW(), "%d/%m/%Y") )
Note that i inserted parens around your OR conditions, because i think this is actually what you intended to query.
I have two date columns - from_date and to_date in a database table.
Example:
from_date: 2012-09-10
to_date: 2012-09-30
today: 2012-09-13
I need to fetch all records, if today's date is between from_date and to_date. How do I do that with a SQL query?
If I have loaded the respective record, I can easily decide, if today's date is between from_date and to_date, but I don't know how to fetch those records straight from the database table.
Check the Rails guides on Range conditions:
Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
That will produce the following SQL:
SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
data = ModelName.where("today >= from_date AND today <= to_date")
A secure and easy way to do this would be:
Model.where(':date BETWEEN from_date AND to_date', date: Date.current)
you can use like this:
Data = Model.where("date(now()) between from_date and to_date")
data = ModelName.find(:all, :conditions => "today >= from_date and today <= to_date")
This should do the trick.
today = Date.today
data = ModelName.where("from_date <= ? AND to_date >= ?", today, today)
You could use below gem to find the records between dates,
This gem quite easy to use and more clear By star am using this gem and the API more clear and documentation also well explained.
ModelName.between_times(Time.zone.now - 3.hours, # all posts in last 3 hours
Time.zone.now)
Here you could pass our field also ModelName.by_month("January", field: :updated_at)
Please see the documentation and try it.
Ok, after a long search in google looking for a "rails way" to do a BETWEEN with two date fields and a variable, the most approximate solution I found is creating your own scope to do that.
in your ApplicationRecord write:
class ApplicationRecord < ActiveRecord::Base
scope :between_fields, -> (value, initial_date, final_date) {
where "('#{value}' BETWEEN #{initial_date} AND #{final_date})"
}
end
So now, wherever you need to do a between you can do:
#clients = Client.between_fields(params[:date], :start_date, :final_date)
# SELECT * FROM clients WHERE ('2017-02-16 00:00:00' BETWEEN start_date AND final_date)
You can combine it with others "where" to do your query as specific as you need.
I need some help figuring out and SQL Statement.
I know what I want I just cant express it.
Im using php, so it doesnt need to be exclusivly SQL, its to act as a filter.
Pseudo code
$query="SELECT * FROM MyTable WHERE 'TIS' is not older than 2 days or empty = ''$ORDER"; }
TIS in the name of the column in my table were I store dates in this format 03-12-09 (d,m,y).
The $ORDER is for ordering the values based on values from other fields not dates.
Im looking at
SELECT *
FROM orders
WHERE day_of_order >
(SELECT DATEADD(day,-30, (SELECT MAX(day_of_order) FROM orders)) AS "-30 Days");
But i dont quite think im on the rigth track with this.
Thanks
Try the following:
SELECT *
FROM MyTable
WHERE COALESCE(TIS, SYSDATE) > SYSDATE - INTERVAL '2' DAY
$ORDER
I don't know what database you're using - the above uses Oracle's method of dealing with time intervals. If you're using SQL Server the following should be close:
SELECT *
FROM MyTable
WHERE COALESCE(TIS, GETDATE()) > DATEADD(Day, -2, GETDATE())
$ORDER
In MySQL try this:
SELECT *
FROM MyTable
WHERE COALESCE(TIS, NOW()) > DATE_SUB(NOW(), INTERVAL 2 DAYS)
$ORDER
I hope this helps.
So, I was pretty lost in all this.
How did it got solved:
First I understood that the Statement I was using was not supported by MySql thanks to eligthment from Bob Jarvis.
_ Second In a comment by vincebowdren wich "strongly" adviced me to change the data type on that field to Date wich indeed I had not, it was a string.
It was pretty Dumb for me to try using SQL operations for Dates on a field that had String values.
So I just RTFM: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
and:
mysql> SELECT something FROM tbl_name
-> WHERE DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= date_col;
Then proceeded to change the field value to date.
and this is my perfectly working query:
$query="SELECT * FROM MyTable WHERE DATE_SUB(CURDATE(),INTERVAL 2 DAY) <= TIS OR TIS = 0000-00-00 $ORDER "; }
I would like to thank the posters for their aid.