Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why isn't SUBSTR stopping at the end index using instr?

I have a string value I’d like to make more presentable:

'Course grade for <font color="#FF0000">Student Name</font>'

but my query to extract the Student Name:

SELECT SUBSTR(col, instr(col, '>',1,1)+1, instr(col, '<',1,2)) FROM my_table where course_id=1

returns Student Name</font> despite instr('<',1,2) returning the correct index.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m not sure why it doesn’t stop on that index and returns the rest of the string. Ideally I’d like it to return Student Name

Many thanks!

>Solution :

You have to subtract the start of the string, as the second paramter is length and INSTR counts from the start

CREATE TABLE my_table (course_id int,col varchar2(200))
INSERT INTO my_table VALUES(1,'Course grade for <font color="#FF0000">Student Name</font>')
INSERT INTO my_table VALUES(1,'Course grade for <font color="#FF0000">abel </font>')
SELECT SUBSTR(col, instr(col, '>',1,1)+1, instr(col, '</',1,1) -  instr(col, '>',1,1) - 1) FROM my_table where course_id=1
| SUBSTR(COL,INSTR(COL,'>',1,1)+1,INSTR(COL,'</',1,1)-INSTR(COL,'>',1,1)-1) |
| :------------------------------------------------------------------------ |
| Student Name                                                              |
| abel                                                                      |

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading