Ignore spaces in substring SQL/Oracle - sql

I'm trying to substring the last 3 digits from a column. Problem is, some of them have a random space at the end, which then only returns 2 of the 3 needed values from the column. Right now I have:
SELECT substr(infovalue, -3)
FROM TABLE
WHERE INFOCODE = 555
How can I get my statement to ignore the space at the end?
thanks!

I guess you are in Oracle. Apply an rtrim to remove all trailing spaces
SELECT substr(rtrim(infovalue), -3)
FROM TABLE
WHERE INFOCODE = 555
And please specify the vendor & product version for all your questions.

Related

Replacing multiple special characters using Oracle SQL functions

#All - Thanks for your help
ID Email
1 karthik.sanu#gmail.com. , example#gmail.com#
2 karthik?sanu#gmail.com
In the above example, if you see the 1st row, the email address is invalid because of dot at the end of 1st email address and # at the end of 2nd email address.
In 2nd row, there is a ? in between email address.
Just wanted to know is there any way to handle there characters and remove those from email address using SQL function and update the same in table.
Thanks in advance.
you can also check a translate function
translate('my ,string#with .special chars','#,?. ', ' ')
You could nest multiple invokations of replace(), but this quickly becomes convoluted.
On the other hand, regexp_replace() comes handy for this:
regexp_replace(column_name, '#|,|\?|\.', ' ')
The pipe character (|) stands for or. The dot (.) and the question mark (?) are meaningful characters in regexes so they need to escaped with a backslash (\).
Something like this will "remove" everything but digits, letters and spaces (if that's what you wanted).
SQL> with test (col) as
2 (select 'This) is a se#nten$ce with. everything "but/ only 123 numbers, and ABC lett%ers' from dual)
3 select regexp_replace(col, '[^a-zA-Z0-9 ]') result
4 from test;
RESULT
-----------------------------------------------------------------------
This is a sentence with everything but only 123 numbers and ABC letters
SQL>

Understanding why length in SQL DB2 would return short results as the max character length

I have a query that pulls the count of all last names in our DB and sorts the count by the length of the last name. This is a VARCHAR field with a max length of 120.
Some results that are a much shorter character length - 5, 6, 7, etc characters - are showing as 120. Using a RTRIM seems to get the right results, but I am confused as to why when I don't have the RTRIM why most values calculate correctly, but some don't. While I know I have the right results with the RTRIM, I just want to understand why some cases don't pull that correctly without it.
SELECT LENGTH(NAME_LAST), COUNT(*)
FROM database
GROUP BY LENGTH(NAME_LAST)
ORDER BY LENGTH(NAME_LAST) DESC;
Db2 does not trim trailing spaces unless you ask it to with e.g. RTRIM
$ db2 "create table t(v varchar(120))"
$ db2 "insert into t values space(120)"
$ db2 "select length(v) from v"
1
-----------
120
1 record(s) selected.
$ db2 "select length(rtrim(v)) from v"
1
-----------
0
1 record(s) selected.
You can have leading/trailing whitespaces or other non-printable characters. Try concatenating quotes or some other characters around the selection of a column and it'll high light it for you. Or as #mao suggests show the hex values
Does this help answer your question?
"If a grouping-expression contains varying-length strings with trailing blanks, the values in the group can differ in the number of trailing blanks and might not all have the same length. In that case, a reference to grouping-expression still specifies only one value for each group, but the value for a group is chosen arbitrarily from the available set of values. Thus, the actual length of the result value is unpredictable."
https://www.ibm.com/support/knowledgecenter/SSEPEK_12.0.0/sqlref/src/tpc/db2z_sql_groupbyclause.html

T/SQL - String Manipulation

I have the below query.
SQLFiddle
I can only have possible 7 characters (- and A-Z combined)
There can only be ONE "-" for first 5 characters (Monday to Friday)
For Saturday and Sunday, we can only have one character or dash
I am replacing Sa and Su with just S
However, whenever they are passing in TWO dashes for Saturday AND/OR Sunday, I need to replace them with ONE dash for each
so length can only be 7 after all manipulations.
I have tried w/e I could but getting stuck at the two vs one dash scenario for Saturday/Sunday position.
Please help! I will keep this updated as I find more.
THX in ADV
Code:
CREATE Table TempTable (string varchar(50))
INSERT INTO TempTable (string)
VALUES ('MTWRFSS')
,('MTWRFSaS')
,('MTWRFSaSu')
,('----F--')
,('----F----')
,('MT------')
,('MT------')
,('----FSa--')
,('----FSa-')
,('----FS--')
,('----FS-')
,('----F-Su')
,('----F--Su')
,('----F-S')
,('----F--S')
UPDATE TempTable
SET string = REPLACE(REPLACE(RTRIM(LTRIM(string)),'SA','S'),'SU','S')
SELECT string
,LEN(String) AS stringLengh FROM TempTable
--DROP TABLE TempTable
Try to manipulate only characters after 5th, because from MON to FRY you always have 1 -.
So I think this will work:
SELECT
string as InitialString
,LEFT(LEFT(String,5) + replace(replace(replace(RIGHT(String,LEN(String)-5),
'Sa','S'),'Su','S'),'--','-') + '--',7) as FinalString
FROM TempTable;
You have to cut string into 2: left 5 and the rest. Then using several replaces you can have correct Sat/Sun combination. Concatenate both and you will have final decision.
Also 2 more dashes have to be added and the you have to take only LEFT 7, because if you have '--' it will be replaced with '-'.

using oracle sql substr to get last digits

I have a result of a query and am supposed to get the final digits of one column say 'term'
The value of column term can be like:
'term' 'number' (output)
---------------------------
xyz012 12
xyz112 112
xyz1 1
xyz02 2
xyz002 2
xyz88 88
Note: Not limited to above scenario's but requirement being last 3 or less characters can be digit
Function I used: to_number(substr(term.name,-3))
(Initially I assumed the requirement as last 3 characters are always digit, But I was wrong)
I am using to_number because if last 3 digits are '012' then number should be '12'
But as one can see in some specific cases like 'xyz88', 'xyz1') would give a
ORA-01722: invalid number
How can I achieve this using substr or regexp_substr ?
Did not explore regexp_substr much.
Using REGEXP_SUBSTR,
select column_name, to_number(regexp_substr(column_name,'\d+$'))
from table_name;
\d matches digits. Along with +, it becomes a group with one or more digits.
$ matches end of line.
Putting it together, this regex extracts a group of digits at the end of a string.
More details here.
Demo here.
Oracle has the function regexp_instr() which does what you want:
select term, cast(substr(term, 1-regexp_instr(reverse(term),'[^0-9]')) as int) as number
select SUBSTRING(acc_no,len(acc_no)-1,len(acc_no)) from table_name;

How to replace a comma separated value in table column with user input value oracle

I have a table in oracle with a column with comma separated values. What i need is when a user enters a value and if that value is present in any of the rows, it should be removed.
eg.
COL
123,234
56,123
If user enters 123, the 1st column should have only 234 and second row should have only 56.
How do we do this in oracle??
Please help
Thanks
delete from yourtable t
where
instr(','||t.col||',', '123') > 0
You can replace '123' with a parameter if you like.
But a better way would be not to store comma separated values, and create a detail table instead. If you need to look for a specific value within a comma separated list, you cannot make use of indices, amongst other limitations.
[edit]
Misunderstood the question. You meant this:
update YourTable t
set
t.col = substr(substr(replace(','||t.col||',', ',123,', ','), 2), -2)
where
instr(','||t.col||',', '123') > 0
Add ',' before and after to match items at the beginning or end of the value.
Replace using the value ',123,' (within comma's) to prevent accidentally matching 1234 too.
Use substr twice to remove the first and last character (the added commas)
Use instr in the where to prevent updating records that don't need to be updated (better performance).
try this :
UPDATE t
SET col = REPLACE(REPLACE(col, '&variable', ''), ',', '') FROM t ;