Search Query for Oracle SQL APEX - oracle

I am trying to create an advance search query using oracle SQL in Oracle APEX class report.
Is there a way to insert the query line into the query when there are values in the parameter?
For example, I have a query like so:
select person_id, fullname from person where first_name like '%:P11_FNAME%' AND last_name like '%:P11_LNAME%'
is there a way to add the first_name like '%:P11_FNAME%' into the query when there are actual values being passed in?

Bind variable syntax will not be recognised by the SQL engine if it is embedded within a string literal like '%:P11_FNAME%'.
You need to use string concatenation to do what you wanted:
select person_id, fullname from person
where first_name like '%' || :P11_FNAME || '%'
AND last_name like '%' || :P11_LNAME || '%';
If the user leaves search criteria blank, this will match all rows except those that have a NULL for the name. To make a blank search criterion match all rows, you need to add extra predicates, e.g.:
select person_id, fullname from person
where (first_name like '%' || :P11_FNAME || '%' or :P11_FNAME is null)
AND (last_name like '%' || :P11_LNAME || '%' or :P11_LNAME is null);

Related

How to use REGEXP_SUBSTR to filter?

I have a select query which is working in postgres , but not in Oracle
The Select Query Uses regexp_split_to_array , which is not suppourted in Oracle
The regexp_split_to_array used here is to filter non working days
select
*
from
department
where
dept_status = 'A'
AND NOT (
#{DAY} = any ( regexp_split_to_array(lower(non_working_days), ',')))
AND dept_loc = 'US'
http://sqlfiddle.com/#!4/fbac4/4
Oracle does not have a function regexp_split_to_array . Instead you can use LIKE (which is much faster than regular expressions) to check for a sub-string match (including the surrounding delimiters so you match a complete term):
SELECT *
FROM department
WHERE dept_status = 'A'
AND ',' || lower(non_working_days) || ',' NOT LIKE '%,' || :DAY || ',%'
AND dept_loc = 'US'
Note: You should pass in variables using bind variables such as :day or ? (for an anonymous bind variable) rather than relying on a pre-processor to replace strings as it will help to prevent SQL injection attacks.
fiddle

Reverse SQL like not working in Oracle 12c

I need to do a reverse like query in Oracle 12c. While it works fine with H2, it fails in Oracle12c.
Table:
CREATE TABLE t
("id" int, "code" varchar(100))
;
INSERT ALL
INTO t ("id", "code")
VALUES (1, 'london')
INTO t ("id", "code")
VALUES (2, 'amsterdam')
INTO t ("id", "code")
VALUES (3, 'Oslo')
INTO t ("id", "code")
VALUES (4, 'Brussels')
SELECT * FROM dual
;
Query:
select * from t where 'london south' like concat('%',code, '%');
It gives error: ORA-00909: invalid number of arguments
How should i query it get (1, london) as the result?
Do NOT use double quotes around lower case column names in your DDL unless you really want to force Oracle to store the column names in lower case, which also means you need to use double quotes in your query:
select * from t where 'london south' like '%'||"code"||'%' ;
got the value london as the single row of output.
Why use the concat function when using || is more flexible?
Here you are a simpler test case:
select concat('a', 'b', 'c')
from dual;
ORA-00909: invalid number of arguments
The CONCAT() function expects exactly two arguments. You'll have to nest several calls or use the || operator.
select *
from t
where 'london south' like '%' || code || '%';

how to get the '' for each string in a listagg?

I have the following query :
SELECT
ix.dt AS DT,
ix.UDBENCH_UDIDX AS UDFO,
' .' || REPLACE(REPLACE( ix.UDBENCH_UDIDX,' ',''),'IS','') AS PF_TICKER,
i.szbez AS PORTFOLIO_NAME,
ix.rm_generic_inst_type_l1,
ix.rm_generic_inst_type_l2,
ix.scd_sec_type,
m.ud_isin AS SECURITY_ID,
'%' AS POS_TYPE,
ix.sec_weight AS QUANTITY,
ix.sec_ccy,
ix.sec_price AS MKT_PRICE,
'' AS COST_PX,
'' AS POSITION_VALUE_AC,
'' AS POSITION_VALUE_FC,
m.ud_sedol AS UD_SEDOL,
m.ud_bbgid AS UD_ID_BB_UNIQUE,
m.ud_cusip AS UD_CUSIP,
m.ud_bbgid AS UD_BBGID,
m.inst_name AS INST_NAME,
ix.idas AS IDAS,
m.ud_scd_securityid AS UD_SCD_SECURITYID
FROM XXXX ix
INNER JOIN XXXXR i ON (i.udidx = ix.UDBENCH_UDIDX),
XXXXX m
WHERE ix.dt >= to_date(sdt_start,'DD.MM.YYYY')
AND ix.dt <= to_date(sdt_end,'DD.MM.YYYY')
AND ix.UDBENCH_UDIDX IN (select listagg( udfo,',') within group(ORDER BY udfo)
from XXXXX where pf_ticker is null )
AND i.szbez LIKE '%DFLT%'
AND ix.idas = m.idas;
I would like the part :
AND ix.UDBENCH_UDIDX IN (select listagg( udfo,',') within group(ORDER
BY udfo)
from XXXXX where pf_ticker is null )
Equivalent to : ix.UDBENCH_UDIDX IN ('blal','bll',blc') but it shows ix.UDBENCH_UDIDX IN (blal,bll,blc) and the result of my query is an empty table, do you know how to set listagg to have this result ( 'blal','bll',blc' instead of blal,bll,blc)?
Thanks
The IN operator doesn't work like that. You'd be comparing the UDBENCH_UDIDX values with a single string containing all udfo values, not all of the individual values of that column.
You can just use a subquery without the listagg():
AND ix.UDBENCH_UDIDX IN (select udfo from XXXXX where pf_ticker is null)
Or you can join to that table instead of using a subquery at all; something like:
FROM XXXX ix
INNER JOIN XXXXR i ON (i.udidx = ix.UDBENCH_UDIDX)
INNER JOIN XXXXX m ON (m.udfo = ix.UDBENCH_UDIDX)
WHERE ix.dt >= to_date(sdt_start,'DD.MM.YYYY')
AND ix.dt <= to_date(sdt_end,'DD.MM.YYYY')
AND i.szbez LIKE '%DFLT%'
AND ix.idas = m.idas
AND m.pf_ticker is null;
... assuming the old-style join to XXXXX m is supposed to be getting the data related to the subquery you're doing - it's hard to tell with obfuscated names. (It's not a good idea to mix old and new style joins anyway; or to use old-style joins at all). It's possible you might want that to be an outer join, or the driving table, or something else - again can't infer that from the information provided.
If you already had a set of string literals to look for then you would do something like:
IN ('val1', 'val2', 'val3')
but you don't have string literals, you have string values from a table, which are not the same. You don't need to, and shouldn't, enclose those column values in single quotes within the query. The single quotes denote a literal value which is to be treated as a string; the values in the column are already strings.
You can actually do what you asked:
select '''' || listagg(udfo, ''',''') within group (order by udfo) || '''' from ...
which would give you a comma-separated list of quoted values from your table (or an empty string, which is the same as null, if there are no matching rows. If you were generating a statement to run later then that might make some sense, but that isn't the case here.

Spring JPA #Query where clause with 'like' and 'or'

I have the following query:
#Query("select c from Category c where ( (lower(c.name) like '%' || lower(:searchText) || '%') or (lower(c.description) like '%' || lower(:searchText)) || '%')")
My product is designed to run in multiple platform, I am getting an error on postgreSQL which is:
PSQLException: ERROR: argument of OR must be type boolean, not type
text.
Which is undestandable since the like clause return strings. But I wasn't able to perform the search in one query request. So the question is how can I perform a search where the where conditions refer to 2 differnt columns and use the 'like' operator.
The parentheses you have are not correct the following should work:
#Query("select c from Category c " +
"where (lower(c.name) like ('%' || lower(:searchText) || '%')) " +
" or (lower(c.description) like ('%' || lower(:searchText) || '%'))")

Oracle nvl in where clause showing strange results?

I have a web form that allows users to search on and edit records from an Oracle table based on parameters passed in to a proc. Here's my data:
CAE_SEC_ID SEC_CODE APPR_STATUS
1 ABC1 100
2 ABC2 100
3 ABC3 101
4 (null) 101
5 (null) 102
6 ABC4 103
And here's the where clause:
select foo
from bar
where CAE_SEC_ID = NVL(p_cae_sec_id,CAE_SEC_ID)
and Upper(SEC_CODE) like '%' || Upper(NVL(p_sec_code,SEC_CODE)) || '%'
and APPR_STATUS = NVL(p_appr_status, APPR_STATUS)
Using nvl on the parameters should return only the matched records if any of the parameters have values, and all records if none of the parameters have values. All pretty standard or so I thought. However when I do a search without any parameter values the query isn't returning records with a null SEC_CODE i.e. only records 1, 2, 3, and 6 are being returned. Shouldn't the where clause above include records with null SEC_CODE values?
The problem is that the SEC_CODE value in the table is NULL. That means that UPPER(sec_code) is NULL and your second predicate simplifies to
and NULL LIKE '%%'
Just like NULL is not equal to anything and not unequal to anything, it is not like anything. Most likely, you want something like
and (Upper(SEC_CODE) like '%' || Upper(NVL(p_sec_code,SEC_CODE)) || '%' or
(sec_code is null and p_sec_code is null))
That will return every row if P_SEC_CODE is NULL but still apply the filter if P_SEC_CODE is non-NULL.
No it shouldn't.
The SEC_CODE in the database is null, so the UPPER(SEC_CODE) is null and so it will fail on a LIKE match or pretty much any other comparison beyond IS NULL. Technically it is a UNKNOWN rather than a FALSE but is isn't enough to pass the test.
The expression NULL = NULL evaluates to NULL, which is not true and so these rows won't be returned. If I understand the requirement correctly, you only want to filter if a parameter is different from null, so I would rewrite the query like this to make the filter more explicit:
select foo from bar
where (p_cae_sec_id is null or CAE_SEC_ID = p_cae_sec_id)
and (p_sec_code is null or Upper(SEC_CODE) like '%' || Upper(p_sec_code) || '%')
and (p_appr_status is null or APPR_STATUS = p_appr_status)
Setting the p_sec_code parameter to null will now return all rows, ignoring the value in the SEC_CODE column.
We can also write the Jorn's query like
select foo from bar
where (CASE WHEN p_cae_sec_id is null THEN 'Y'
WHEN CAE_SEC_ID = p_cae_sec_id THEN 'Y'
ELSE 'N'
END)='Y'
and (CASE WHEN p_sec_code is null THEN 'Y'
WHEN Upper(SEC_CODE) like '%' || Upper(p_sec_code) || '%' THEN 'Y'
ELSE 'N'
END)='Y'
and (CASE WHEN p_appr_status is null THEN 'Y'
WHEN APPR_STATUS = p_appr_status THEN 'Y'
ELSE 'N'
END)='Y'
to make it concrete and increase the performance .

Resources