Query optimization and concatenation - sql

I'm running often this query and I would like to optimize it.
select
number || ' ' || name
from tasks
where upper(number || ' ' || name) like '%VALUE%'
I've created an index, but the it took the same time as without the index
create index name on tasks (upper(number || ' ' || name))
Are there any other options ?

You should consider using text indexes:
http://docs.oracle.com/cd/E11882_01/text.112/e24435/overview.htm#i1007403

If you're sure that the condition is selective enough to justify using an index then you might like to try promoting an index fast full scan with the following:
select /*+ INDEX_FFS(tasks your_index_name) */
number || ' ' || name
from tasks
where upper(number || ' ' || name) like '%VALUE%'
Edit:
I seem to recall that another way of promoting an IFFS is:
select number || ' ' || name
from tasks
where rowid in (
select rowid
from tasks
where upper(number || ' ' || name) like '%VALUE%')
Surprisingly barely less efficient that the former method.

Related

Conditionally concatenating fields in Oracle

What I need to do is to concatenate 4 fields in Oracle SQL Developer. The fields are:
Network, Network2, Network3, Network4
However, sometimes not all of the fields are filled in. This would always happen in sequence; it would never be just Network3 that's empty, it's either they fill in the first one only, the first 2 only, etc...
So, how can I write a Select statement that will ignore any fields that are NULL? I need the end result to look like:
Select Network, Network2, Network3, Network4 as Defect
and it should show Defect as something like "ON1, ON2, ON3, ON4" all in one field. But if only the first 2 are filled in, I don't want it to look like, "ON1, ON2, , , ".
Use NVL2(v, valueIfNotNull, valueIfNull)
SELECT
Network
|| nvl2(Network2, ', ' || Network2, '')
|| nvl2(Network3, ', ' || Network3, '')
|| nvl2(Network4, ', ' || Network4, '') AS Defect
FROM my_table
Use the CONCATENATE || operator and COALESCE() function:
SELECT Network
|| COALESCE(' - ' || Network2, '')
|| COALESCE(' - ' || Network3, '')
|| COALESCE(' - ' || Network4, '')
as Defect

Oracle Query, why double quotes around results, can I prevent them?

Oracle Query, why double quotes around results, can I prevent them?
I am running a query to create a fix length file that I will send to a mainframe to be processed. The results have double quotes that I need to remove before sending the file. I need to prevent the quotes via the query if possible. Here is the query:
SELECT '00000000' ||
CAST(' ' AS CHAR(161)) || '95005000000000000000' ||
CAST(' ' AS CHAR(63)) ||
CAST(CONACCT.CONTACT_ID AS CHAR(24)) ||
CAST(CONACCT.LOCATION_CODE AS CHAR(6)) ||
CAST(CONACCT.ACCT_NUM AS CHAR(18)) ||
CONACCT.NAME_RELATIONSHIP ||
CONACCT.LEAD_CONTACT_IND ||
CONACCT.RESPONSIBLE_PARTY ||
CONACCT.CAS_ADDRESS_IND ||
CAST(CONACCT.EXT_SYS_ID AS CHAR(4)) ||
CONACCT.PREF_CURRENCY
FROM CACS.CONTACT_ACCOUNT CONACCT,
CACS.ACCOUNT ACCT
WHERE CONACCT.ACCT_NUM = ACCT.ACCT_NUM
And the results look like (I removed most of the data for brevity):
"00000000 95005000000000000000 ... USD"
I need the double quotes not to be in the results. Thanks.

Format Column Headers during Pipe Delimited Concatenation (Oracle SQL)

