What am I doing wrong? I have an query to get data between two dates, but it does not get the last date.
I tried
select *
from data
where dates between '2016-01-01' and '2016-01-02'
and
select *
from data
where dates >= '2016-01-01' and dates <= '2016-01-02'
I need SQL Server to return data between 2016-01-01 and 2016-01-02
Output should be
pid name date
-------------------------------
1 test2 2016-01-02
2 test2 2016-01-01
3 test3 2016-01-02
This works
select *
from data
where dates >= '2016-01-01' and dates <= '2016-01-03'
but why do I need to add an extra day?
Presumably your column (mis)named dates has a time component. This should work for what you want:
select *
from data
where dates >= '2016-01-01' and dates < '2016-01-03';
Aaron Bertrand, a SQL Server guru, has an excellent blog post on this subject, What do BETWEEN and the devil have in common?. That is a good place to start.
Alternatively, you could write the query as:
select *
from data
where cast(dates as date) >= '2016-01-01' and dates <= '2016-01-02';
Once you remove the time component, the comparisons will work. However, I'm reluctant to use functions on columns, because that can preclude the use of indexes in the query (SQL Server makes an exception for conversion to date).
I agree with #GordonLinoff and was devising an example to show you so I will put it here anyway for you. note you can also just drop off the time component from your field by casting to a date and it will work.
WHERE CAST([date] as DATE) BETWEEN '2016-01-01' and '2016-01-02'
Example so it is apparent
DECLARE #Data AS TABLE (pid INT, name VARCHAR(10), [date] date, [datetime] DATETIME)
INSERT INTO #Data (pid, name, [date], [datetime])
VALUES
(1, 'test1', '2016-01-02', '2016-01-02')
,(2, 'test2', '2016-01-01', '2016-01-01')
,(3, 'test3', '2016-01-02', '2016-01-02')
,(3, 'test3', '2016-01-02', '2016-01-02 11:00:00.000')
SELECT *
FROM
#Data
WHERE
[date] BETWEEN '2016-01-01' and '2016-01-02'
SELECT *
FROM
#Data
WHERE
[datetime] BETWEEN '2016-01-01' and '2016-01-02'
SELECT *
FROM
#Data
WHERE
CAST([datetime] AS DATE) BETWEEN '2016-01-01' and '2016-01-02'
Are your columns datetime or just dates? did you try with convert functions?
e.g.
CONVERT(VARCHAR(10),dates,110) --> 16-06-2016
i guess you have datetime columns which means that comparing with today's date,
if the column is today then >= will always return true and <= will always return false, because timestamp being persisted to DB will probably be >= of today 00:00:00
If the type of your column dates is DATETIME, the query
select * from data
where dates >= '2016-01-01' and dates <= '2016-01-02'
only pick up records that have dates between 2016-01-01 00:00:00.000 and 2016-01-02 00:00:00.000.
It will not pick up the records that have dates > 2016-01-02 00:00:00.000. If you want to the query to pick up all records until 2016-01-02 23:59:59.999, then you will have to use your this query:
select * from data
where dates >= '2016-01-01' and dates < '2016-01-03'
Related
I have a lot of registers in my Database with startdate and enddate. I need to print the interval between these dates, month per month. Example:
StartDate EndDate
2015-01-01 2015-12-01
I need to print like
2015-01-01
2015-02-01
2015-03-01
2015-04-01
until 2015-12-01 for which one registers
If I understand you correctly
DECLARE #startDate DATE, #endDate DATE
SELECT #startDate = '2015-01-01', #endDate = '2015-12-01'
;WITH Calender AS (
SELECT #startDate AS CalanderDate
UNION ALL
SELECT DATEADD(month,1,CalanderDate) FROM Calender
WHERE DATEADD(month,1,CalanderDate) <= #endDate
)
SELECT * FROM Calender ORDER BY CalanderDate
FIDDLE
;WITH CTE AS (
SELECT 0 AS months
UNION ALL
SELECT months + 1
FROM CTE, TESTE t1
WHERE months < datediff(month,t1.dateid,t1.enddate)and t1.code=t1.code)
SELECT distinct t2.code, DATEADD(MONTH,months,t2.dateid), t2.Dscription, t2.Credit, t2.enddate
FROM CTE, TESTE t2 where t2.code=t2.code and DATEADD(MONTH,months,t2.dateid)<=t2.enddate but I need to change to a normal select because crystal reports desnĀ“t accept cte
I have some SQL below which is programmatically generated:
INSERT INTO TABLE (COMID, NAME, DATE)
SELECT DISTINCT 'COM001', 'John', '01-Jan-4501 00:00:00'
How can i amend this so that if it finds the date time of : 01-Jan-4501 00:00:00 then it replaces it with todays date?
You probably want to avoid some wrong or irrelevant values.
SELECT
'COM001',
'John',
case
when cast('01-Jan-4501 00:00:00' as date) > cast('01-Jan-2100 00:00:00' as date)
then cast(getdate() as varchar(30))
else '01-Jan-4501 00:00:00'
end
Another way is to create a trigger on that table that automatically makes the date field correction.
SELECT DISTINCT 'COM001', 'John',
case when date = '01-Jan-4501 00:00:00' then convert(date,getdate()) end
Is there a way to use the Now() function in SQL to select values with today's date?
I was under the impression Now() would contain the time as well as date, but today's date would have the time set to 00:00:00 and therefore this would never match?
OK, lets do this properly. Select dates matching today, using indexes if available, with all the different date/time types present.
The principle here is the same in each case. We grab rows where the date column is on or after the most recent midnight (today's date with time 00:00:00), and before the next midnight (tomorrow's date with time 00:00:00, but excluding anything with that exact value).
For pure date types, we can do a simple comparison with today's date.
To keep things nice and fast, we're explicitly avoiding doing any manipulation on the dates stored in the DB (the LHS of the where clause in all the examples below). This would potentially trigger a full table scan as the date would have to be computed for every comparison. (This behaviour appears to vary by DBMS, YMMV).
MS SQL Server: (SQL Fiddle | db<>fiddle)
First, using DATE
select * from dates
where dte = CAST(CURRENT_TIMESTAMP AS DATE)
;
Now with DATETIME:
select * from datetimes
where dtm >= CAST(CURRENT_TIMESTAMP AS DATE)
and dtm < DATEADD(DD, 1, CAST(CURRENT_TIMESTAMP AS DATE))
;
Lastly with DATETIME2:
select * from datetimes2
where dtm2 >= CAST(CURRENT_TIMESTAMP AS DATE)
and dtm2 < DATEADD(DD, 1, CAST(CURRENT_TIMESTAMP AS DATE))
;
MySQL: (SQL Fiddle | db<>fiddle)
Using DATE:
select * from dates
where dte = cast(now() as date)
;
Using DATETIME:
select * from datetimes
where dtm >= cast((now()) as date)
and dtm < cast((now() + interval 1 day) as date)
;
PostgreSQL: (SQL Fiddle | db<>fiddle)
Using DATE:
select * from dates
where dte = current_date
;
Using TIMESTAMP WITHOUT TIME ZONE:
select * from timestamps
where ts >= 'today'
and ts < 'tomorrow'
;
Oracle: (SQL Fiddle)
Using DATE:
select to_char(dte, 'YYYY-MM-DD HH24:MI:SS') dte
from dates
where dte >= trunc(current_date)
and dte < trunc(current_date) + 1
;
Using TIMESTAMP:
select to_char(ts, 'YYYY-MM-DD HH24:MI:SS') ts
from timestamps
where ts >= trunc(current_date)
and ts < trunc(current_date) + 1
;
SQLite: (SQL Fiddle)
Using date strings:
select * from dates
where dte = (select date('now'))
;
Using date and time strings:
select dtm from datetimes
where dtm >= datetime(date('now'))
and dtm < datetime(date('now', '+1 day'))
;
Using unix timestamps:
select datetime(dtm, 'unixepoch', 'localtime') from datetimes
where dtm >= strftime('%s', date('now'))
and dtm < strftime('%s', date('now', '+1 day'))
;
Backup of SQL Fiddle code
There is no native Now() function in SQL Server so you should use:
select GETDATE() --2012-05-01 10:14:13.403
you can get day, month and year separately by doing:
select DAY(getdate()) --1
select month(getdate()) --5
select year(getdate()) --2012
if you are on sql server 2008, there is the DATE date time which has only the date part, not the time:
select cast (GETDATE() as DATE) --2012-05-01
Not sure what your asking!
However
SELECT GETDATE()
Will get you the current date and time
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
Will get you just the date with time set to 00:00:00
Just zero off the time element of the date. e.g.
SELECT DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
I've used GetDate as that's an MSSQL function, as you've tagged, but Now() is probably MySQL or you're using the ODBC function call, still should work if you just replace one with the other.
Not sure exactly what you're trying to do, but it sounds like GETDATE() is what you're after. GETDATE() returns a datetime, but if you're not interested in the time component then you can cast to a date.
SELECT GETDATE()
SELECT CAST(GETDATE() AS DATE)
Building on the previous answers, please note an important point, you also need to manipulate your table column to ensure it does not contain the time fragment of the datetime datatype.
Below is a small sample script demonstrating the above:
select getdate()
--2012-05-01 12:06:51.413
select cast(getdate() as date)
--2012-05-01
--we're using sysobjects for the example
create table test (id int)
select * from sysobjects where cast(crdate as date) = cast(getdate() as date)
--resultset contains only objects created today
drop table test
I hope this helps.
EDIT:
Following #dwurf comment (thanks) about the effect the above example may have on performance, I would like to suggest the following instead.
We create a date range between today at midnight (start of day) and the last millisecond of the day (SQL server count up to .997, that's why I'm reducing 3 milliseconds). In this manner we avoid manipulating the left side and avoid the performance impact.
select getdate()
--2012-05-01 12:06:51.413
select dateadd(millisecond, -3, cast(cast(getdate()+1 as date) as datetime))
--2012-05-01 23:59:59.997
select cast(getdate() as date)
--2012-05-01
create table test (id int)
select * from sysobjects where crdate between cast(getdate() as date) and dateadd(millisecond, -3, cast(cast(getdate()+1 as date) as datetime))
--resultset contains only objects created today
drop table test
If you have a table with just a stored date (no time) and want to get those by "now", then you can do this:
SELECT * FROM tbl WHERE DATEDIFF(d, yourdate, GETDATE())=0
This results in rows which day difference is 0 (so today).
For me the query that is working, if I want to compare with DrawDate for example is:
CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)
This is comparing results with today's date.
or the whole query:
SELECT TOP (1000) *
FROM test
where DrawName != 'NULL' and CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)
order by id desc
You can try this sql code;
SELECT [column_1], [column_1], ...
FROM (your_table)
where date_format(record_date, '%e%c%Y') = date_format(now(), '%e%c%Y')
You can try:
WHERE created_date BETWEEN CURRENT_TIMESTAMP-180 AND CURRENT_TIMESTAMP
This worked for me:
SELECT * FROM table where date(column_date) = curdate()
I have a question. I have a SQL Server 2008 table with a field column. I have for example the Following dates:
1/1/2001
5/5/2004
8/5/2009
10/7/2011
5/5/2012
1/13/2014
Id like to be able to show all dates >= the current date (7/29/2011) as well as largest table date that is < current date. In this example, the result would be all dates >= 8/5/2009.
Can someone help guide me please??
select max(date) [date] from table where date < getdate()
union
select date from table where date >= getdate()
If I understand correctly, you want to include the date prior to the current date. GETDATE() will get the current date (with time). If you're alright with that, then this should work. Otherwise, you may have to parse out just the date from GETDATE()
SELECT TheDate
FROM DateTable
WHERE TheDate >= (SELECT MAX(TheDate) FROM DateTable WHERE TheDate < GETDATE())
This gets all dates greater than or equal to the most recent date before the current date.
I am not entirely sure I understand, but this looks like a BETWEEN the relevant dates. Or is there something more I am missing?
Assuming your table is called DateTable and your field is called TheDate, do it like this:
SELECT TheDate
FROM DateTable
WHERE TheDate >= DATEADD(d, -2, GETDATE())
Good luck!
It depends on the SQL server you're using. In postgres, for example, you need something like
SELECT fields FROM table WHERE date_field >= CURRENT_DATE - 1
But other SQL servers have different ways to specify "yesterday"
SELECT d1.*
FROM dates d1
LEFT JOIN dates d2 ON d1.Date < d2.Date AND d2.Date < GETDATE()
WHERE d2.Date IS NULL
Explanation:
Select every date for which there does not exist a date that is both earlier than today and later than the one being inspected.
Lots of guessing here based on loose narrative and unknown data types.
DECLARE #t TABLE(d DATE);
INSERT #t SELECT '20010101'
UNION ALL SELECT '20040505'
UNION ALL SELECT '20090805'
UNION ALL SELECT '20111007'
UNION ALL SELECT '20120505'
UNION ALL SELECT '20140113';
DECLARE #now DATE = SYSDATETIME();
WITH t AS
(
SELECT d, rn = ROW_NUMBER() OVER (ORDER BY d)
FROM #t
)
SELECT t.d
FROM t LEFT OUTER JOIN t AS x
ON t.rn = x.rn - 1
WHERE COALESCE(x.d, #now) >= #now
ORDER BY t.d;
I'm working in project for by PHP and SQL Server.
The owner want from me design page show only users who register in same day
i.e., if today 11-3-2011 i want show only all users who register in 11-3-2011
The table is:
id username date
1 john 11\3\2011
2 sara 11\3\2011
3 john 5\1\2011
4 kreem 1\2\2011
i make it by mysql
where DATE_ADD( items.created_date, INTERVAL 1 DAY ) > NOW()
this cable of code show data which only insert in same day thats mean if today 10-4-2011 it will show only data which insert in 10-4-2011 if i today 15-4-2011 and im dose not insert any thing it will not show any thing, how i can build code like this in sql server? hope to be my question clear and understand
select id, userName
from YourTable
where CAST(date AS DATE) = CAST(GETDATE() AS DATE)
Function GETDATE() returns the current date and time.
CAST(column as TYPE) will threat DateTime as just Date to omit differences in Time
For getting today's date record:
select * from tablename where date column between '2011-10-25 00:00:00' And '2011-10-25 23:59:59'
select * from yourtable where date = CONVERT(VARCHAR(20),GETDATE(),101) // hope this will be helpful to get current date value..
This query compares only the date piece of today, ignoring the time. It works in MS SQL Server, I'm not sure about other implimentations:
select *
from YourTable
where convert(datetime, floor(convert(float, GETDATE()))) = [date]
select *
from YourTable
where
[date] >= '20110311' and
[date] < '20110312'
If you want it for today (always) you can use this
select *
from YourTable
where
[date] >= dateadd(d, datediff(d, 0, getdate()), 0) and
[date] < dateadd(d, datediff(d, 0, getdate())+1, 0)
Last 10 days.
select *
from YourTable
where
[date] >= dateadd(d, datediff(d, 0, getdate())-9, 0)
Edit 1 Query with sample data and result
Table definition
create table users
(name varchar(20),
user_register_date datetime)
Data
insert into users values ('user today', getdate())
insert into users values ('user yesterday', getdate()-1)
insert into users values ('user 9 days ago', getdate()-9)
insert into users values ('user 10 days ago', getdate()-10)
Query
select *
from users
where user_register_date >= dateadd(d, datediff(d, 0, getdate())-9, 0)
Result
name user_register_date
-------------------- -----------------------
user today 2011-04-14 08:29:28.407
user yesterday 2011-04-13 08:29:28.410
user 9 days ago 2011-04-05 08:29:28.410
SELECT * from YourTable
WHERE cast(convert(varchar(10),yourdate,101) as datetime) =
cast(convert(varchar(10),[any day you want],101) as datetime)
Hope this helps. Just replace [any day you want] with a date or datetime value
The CAST function is equivalent to the CONVERT function, except convert allows for some formatting options. In my example, I simply trimmed off the time from the date.