Use of substring in SQL - sql

My query is the following:
SELECT id, category FROM table1
This returns the following rows:
ID|category
1 |{IN, SP}
2 |
3 |{VO}
Does anyone know how i can remove the first char and last char of the string in PostgreSQL, so it removes: {}?

Not sure, what you mean with "foreign column", but as the column is an array, the best way to deal with that is to use array_to_string()
SELECT id, array_to_string(category, ',') as category
FROM table1;
The curly braces are not part of the stored value. This is just the string representation of an array that is used to display it.

Either using multiple REPLACE functions.
SELECT id, REPLACE(REPLACE(category, '{', ''), '}', '')
FROM table1
Or using a combination of the SUBSTRING, LEFT & LENGTH functions
SELECT id, LEFT(SUBSTRING(category, 2, 999),LENGTH(SUBSTRING(category, 2, 999)) - 1)
FROM table1
Or just SUBSTRING and LENGTH
SELECT id, SUBSTRING(category, 2, LENGTH(category)-2)
FROM table1

You could replace the {} with an empty string
SELECT id, replace(replace(category, '{', ''), '}', '') FROM table1

select id,
substring(category,charindex('{',category,len(category))+2,len(category)-2)
from table1;

select id
,left(right(category,length(category)-1),length(category)-2) category
from boo
select id
,trim(both '{}' from category)
from boo
Trim():
Remove the longest string containing only the characters (a space by
default) from the start/end/both ends of the string

The syntax for the replace function in PostgreSQL is:
replace( string, from_substring, to_substring )
Parameters or Arguments
string
The source string.
from_substring
The substring to find. All occurrences of from_substring found within string are replaced with to_substring.
to_substring
The replacement substring. All occurrences of from_substring found within string are replaced with to_substring.

UPDATE dbo.table1
SET category = REPLACE(category, '{', '')
WHERE ID <=3
UPDATE dbo.table1
SET category = REPLACE(category, '}', '')
WHERE ID <=3

Related

Remove items in a delimited list that are non numeric in SQL for Redshift

I am working with a field called codes that is a delimited list of values, separated by commas. Within each item there is a title ending in a colon and then a code number following the colon. I want a list of only the code numbers after each colon.
Example Value:
name-form-na-stage0:3278648990379886572,rules-na-unwanted-sdfle2:6886328308933282817,us-disdg-order-stage1:1273671130817907765
Desired Output:
3278648990379886572,6886328308933282817,1273671130817907765
The title does always start with a letter and the end with a colon so I can see how REGEXP_REPLACE might work to replace any string between starting with a letter and ending with a colon with '' might work but I am not good at REGEXP_REPLACE patterns. Chat GPT is down fml.
Side note, if anyone knows of a good guide for understanding pattern notation for regular expressions it would be much appreciated!
I tried this and it is not working REGEXP_REPLACE(REPLACE(REPLACE(codes,':', ' '), ',', ' ') ,' [^0-9]+ ', ' ')
This solution assumes a few things:
No colons anywhere else except immediately before the numbers
No number at the very start
At a high level, this query finds how many colons there are, splits the entire string into that many parts, and then only keeps the number up to the comma immediately after the number, and then aggregates the numbers into a comma-delimited list.
Assuming a table like this:
create temp table tbl_string (id int, strval varchar(1000));
insert into tbl_string
values
(1, 'name-form-na-stage0:3278648990379886572,rules-na-unwanted-sdfle2:6886328308933282817,us-disdg-order-stage1:1273671130817907765');
with recursive cte_num_of_delims AS (
select max(regexp_count(strval, ':')) AS num_of_delims
from tbl_string
), cte_nums(nums) AS (
select 1 as nums
union all
select nums + 1
from cte_nums
where nums <= (select num_of_delims from cte_num_of_delims)
), cte_strings_nums_combined as (
select id,
strval,
nums as index
from cte_nums
cross join tbl_string
), prefinal as (
select *,
split_part(strval, ':', index) as parsed_vals
from cte_strings_nums_combined
where parsed_vals != ''
and index != 1
), final as (
select *,
case
when charindex(',', parsed_vals) = 0
then parsed_vals
else left(parsed_vals, charindex(',', parsed_vals) - 1)
end as final_vals
from prefinal
)
select listagg(final_vals, ',')
from final

