0

I need to create a SQL Query. This query need to select from a table where a column contains regular expression.

For example, I have those values:

TABLE test (name)

  • XHRTCNW
  • DHRTRRR
  • XHRTCOP
  • CPHCTPC
  • CDDHRTF
  • PEOFOFD

I want to select all the data who have "HRT" after 1 char (value 1, 2 and 3 - Values who looks like "-HRT---") but not those who might have "HRT" after 1 char (value 5).

So I'm not sure how to do it because a simple

SELECT * 
FROM test 
WHERE name LIKE "%HRT%"

will return value 1, 2, 3 and 5.

Sorry if I'm not really clear with what I want/need.

1
  • plsql is for Oracle only. Commented Jan 13, 2016 at 14:15

3 Answers 3

2

You can also change the pattern. Instead of using % which means zero-or-more anything, you can use _ which means exactly one.

SELECT * FROM test WHERE name like '_HRT%';
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, this way is also working thanks ! Is there any other char that might means other value than "_" ?
The LIKE function is quite restricted and only uses "_" and "%" as wildcards. There are other functions available that do full regular expression matching etc. Details available at: postgresql.org/docs/current/static/functions-matching.html
Thanks for the tip !
1

You can use substring.

SELECT * FROM test WHERE substring(name from 2 for 3) = 'HRT'

1 Comment

Cool ! It's working with this function. Is there any link where I can find "All the function" available in the Where section?
0

Are the names always 7 letters? Do:

SELECT substring (2, 4, field) from sometable

That will just select the 2-4th characters and then you can use like "%HRT"

2 Comments

Nop sadly, it's not always 7 letters
Regardless, all three answers will return the entries you are looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.