I have this code that runs a query in PostgreSQL:
SELECT planned,COUNT(*) AS results
FROM dashboard.event
WHERE event_start_adj::TIMESTAMP::DATE = '2020-04-05'
GROUP BY planned
This code actually works but the problem is when i insert this to Java Spring like this:
it gives me an error like this:
org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
Position: 80
I've tried removing it to event_start_adj = But it returns nothing since the data of my event_start_adj in PostgreSQL is timestamp without time zone That's why the query above extracts the date first. How can I fix this?
Obfuscation layers like JPA can't properly handle the :: operator, you need to rewrite it to use the CAST() operator instead:
WHERE cast(cast(event_start_adj as TIMESTAMP) as DATE) = '2020-04-05'
However if event_start_adj is already a timestamp the first case is useless, so it seems the following should be enough:
WHERE cast(event_start_adj as DATE) = '2020-04-05'
Unrelated to the problem at hand, but the expression you are using can't make use of an index on event_start_adj. So from a performance point of view, not casting at all would be better, but then you need to change the query to:
WHERE event_start_adj => date '2020-04-05'
AND event_start_adj < date '2020-04-06'
WHERE timestamp_column::::DATE = '2020-04-05'
The above worked for me in springboot native query.
Related
I have an insert statement, where one of the inserted fields is date. I use to_date function to convert string to date in this way:
to_date('10-MAY-10', 'DD-MON-RR')
It works fine, but I found, that it allows also variants like:
to_date('10?MAY?10', 'DD-MON-RR')
to_date('10+MAY+10', 'DD-MON-RR')
I'm expecting an Oracle error, however it makes an insert. Could you please explain why or give a reference to relevant documentation?
Oracle will test for other formats if it fails to find a match in the string - you can see the rules for what it looks for here in the documentation.
As an aside, years have four digits. Please make sure you specify all four when you provide a date-as-a-string, where possible; it saves the database from having to guess and potentially getting it wrong. I.e. your original example should be:
to_date('10-05-2010', 'DD-MM-YYYY')
If you need to restrict the date-as-a-string to a specific format, you can use the fx format modifier, which is mentioned earlier in the same document I linked to previously.
eg. to_date('10/05/2010', 'dd-mm-yyyy') would match but to_date('10/05/2010', 'fxdd-mm-yyyy') would fail
My query that I put into a prepared statement is:
select *
from ( select seq, audit_ts, message_type
from log2
where 1 = 1
and message_type in ('SOURCE', 'DEST')
order by seq desc )
where ROWNUM <= ?
When I run the query in my application, I get:
java.sql.SQLSyntaxErrorException: ORA-00907: missing right parenthesis
EDIT: Here is the java executing the query. I am trying to return a set of search results, so the prefix contains the SELECT statement and then I can have any number of suffixes (in this excerpt "AUDIT_LOG_SEARCH2") which are the parameterized WHERE clauses based on the user search:
StringBuffer query = new StringBuffer(300);
query.append(dbAdapter.getQuery("AUDIT_LOG_ENTRY_PREFIX"));
query.append(dbAdapter.getQuery("AUDIT_LOG_SEARCH2"));
// Insert parameters to complete the sql prepared statement
PreparedStatement ps = _dbConn.prepareStatement(query.toString());
ResultSet rs = ps.executeQuery();
But the query runs fine when I run it separately in SQL Developer. The query was originally created for Postgres, then updated for Oracle. Any tips?
You need to set the variables into the preparedStatement before executing.
PreparedStatement ps = _dbConn.prepareStatement(query.toString());
ps.setInt(1, 10);
Please post what query.toString() gives you if that doesn't work. Not query, but query.toString()
What are you doing in your:
// Insert parameters to complete the sql prepared statement
Are you using correctly the methods ps.setString... or whatever? Or are you just replacing the question marks? the second might be corrupting your query.
Based on #AlexPoole and #EdGibbs comments, I decided to add a bunch more debug statements. It turns out the method was being recursively called with a different sql "suffix" later on in the program if certain conditions were met. The suffix was not updated with the necessary parenthesis for the new ROWNUM wrapping the statement. So although the ORA-00907 can be thrown for many different formatting problems, it was in fact a right parenthesis that was causing me problems :P
The prefix and suffix seems like a weird pattern in this code base for creating sql queries. I'm thinking of getting rid of this and refactoring so queries don't have to be built like that. Any advice??
So for anyone else who runs into this Oracle error, I would suggest logging the sql statement you are generating and play around with it in SQL Developer. If it works in there, but not in your application, your code is probably doing something funky :P
Have a named query written like this
select u from User u where u.creationdate < DATE_SUB(CURDATE(),INTERVAL :upperDate DAY) and status=:status and reminder_counter =:counter
But I get a Syntax error parsing.
Any ideas`?
P
The function DATE_SUB you are using is MySQL specific, resulting in parsing error.
Create a named native query to use DATE_SUB function.
Else, can calculate the duration explicitly & then setting the parameter.
Im new with JDBC, and while executing some query i get a result that is inconsistent.
If i execute this query in sql developer (connected to a Oracle DB) i get 4 results
SELECT *
FROM someTable1 some1
JOIN someTable2 some2 on (some1.some_id= some2.other_id)
WHERE some2.some_date LIKE '01/01/01' OR some2.some_date IS NULL
Then, i load this same query from a properties file in java and execute the query and get 0 results... anyone know why this is happening? I first suspect of the single quotes in the propertie value but i dont know...
Thanks in advance and excuse my poor english! :)
The query doesn't contain any special characters which could confuse Java, the properties loader or JDBC, so you should get exactly the same results in SQL Developer and with JDBC.
In fact, SQL Developer is written in Java, so it is using JDBC to execute the queries.
Print the query to the console before you execute it to make 100% sure the code executes the query that you have in mind.
Next, you should check the type of some_date. LIKE is only defined for string types (VARCHAR and similar), not for date/time types.
Oracle has a set of helper functions to build queries for date/time types, for example:
some_date = to_date( '01/01/2001','mm/dd/yyyy')
or
TRUNC(some_date, 'DAY') = to_date( '01/01/2001','mm/dd/yyyy')
The second query strips hours, minutes, seconds, etc. from the column and will compare only days, months and years.
Note: Always use 4-digit years to avoid all kinds of odd problems.
I'm working on a report in iReport 2.0.4 connecting to an Oracle database through oracle.jdbc.driver.OracleDriver that returns a list of entries based on union membership. The report takes a start date, end date, and union name as parameters. The basic structure of the query is
select
...
from
...
where
union_opt_in_dt <= $P{EndDate} and
union_opt_out_dt >= $P{StartDate} and
union_name = $P{UnionName}
...
where StartDate and EndDate have type java.lang.Date and UnionName has type java.lang.String.
The problem is that, if I use the UnionName parameter and pass in the union name (example "AFSCME"), the query returns no data. If I remove the UnionName parameter and hardcode the union name, as in
where
union_opt_in_dt <= $P{EndDate} and
union_opt_out_dt >= $P{StartDate} and
union_name = 'AFSCME'
then I get the rows I expect for that union name.
So why do the date parameters work, but not the string parameter? Is there a method I need to call on the string parameter (such as .trim()) to get it to work?
UPDATE, FIXED
Found an answer to a different question on another forum that fixes it; I have to do an immediate substitution (terminology?) of the parameter in the query, so it needs to be
where
union_opt_in_dt <= $P{EndDate} and
union_opt_out_dt >= $P{StartDate} and
union_name = '$P!{UnionName}'
That works. Not sure I understand the logic of it (as of a week and a half ago I'd never heard of Jasper Reports), but at least I can move forward.
UPDATED UPDATE, NOT FIXED
Okay, so the above solution isn't quite what I need; it only substitutes the default value, not necessarily what's passed in. Argh.
Why do the dates work, but not the union name? I've made sure that the value in the parameter exactly matches what's in the database, character for character.
Try trimming the UnionName before passing.