Correct Use of the SQL String_Split and Substring function

I have the SQL code below, where the #Province input parameter is in this form: "[""Central District","Central Region","Delaware","Drenthe","Eastern Cape","Free State","Gauteng","Hardap Region","Haryana","Karas Region","KwaZulu Natal","KwaZulu-Natal","Limpopo","Lorestan Province","Mpumalanga","North West","Northern Cape","Pennsylvania","Qarku i Tiranës","State of Rio de Janeiro","Toscana","Wes-Kaap","Western Cape""]" However when I test my SQL I get no rows returned. Please assist.
WITH ProvinceList as (
SELECT CAST (value AS nvarchar) name FROM STRING_SPLIT(SUBSTRING(#Provinces, 3, LEN(#Provinces)-3), ',')
)
SELECT {Site}.*
FROM {Site}
WHERE ({Site}.[Province] IN -- Get all Province names in list sent
(SELECT name
FROM ProvinceList))
ORDER BY {Site}.[Name] ASC
After the STRING_SPLIT your list will consist of names like "Eastern Cape" and "Free State" with the quotation mark. Most likely you do not have quotation marks in your table, so you need to remove those characters from the input.
SET #Provinces = REPLACE(#Provinces, '"', '')
WITH ProvinceList as (
SELECT CAST (value AS nvarchar) name FROM STRING_SPLIT(SUBSTRING(#Provinces, 2, LEN(#Provinces)-2), ',')
)

SQL Server select part of string

I have table like this
Column1
-------------------------------------------------------
nn=APPLE IPod 44454,o=0006,o=TOP8,nn=USA,nn=TOP8+
nn=SAMSUNG G5 487894,o=04786,o=T418,nn=JPN,nn=TO478+
And I need update that table and get result like this
Column1 Column2
---------------------------------------------------------------
nn=APPLE IPod 44454,o=0006,o=TOP8,nn=USA,nn=TOP8+ 44454
nn=SAMSUNG G5 487894,o=04786,o=T418,nn=JPN,nn=TO478+ 487894
My idea is but I can not fit with first character:
update tablename
set [column2] = SUBSTRING(column1, 1, CHARINDEX(' ', column1) - 1 (column1, CHARINDEX(' ', column1) + 1, LEN(column1))
This query can help you.
UPDATE tablename SET [column2] =
SUBSTRING((LEFT(column1,CHARINDEX(',',column1)-1)), CHARINDEX(' ', column1, CHARINDEX(' ',column1) +1 ) +1 ,LEN(column1))
Okay, given the second sample record, it looks like what you need is the last element of the space-delimited string in the first position of the comma-delimited string. So write yourself (or find) a string-splitter function that accepts a string and a delimiter, and then your parsing logic is:
split the field at the commas
take the first element
split that element at the spaces
take the last element
Does that make sense?
The following answer is based only on the two records you actually showed us. If we were to derive a rule from this, it might be that we want to extract the previous word (a product number) occurring immediately before the first comma in the string. If so, then we can try the following logic:
isolate the substring before the comma (e.g. nn=APPLE Ipod 44454)
reverse that string (45444 dopI ELPPA=nn)
then take the substring of that before the first space (45444)
finally reverse this substring to yield the product number we want (44454)
Consider the following query, with data imported via a CTE:
WITH yourTable AS (
SELECT 'nn=APPLE IPod 44454,o=0006,o=TOP8,nn=USA,nn=TOP8+' AS column1 UNION ALL
SELECT 'nn=SAMSUNG G5 487894,o=04786,o=T418,nn=JPN,nn=TO478+'
),
update_cte AS (
SELECT
column1,
column2,
REVERSE(
SUBSTRING(REVERSE(SUBSTRING(column1, 1, CHARINDEX(',', column1)-1)),
1,
CHARINDEX(' ', REVERSE(SUBSTRING(column1, 1, CHARINDEX(',', column1)-1))) - 1)
) AS col2
FROM yourTable
)
SELECT column1, col2 FROM update_cte;
Output:
Demo here:
Rextester
If you wanted to update your table to bring in these column2 product IDs, then you can use the above CTE fairly easily:
UPDATE update_cte
SET column2 = col2;

How to Extract the middle characters from a string without an specific index to start and end it before the space character is read?

I have a column that contains data like:
AB-123 XYZ
ABCD-456 AAA
BCD-789 BBB
ZZZ-963
Y-85
and this is what i need from those string:
123
456
789
963
85
I need the characters from the left after the dash('-') character, then ends before the space character is read.
Thank You guys.
Note: Original tag on this question was Oracle and this answer is based on that tag. Now that, tag is updated to SqlServer, this answer is no longer valid, if somebody looking for Oracle solution, this may help.
Use regular expression to arrive at sub string.
select trim(substr(regexp_substr('ABCD-456 AAA','-[0-9]+ '),2)) from dual
'-[0-9]+ ' will grab any string pattern which starts with dash has one or more digits and ends with a ' ' and returns number with dash
substr will remove '-' from above output
trim will remove any trailing ' '
Check This.
Using Substring and PatIndex.
select
SUBSTRING(colnm, PATINDEX('%[0-9]%',colnm),
PATINDEX('%[^0-9]%',ltrim(RIGHT(colnm,LEN(colnm)-CHARINDEX('-',colnm)))))
from
(
select 'AB-123 XYZ' colnm union
select 'ABCD-456 AAA' union
select 'BCD-789 BBB' union
select 'ZX- 23 BBB'
)a
OutPut :
Try this
http://rextester.com/YTBPQD69134
CREATE TABLE Table1 ([col] varchar(12));
INSERT INTO Table1
([col])
VALUES
('AB-123 XYZ'),
('ABCD-456 AAA'),
('BCD-789 BBB');
select substring
(col,
charindex('-',col,1)+1,
charindex(' ',col,1)-charindex('-',col,1)
) from table1;
Assume all values has '-' and followed by a space ' '. Below solution will not tolerant to exception case:
SELECT
*,
SUBSTRING(Value, StartingIndex, Length) AS Result
FROM
-- You can replace this section of code with your table name
(VALUES
('AB-123 XYZ'),
('ABCD-456 AAA'),
('BCD-789 BBB')
) t(Value)
-- Use APPLY instead of sub-query is for debugging,
-- you can view the actual parameters in the select
CROSS APPLY
(
SELECT
-- Get the first index of character '-'
CHARINDEX('-', Value) + 1 AS StartingIndex,
-- Get the first index of character ' ', then calculate the length
CHARINDEX(' ', Value) - CHARINDEX('-', Value) - 1 AS Length
) b

Changing LastName,FirstName to LastName,FirstInitial

I'm sure this is super easy, but how would I go about converting LastName,FirstName to LastName,FirstInitial?
For example changing Smith,John to Smith,J or Johnson,John to Johnson,J etc.
Thank You!
In case of LastName and FirstName columns:
select LastName,substr(FirstName,1,1)
from mytable
;
In case of a fullname saved in a single column:
select substr(fullname,1,instr(fullname || ',',',')-1) || substr(fullname,instr(fullname || ',',','),2)
from mytable
;
or
select regexp_replace (fullname,'([^,]*,?)(.).*','\1\2')
from mytable
;
Here is one way, using just "standard" instr and substr. Assuming your input is a single string in the format 'Smith,John':
select substr(fullname, 1, instr(fullname, ',')+1) from yourtable;
yourtable is the name of the table, and fullname is the name of the column.
instr(fullname, ',') finds the position of the comma within the input string (it would be 6 in 'Smith,John'); thensubstrtakes the substring that begins at the first position (the1in the function call) and ends at the position calculated byinstr`, PLUS 1 (to get the first initial as well).