I want to filter the date range from April 1 to April 22, but only between 8:00 PM and 6:00 AM - the rest of the hours that are not in this range should be excluded. Do you have any ideas on how to do that? The only thing I have done so far is the date range but I don't know how to handle it next:
select * from cdm_service_request_logs
where inserted_at >= '20/04/01 20:00:00%'
and inserted_at < '20/04/22 06:00:00%'
ORDER BY ID DESC;
I think you want something like this:
select srl.*
from cdm_service_request_logs srl
where inserted_at >= date '2020-04-01' and
inserted_at < date '2020-04-022' and
extract(hour from inserted_at) not between 6 and 19;
In Oracle, the time comparison would often use strings:
where inserted_at >= date '2020-04-01' and
inserted_at < date '2020-04-022' and
(to_char(inserted_at, 'HH24:MI') >= '20:00' or
to_char(inserted_at, 'HH24:MI') < '06:00'
)
Note that the date comparison uses date constant values. This is correct. The % is not valid for a date, so your comparisons are as strings. I can only speculate that you are confusing like patterns with date constants. If so, that is just misguided.
I wanted to get yesterday date from my Date column,
My logic is
SELECT MY_DATE,NAME,MONEY FROM MY_TABLE
WHERE MY_DATE-1
My records looks like this
MYDATE NAME MONEY
10/31/2019 BILLY 2000
11/1/2019 BILLY 3000
If today is 11/1/2019, i wanted to get the records on 10/31/2019.
The output of the select i wanted is
MYDATE NAME MONEY
10/31/2019 BILLY 2000
Since you want yesterday's date, I don't understand why you don't want to use SYSDATE.
Otherwise, it's quite easy:
WHERE my_date = TRUNC(SYSDATE-1);
In Oracle a DATE data type always has year, month, day, hour, minute and second components. Your user interface may not show the time components but they still exist.
If your time components are guaranteed to always be set to midnight then you can use:
SELECT MY_DATE,
NAME,
MONEY
FROM MY_TABLE
WHERE MY_DATE = TRUNC( SYSDATE ) - 1;
If you have non-midnight time values in the MY_DATE column then above method will not work and, instead, the best method is to compare on a range of values (since this allows Oracle to use an index on your column):
SELECT MY_DATE,
NAME,
MONEY
FROM MY_TABLE
WHERE MY_DATE >= TRUNC( SYSDATE ) - 1
AND MY_DATE < TRUNC( SYSDATE );
You could also truncate both sides of the comparison (however, Oracle would not use an index on the column and would need a separate function-based index):
SELECT MY_DATE,
NAME,
MONEY
FROM MY_TABLE
WHERE TRUNC( MY_DATE ) = TRUNC( SYSDATE ) - 1;
I am trying to select a specific time range on a specific days range in SQL postgres. PLease see the code below which gives an error on the '10:00:00'.
The type of data for each columns is :
numeric for "balance",
character varying(255) for "currency",
timestamp without time zone for "created_at" (ex: 2018-03-20 00:00:00).
I tried this link without success.
MySQL select based on daily timestamp range
SELECT SUM(bl.balance) AS balance, bl.currency, bl.created_at
FROM balance_logs bl
WHERE bl.balance_scope = 'system' AND
created_at >= CURRENT_DATE - 2 AND
created_at < CURRENT_DATE AND
created_at BETWEEN '10:00:00' AND '11:00:00'
GROUP BY bl.currency, bl.created_at
ORDER BY created_at DESC
The comparison needs to be as a time:
SELECT SUM(bl.balance) AS balance, bl.currency, bl.created_at
FROM balance_logs bl
WHERE bl.balance_scope = 'system' AND
created_at >= CURRENT_DATE - 2 AND
created_at < CURRENT_DATE AND
created_at::time BETWEEN '10:00:00'::time AND '11:00:00'::time
GROUP BY bl.currency, bl.created_at
ORDER BY created_at DESC;
However, I think it is better to write the WHERE condition as:
extract(hour from created_at) = 10
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 want to be able to select all database rows where the month and year are the same as what I am searching for. Since the DATE field has year, month, and day, how do I search with year and month?
SELECT *
FROM tblTableName
WHERE Month(ColumnDate) = Month(MyDate)
AND Year(ColumnDate) = Year(MyDate)
SELECT *
FROM myTable
WHERE ( YEAR(myfield) = '2009')
AND ( MONTH(myfield) = '1')
The most efficient is to create the start and end date of the range that you want, so that you compare the dates as a single value instead of extracting the year and month properties from each date.
Example:
select SomeField
from SomeTable
where SomeDate >= ? and SomeDate < ?
(Note that the first comparison is inclusive and the seond is exclusive.)
Create the start and end date to use as parameters: (example in C#)
DateTime start = new DateTime(date.Year, date.Month, 1)
DateTIme end = start.AddMonths(1);
In MySQL:
SELECT *
FROM mytable
WHERE date >= STR_TO_DATE(CONCAT(EXTRACT(YEAR_MONTH FROM #mydate), '01'), '%Y%m%d')
AND date < STR_TO_DATE(CONCAT(EXTRACT(YEAR_MONTH FROM #mydate), '01'), '%Y%m%d') + INTERVAL 1 MONTH
This will efficiently use an index on the date field.
That would depend on what database backend you are using. IN SQl Server I would use
where year(datefield) = #year and month (datefield) - #month
to do this.
or you could build a where clause by creating a date range
where datefield between 20090101 and 20090201
You will want to use MONTH() and YEAR() in mysql.