Syntax for Combining BETWEEN and LIKE - postgresql

I have a syntax, but it doesn't work.
Here is my query:
SELECT *
FROM aqua.reading
WHERE
CAST(reading.pres_date AS VARCHAR)
BETWEEN LIKE '2022-10-18%' AND LIKE '2022-10-18%'
it says:
ERROR: type "like" does not exist
LINE 1: ... WHERE CAST(reading.pres_date AS VARCHAR) BETWEEN LIKE '2022...
^
SQL state: 42704
Character: 77
I am trying to get all the data with timestamp and timezone and implement a date range

Don't compare dates (or timestamps) as strings. Compare them to proper date (or timestamp) values. Given the fact that you use the same "date" but with a wildcard at the end, I am assuming(!) that pres_date is in fact a timestamp column and you want to find all rows with a given date regardless of the time value of the timestamp.
The best approach is to use a range query with >= ("greater than or equal) on the lower value and < (strictly lower than) on the next day:
SELECT *
FROM aqua.reading
WHERE reading.pres_date >= DATE '2022-10-18'
AND reading.pres_date < DATE '2022-10-19'
Alternatively you can cast the timestamp to a date and use the = operator if you really want to pick just one day:
SELECT *
FROM aqua.reading
WHERE cast(reading.pres_date as DATE) = DATE '2022-10-18'
However that will not make use of a potential index on pres_date so is likely to be slower than the range query from the first solution

Related

Add to DATE hour - TSQL

I have a column type time(7).
What i want is to add in time column to date.
i manage to get the only date using GETDATE() function but i fail to add the time part next to date.
Query:
SELECT [Compay]
,[Time]
,CAST(GETDATE() AS DATE) AS Today
,CAST(CAST(GETDATE() AS DATE) AS NVARCHAR) AS Today_AS_Nvarchar
,CAST([Time] AS NVARCHAR) AS Time_AS_Nvarchar
,CAST(CAST(GETDATE() AS DATE) AS NVARCHAR) + ' ' + CAST([Time] AS NVARCHAR) AS Today_Time_AS_Nvarchar
,CONVERT(datetime,CAST(CAST(GETDATE() AS DATE) AS NVARCHAR) + ' ' + CAST([Time] AS NVARCHAR),103)
FROM [Testing_Env].[dbo].[Com_CD_Test]
Error:
Conversion failed when converting date and/or time from character string.
The error arise on CONVERT(datetime,CAST(CAST(GETDATE() AS DATE) AS NVARCHAR) + ' ' + CAST([Time] AS NVARCHAR),103)
is there any easier/orthodox way to achieve it?
You can't add the new date and time data types together like you can the old data types; personally I think this is also better as it stop people treating dates and times like a numerical value.
Assuming you have a date column and a time column you have a few of options. The first is to CAST/CONVERT both to a datetime and then "add" them together. Because the "old" data types work more like numerical values this works, however, you will lose accuracy of your time value if it has a precision of 3 or higher (as datetime is only accurate to 1/300 seconds):
DECLARE #TimeValue time(7) = '17:52:12.1234567',
#DateValue date = '20211016';
SELECT CONVERT(datetime, #DateValue) + CONVERT(datetime, #TimeValue);
If loosing accuracy isn't an option, then you could to use conversion on the date value and use DATEDIFF and DATEADD. For a time(7) you'll want to be using nanoseconds (as microseconds isn't accurate enough). Unfortunately this poses another problem; DATEADD can't handle bigint values (still) and there is no DATEADD_BIG (like there is DATEDIFF_BIG), so this becomes overly complex. You need to first get the difference in milliseconds, and then add the remainder in nanoseconds to still be accurate to 1/1000000 of a second:
DECLARE #TimeValue time(7) = '17:52:12.1234567',
#DateValue date = '20211016';
SELECT DATEADD(NANOSECOND,DATEDIFF_BIG(NANOSECOND,'00:00:00', #TimeValue) % 1000000,DATEADD(MILLISECOND, DATEDIFF_BIG(MILLISECOND,'00:00:00', #TimeValue), CONVERT(datetime2(7),#DateValue)));
Finally, yes, you can convert to values to strings, and then to a datetime2 value; this is probably the easiest methiod. You just need to ensure you use style codes:
DECLARE #TimeValue time(7) = '17:52:12.1234567',
#DateValue date = '20211016';
SELECT CONVERT(datetime2(7),CONVERT(varchar(10), #DateValue, 23) + 'T' + CONVERT(varchar(17), #TimeValue, 114),126);

MySQL query show the result out of range

I have the following mysqli query in my search.php file with ajax.
SELECT demand2.* FROM demand2
WHERE ddate >= '$dto' AND ddate >= '$dfrom' AND !(mach='--' OR mach='-' OR mach='' OR mach='----' OR mach='-----' OR mach='---');
field ddate is datatype of varchar2
as I entered Date From 01-01-2019 and Date To 30-01-2019, it shows the result with previous date like 29-12-2019.
So I can't find the solution to get result within specified range. Please Help.
Just as rypskar said, your type of field should be date.
If you don't want to change the datatype of the fiels, then you have to convert the string to date with STR_TO_DATE(ddate, '%d-%m-%Y'). But this is not recommended, as it will cause performance degradation on larger tables.
So your query would be like that (not tested!):
SELECT demand2.* FROM demand2
WHERE STR_TO_DATE(ddate, '%d-%m-%Y') >= STR_TO_DATE('$dto', '%d-%m-%Y') AND STR_TO_DATE(ddate, '%d-%m-%Y') >= STR_TO_DATE('$dfrom', '%d-%m-%Y') AND !(mach='--' OR mach='-' OR mach='' OR mach='----' OR mach='-----' OR mach='---');
If you want to keep the varchar type of field and not make any runtime conversions, then you have to change the format to Y-m-d, so the comparison with character set will work the same as a date comparison.
Right now, you are getting the result of 29-12-2019 because 29 is between 1 and 30.

Convert packed DB2 iseries value to YYYY-MM-DD

I'm trying to select records from a DB2 Iseries system where the date field is greater than the first of this year.
However, the date fields I'm selecting from are actually PACKED fields, not true dates.
I'm trying to convert them to YYYY-MM-DD format and get everything greater than '2018-01-01' but no matter what I try it says it's invalid.
Currently trying this:
SELECT *
FROM table1
WHERE val = 145
AND to_date(char(dateShp), 'YYYY-MM-DD') >= '2018-01-01';
it says expression not valid using format string specified.
Any ideas?
char(dateshp) is going to return a string like '20180319'
So your format string should not include the dashes.. 'YYYYMMDD'
example:
select to_date(char(20180101), 'YYYYMMDD')
from sysibm.sysdummy1;
So your code should be
SELECT *
FROM table1
WHERE val = 145
AND to_date(char(dateShp), 'YYYYMMDD') >= '2018-01-01';
Charles gave you a solution that converts the Packed date to a date field, and if you are comparing to another date field, this is a good solution. But if you are comparing to a constant value or another numeric field, you could just use something like this:
select *
from table1
where val = 145
and dateShp >= 20180101;

Converting date format in denodo database

I'm trying to convert value for DIM_DT_ID to MMddYY. I'm successful in doinf that. However, query fails because ultimately I'm comparing a character value to date here. Is there a way by which I can get value for DIM_DT_ID in MMddyy format and its data type still remains DATE ?
Here DIM_DT_ID
SELECT DIM_DT_ID
DIM_DT_ID >= FORMATDATE('MMddyy',ADDDAY(TO_date('yyyy-MM-dd','2016-12-21'), -25)); from abc;
Regards,
Ajay
In Denodo, to convert a string to a date field, use "to_date()" (which returns a date).
Then, don't convert back to a string, leave that field as a date (so don't use "Formatdate()", which returns a string).
So:
SELECT *
FROM MyTable
WHERE now() >= to_date('yyyy-MM-dd',myStringFieldThatLooksLikeADate)
In my example, "now()" is a date, and so is the output of the to_date function... so you can do a comparison.
If you try to convert the date back to a string using formatdate, it won't work:
#This doesn't work:
SELECT *
FROM MyTable
WHERE now() >= formatdate('MMddyy',to_date('yyyy-MM-dd',myStringFieldThatLooksLikeADate))
It doesn't work because we are comparing a date ("now()") to a string.

Postgresql Query very slow with ::date, ::time, and interval

I have a sql query that is very slow:
select number1 from mytable
where symbol = 25
and timeframe = 1
and date::date = '2008-02-05'
and date::time='10:40:00' + INTERVAL '30 minutes'
The goal is to return one value, and postgresql takes 1.7 seconds to return the desired value(always a single value). I need to execute hundreds of those queries for one task, so this gets extremely slow.
Executing the same query, but pointing to the time directly without using interval and ::date, ::time takes only 17ms:
select number1 from mytable
where symbol = 25
and timeframe = 1
and date = '2008-02-05 11:10:00'
I thought it would be faster if I would not use ::date and ::time, but when I execute a query like:
select number1 from mytable
where symbol = 25
and timeframe = 1
and date = '2008-02-05 10:40:00' + interval '30 minutes'
I get a sql error (22007). I've experimented with different variations but I couldn't get interval to work without using ::date and ::time. Date/Time Functions on postgresql.org didn't help me out.
The table got a multi column index on symbol, timeframe, date.
Is there a fast way to execute the query with adding time, or a working syntax with interval where I do not have to use ::date and ::time? Or do I need to have a special index when using queries like these?
Postgresql version is 9.2.
Edit:
The format of the table is:
date = timestamp with time zone,
symbol, timeframe = numeric.
Edit 2:
Using
select open from ohlc_dukascopy_bid
where symbol = 25
and timeframe = 1
and date = timestamp '2008-02-05 10:40:00' + interval '30' minute
Explain shows:
"Index Scan using mcbidindex on mytable (cost=0.00..116.03 rows=1 width=7)"
" Index Cond: ((symbol = 25) AND (timeframe = 1) AND (date = '2008-02-05 11:10:00'::timestamp without time zone))"
Time is now considerably faster: 86ms on first run.
The first version will not use a (regular) index on the column named date.
You didn't provide much information, but assuming the column named date has the datatype timestamp (and not date), then the following should work:
and date = timestamp '2008-02-05 10:40:00' + interval '30 minutes'
this should use an index on the column named date (but only if it is in fact a timestamp not a date). It is essentially the same as yours, the only difference is the explicit timestamp literal (although Postgres should understand '2008-02-05 10:40:00' as a timestamp literal as well).
You will need to run an explain to find out if it's using an index.
And please: change the name of that column. It's bad practise to use a reserved word as an identifier, and it's a really horrible name, which doesn't say anything about what kind of information is stored in the column. Is it the "start date", the "end date", the "due date", ...?