How to do string manipulation in SQL query - sql

I know I'm close to figuring this out but need a little help. What I'm trying to do is all grab a column from a particular table, but chop off the first 4 characters. For example if in a column the value is "KPIT08L", the result I was is 08L. Here is what I have so far but not getting the desired results.
SELECT LEFT(FIELD_NAME, 4)
FROM TABLE_NAME

First up, left will give you the leftmost characters. If you want the characters starting at a specific location, you need to look into mid:
select mid (field_name,5) ...
Secondly, if you value performance,portability and scalability at all, this sort of "sub-column" manipulation should generally be avoided. It's usually far easier (and faster) to patch columns together than to split them apart.
In other words, keep the first four characters in their own column and the rest in a separate column, and do your selects on the relevant one. If you're using anything less than a full column, then it's technically not one attribute of the row.

Try with
SELECT MID(FIELD_NAME, 5) FROM TABLE_NAME
Mid is very powerfull, it let you select the starting point and all the remainder, or,
if specified, the length desidered as in
SELECT MID(FIELD_NAME, 5, 2) FROM TABLE_NAME ' gives 08 in your example text

SELECT RIGHT(FIELD_NAME,LEN(FIELD_NAME)-4)
FROM TABLE_NAME;
If it is for a generic string then the above one will work...

Don't have Access at my current location, but please try this.
SELECT RIGHT(FIELD_NAME, LEN(FIELD_NAME)-4)
FROM TABLE_NAME

The LEFT(FIELD_NAME, 4) will return the first 4 caracters of FIELD_NAME.
What you need to do is :
SELECT MID(FIELD_NAME, 5)
FROM TABLE_NAME
If you have a FIELD_NAME of 10 caracters, the function will return the 6 last caracters (chopping the first 4)!

Related

Using the function SPLIT_PART twice in PostgreSQL?

I have a TEXT column where each text is formatted as such:
/customers/{customer_id}/views/{id1}~{id2}/
I am trying to fetch the id2 only.
My idea is how to split the string by the / character first, where I will have:
customers, {customer_id}, views, {id1}~{id2}.
And then, get the last position:
{id1}~{id2}. And then split it again by the ~ character, and finally get the last position.
The issue is that I am new to SQL and I have no idea if this is even possible. How can I do that and end up with only one column?
SELECT
split_part(thetext, '/', 4) as temp
// how do I proceed from here?
FROM mytable
EDIT:
Some examples:
/customers/1231341/views/1312391293~3432491/
/customers/2213441/views/424131~231321341/
The IDs are of different lengths as well.
Use regexp_replace() to capture the part you want while matching the whole input, and replacing (the whole input) with the capture:
select regexp_replace(thetext, '.*~(.*)/', '\1') as temp
from mytable
See live demo.

Substring of a specific occurence

I have a column as varchar2 datatype, the data in it is in format:
100323.3819823.222
100.323123.443422
1001010100.233888
LOL12333.DDD33.44
I need to remove the whole part after the first occurrence of '.'
In the end it should look like this:
100323
100
1001010100
LOL12333
I cant seem to find the exact substring expression due to the fact that there is not any fix length of the first part.
One way is to use REGEXP_SUBSTR:
SELECT REGEXP_SUBSTR(column_name,'^[^.]*') FROM table
The other way is to combine SUBSTR with INSTR, which is a bit faster, but will result in NULL if the data doesn't contain a dot, so you'll have to add a switch if needed:
SELECT SUBSTR(column_name, 1, INSTR(column_name,'.') - 1) FROM table
For oracle you can try this:
select substr (i,1,Instr(i,'.',i)-1) from Table name.

Query to return all results where a specific character is in the 4th position of a string

I have a table that contains 6 digit ID numbers ('AB1E11' for example) and I need to build a query in Teradata SQL that returns all results where 'E' is in the fourth position of the string. I haven't had a reason to do anything like this in several years, so I am extremely rusty. I know how to filter the results so that 'E' is contained anywhere in the string ( using SELECT * WHERE PLANID LIKE '%E%'), but I'm not sure how to filter the results so that only the ones where 'E' is in the 4th position show up. Can anyone help me out with this? I tried searching several times but couldn't find an answer.
Thank you.
Just use LIKE with the _ wildcard:
where planid like '____E%'
Note: that is 4 underscores, which represent any single character.
SELECT planid WHERE CHARINDEX('E', planid) = 4;
The starting position returned is 1-based, not 0-based.