Overview: I am tasked with providing a data extract from an Oracle database as a pipe-delimited output text file. I will be using SQLPlus to do this on the server where the data lives. Ordinarily, this task is not beyond my experience, but this time, the business desires column headers to be present.
Consider the following five columns that I need to output:
SELECT
a.USER_NAME || '|'
|| a.LAST_NAME || '|'
|| a.FIRST_NAME || '|'
|| b.PRODUCT_PURCHASED || '|'
|| c.DATEPURCHASED
FROM ...
WHERE ... ;
This SQL works fine, where the output looks like:
omnusruthius|ruthius|omnus|stackoverflow_prod|19-APR-16
However, the business wants it to look like:
USER_NM|LAST|FIRST|PROD|EFFECTIVE_DATE
omnusruthius|ruthius|omnus|stackoverflow_prod|19-APR-16
Problem: So the objective here is essentially to output the first row with custom-named column headers (aliases), as shown above. So my first approach was to try something like:
SELECT
a.USER_NAME AS USER_NM || '|'
|| a.LAST_NAME AS LAST || '|'
|| a.FIRST_NAME AS FIRST || '|'
|| b.PRODUCT_PURCHASED AS PROD || '|'
|| c.DATEPURCHASED AS EFFECTIVE_DATE
FROM ...
WHERE ...
Unfortunately, I receive:
ORA-00923: FROM keyword not found where expected
I'm not sure how that would help anyway, as the original SQL output without aliases does not show column headers in the first row anyway. Remember, this is through the command line (SQLPlus), not Toad or some other RDMS.
So then I tried:
SELECT
'USER_NM', 'LAST', 'FIRST', 'PROD', 'EFFECTIVE_DATE' FROM DUAL
UNION ALL
SELECT
a.USER_NAME || '|'
|| a.LAST_NAME || '|'
|| a.FIRST_NAME || '|'
|| b.PRODUCT_PURCHASED || '|'
|| c.DATEPURCHASED
FROM ...
WHERE ...
Which gives the following error:
ORA-01789: query block has incorrect number of result columns
I feel so close to the solution, what am I missing here? Any help will be appreciated!
Edit: Just a note to a future reader, both answers here will help you solve this problem, but upon further tweaking, I realize we've all been overthinking the solution. I'm not going to propose a new solution as the change is trivial, but consider doing the following instead:
SELECT 'USER_NM|LAST|FIRST|PROD|EFFECTIVE_DATE' FROM DUAL;
SELECT a.USER_NAME AS USER_NM || '|'
|| a.LAST_NAME AS LAST || '|'
|| a.FIRST_NAME AS FIRST || '|'
|| b.PRODUCT_PURCHASED AS PROD || '|'
|| c.DATEPURCHASED AS EFFECTIVE_DATE
FROM ...
WHERE ...
ORDER BY ... ;
The key here is the use of the semicolons in SQL*Plus. That first SELECT statement is completely independent from the second; no UNION is necessary as the output of the first query is automatically displayed immediately before the output of the second query. Both can have their own rules, which is especially convenient if your latter query is much more complicated. I can confirm the above query is working, and I'm surprised it took me that long to make that realization...
When concatenating make sure the header is a single string. Because you are concatenating the values in columns to be on one row.
If comma separation is used, as you have it in the question, the result block should also have 5 columns,which is not the case.
SELECT
'USER_NM|LAST|FIRST|PROD|EFFECTIVE_DATE' FROM DUAL
UNION ALL
SELECT
a.USER_NAME || '|'
|| a.LAST_NAME || '|'
|| a.FIRST_NAME || '|'
|| b.PRODUCT_PURCHASED || '|'
|| c.DATEPURCHASED
FROM ...
WHERE ...
Edit: The columns can also be sorted.
SELECT 'USER_NM|LAST|FIRST|PROD|EFFECTIVE_DATE' FROM DUAL
UNION ALL
SELECT * FROM (
SELECT
a.USER_NAME || '|'
|| a.LAST_NAME || '|'
|| a.FIRST_NAME || '|'
|| b.PRODUCT_PURCHASED || '|'
|| c.DATEPURCHASED
FROM ...
WHERE ...
ORDER BY DATEPURCHASED) --add any other columns needed
Since you tagged the question with SQL*Plus, you can use the PROMPT command to generate the header, which avoids complications ordering the results with a union:
PROMPT USER_NM|LAST|FIRST|PROD|EFFECTIVE_DATE
SELECT
a.USER_NAME AS USER_NM || '|'
|| a.LAST_NAME AS LAST || '|'
|| a.FIRST_NAME AS FIRST || '|'
|| b.PRODUCT_PURCHASED AS PROD || '|'
|| c.DATEPURCHASED AS EFFECTIVE_DATE
FROM ...
WHERE ...
ORDER BY ...
That takes the headings out of the SQL and into the client realm, where it arguably belongs. This also works in SQL Developer, and other clients may be able to do something similar. It won't work if you run the query on its own from another client, or over JDBC, or whatever; but then whatever is running the query can (and maybe should) provide the header in that case too.
If you aren't already, you could also consider doing SET HEADING OFF or SET PAGESIZE 0 to suppress the column headings from the query itself (though from what you said you're already doing that); and possibly SET EMBED OFF, though I don't think that's needed unless you do a separate query to generate the header line.