Finding first and second word in a string in SQL Developer

How can I find the first word and second word in a string separated by unknown number of spaces in SQL Developer? I need to run a query to get the expected result.
String:
Hello Monkey this is me
Different sentences have different number of spaces between the first and second word and I need a generic query to get the result.
Expected Result:
Hello
Monkey
I have managed to find the first word using substr and instr. However, I do not know how to find the second word due to the unknown number of spaces between the first and second word.
select substr((select ltrim(sentence) from table1),1,
(select (instr((select ltrim(sentence) from table1),' ',1,1)-1)
from table1))
from table1
Since you seem to want them as separate result rows, you could use a simple common table expression to duplicate the rows, once with the full row, then with the first word removed. Then all you have to do is get the first word from each;
WITH cte AS (
SELECT value FROM table1
UNION ALL
SELECT SUBSTR(TRIM(value), INSTR(TRIM(value), ' ')) FROM table1
)
SELECT SUBSTR(TRIM(value), 1, INSTR(TRIM(value), ' ') -1) word
FROM cte
Note that this very simple example assumes that there is a second word, if there isn't, NULL will be returned for both words.
An SQLfiddle to test with.
While Joachim Isaksson's answer is a robust and fast approach, you can also consider splitting the string and selecting from the resulting pieces set. This is just meant as hint for another approach, if your requirements alter (e.g. more than two string pieces).
You could split finally by the regex /[ ]+/, and so getting the words between the blanks.
Find more about splitting here: How do I split a string so I can access item x?
This will strongly depend on the SQL dialect you are using.
Try this with REGEXP_SUBSTR:
SELECT
REGEXP_SUBSTR(sentence,'\w+\s+'),
REGEXP_SUBSTR(sentence,'\s+(\w+)\s'),
REGEXP_SUBSTR(sentence,'\s+(\w+)\s+(\w+)'),
REGEXP_SUBSTR(REGEXP_SUBSTR(sentence,'\s+(\w+)\s+(\w+)'),'\w+$'),
REGEXP_SUBSTR(sentence,'\s+(\w+)\s+$')
FROM table1;
result:
1 2 3 4 5
Hello Monkey Monkey this this is_me
Learn more about REGEXP_SUBSTR reference to Using Regular Expressions With Oracle Database
Test use SqlFiddle: http://sqlfiddle.com/#!4/8e9ef/9
If you only want to get the first and the second word, use REGEXP_INSTR to get second word start position :
SELECT
REGEXP_SUBSTR(sentence,'\w+\s+') AS FIRST,
REGEXP_SUBSTR(sentence,'\w+\s',REGEXP_INSTR(sentence,'\w+\s+')+length(REGEXP_SUBSTR(sentence,'\w+\s+'))) AS SECOND
FROM table1;

Is it possible to get the matching string from an SQL query?

If I have a query to return all matching entries in a DB that have "news" in the searchable column (i.e. SELECT * FROM table WHERE column LIKE %news%), and one particular row has an entry starting with "In recent World news, Somalia was invaded by ...", can I return a specific "chunk" of an SQL entry? Kind of like a teaser, if you will.
select substring(column,
CHARINDEX ('news',lower(column))-10,
20)
FROM table
WHERE column LIKE %news%
basically substring the column starting 10 characters before where the word 'news' is and continuing for 20.
Edit: You'll need to make sure that 'news' isn't in the first 10 characters and adjust the start position accordingly.
You can use substring function in a SELECT part. Something like:
SELECT SUBSTRING(column, 1,20) FROM table WHERE column LIKE %news%
This will return the first 20 characters from column column
I had the same problem, I ended up loading the whole field into C#, then re-searched the text for the search string, then selected x characters either side.
This will work fine for LIKE, but not full text queries which use FORMS OF INFLECTION because that may match "women" when you search for "woman".
If you are using MSSQL you can perform all kinds VB-like of substring functions as part of your query.