how to do two sqlplus queries and display the result in single line

I do not know sqlplus. But trying to complete one task at work. The task is to logon to a schema and get following information in single line -
schema_name, database_name, database_link_name, user_name
I am able to get that information in TWO lines. I will be grateful if somebody suggests a simple way of getting results of two different select queries in a single line.
Following works but gives me required results in TWO lines. I want them in single line.
SQL> select * from
(select user || ' ' || sys_context('USERENV','DB_NAME') as Instance from dual),
(select DB_LINK || ' ' || username from user_db_links);
TSTSCRIPT2 ORADEV
MCCODEVTOMCCOSTG_TSTSCRIPT1 TSTSCRIPT1
Simply specify display format for a column. In your situation, as there several values are being concatenated it'll be aliases.
/* Here character value is 11 characters long "a11"
If you need it to be longer or shorter simply increase or decrease
the value of the constant, make it "a20", for instance
*/
SQL> column instance format a11;
SQL> column res2 format a11;
SQL> select user || ' ' || sys_context('USERENV','DB_NAME') as instance
, DB_LINK || ' ' || username as res2
from user_db_links t
Result:
INSTANCE RES2
----------- -----------
HR CDB NK1 HR
select (select user || ' ' || sys_context('USERENV','DB_NAME') as Instance from dual) as user_info,
(select DB_LINK || ' ' || username from user_db_links where rownum < 2) as db_link
from dual;

Concatenate string in Oracle SQL? (wm-concat)

I've got some SQL that I'd like to format correctly for a mailout (generated directly from SQL - don't ask!). The code is as follows:
SELECT wm_concat('<br>• ' || FIELD1 || ' ' || FIELD2 || ' : ' || FIELD 3 || ' text') AS "Team"
Okay, so this kinda works - but it places a comma at the end of each line. Silly question, and possibly quite trivial, but is there anyway at all to remove the comma please? I think it's being added by the wm_concat function
Thanks
Yes the WM_CONCAT function puts a comma between each value it concatenates.
If there are no commas in your data you could do this:
SELECT replace (wm_concat('<br>• ' || FIELD1 || ' ' || FIELD2 || ' : '
|| FIELD 3 || ' text'),
',', null) AS "Team"
If you are on 11G you can use the new LISTAGG function instead:
SELECT LISTAGG ('<br>• ' || FIELD1 || ' ' || FIELD2 || ' : '
|| FIELD 3 || ' text')
WITHIN GROUP (ORDER BY <something>) AS "Team"
That will produce a result without commas.
Just trim the string for trailing commas:
RTRIM( wm_concat(...), ',' )
Oracle 10g provides a very convenient function wm_concat used to solve line reclassified demand, very easy to use this function, but the function provides only ',' this kind of delimiter.
In fact, as long as some simple conversion you can use other delimiters separated, the first thought is replace function
with t as( select 'a' x from dual union select 'b' from dual )
select replace(wm_concat(x),',','-') from t;
But taking into account the string itself may contain ',' character, use the above SQL will lead to erroneous results, but also made some changes to the above SQL.
with t as( select 'a' x from dual union select 'b' y from dual)
select substr(replace(wm_concat('%'||x),',%','-'),2) from t;
In the above SQL by a '%' as a separator, and then replace the '%' to remove the error. The program assumes that the string does not exist within the '%' string to replace the '%' in the SQL can also use other special characters.
Source: http://www.databaseskill.com/3400944/
You can create your own aggregate functions in Oracle and use those to aggregate strings.
Or use the StrAgg function written by Tom Kyte: http://www.sqlsnippets.com/en/topic-11591.html
SELECT StrAgg('<br>• ' || FIELD1 || ' ' || FIELD2 || ' : ' || FIELD 3 || ' text') AS "Team"
FROM Abc