1

I am trying to run a query to select values from a column in a table, which doesn't have space at specific position in the data in the column. i.e. first two positions.

Select test_col from A where SUBSTR(test_col, 0 ,2) <> ' '

So far, it's returning columns with have space in the beginning two position.

Any Suggestion.

Example:

test_col
  Quick Brown Fox
Black Sheep
  This a test
Mary had a little lamb

So the query should return Black Sheep and Mary had a little lamb.

4
  • You need to elaborate. Could you show some sample data and what the output would look like? Commented May 16, 2013 at 17:37
  • Ok update with example. Commented May 16, 2013 at 17:39
  • 1
    Setting up a sqlfiddle is always helpful too. Commented May 16, 2013 at 17:40
  • Is test_col a VARCHAR or a CHAR column? Commented May 16, 2013 at 17:48

4 Answers 4

4

Your index should start with 1 and not 0 and I prefer Trim and check for null over checking for space in data. Try this

Select test_col from A where Trim(SUBSTR(test_col, 1 ,2)) IS NOT NULL
Sign up to request clarification or add additional context in comments.

Comments

1

Oracle 10g and later:

SELECT test_col FROM a WHERE REGEXP_LIKE(test_col, '^[^ ]{2}.*$'); 

Here's SQL Fiddle

3 Comments

Thanks it gives error of invalid relational operator ora-00920
Sorry about that. Should've tested. Give me a few and I'll fix it.
Thanks it works now. There are more than one correct answer. Since you provided sql fiddle. So i am accepting your answer. Thanks to every one for their help and time.
1
select test_col 
  from A 
 where SUBSTR(test_col, 1, 1) <> ' '
   and SUBSTR(test_col, 2, 1) <> ' ';

OR (even better)

select test_col 
  from A 
 where INSTR(SUBSTR(test_col, 1, 2), ' ') = 0;

Comments

1

The first positional index of a string is 1, not 0 (though SUBSTR() treats it as 1) and you're only testing for one space:

select test_col from A where SUBSTR(test_col, 1, 2) <> '  '

7 Comments

I tried before with indices (1,2) it returns the data which has space in those two positions.
You're checking for one space though @Nomad, not two.
you are right, thanks. But same result if i change indices to 1,3 instead of 1,2 etc.
Thanks Ben for your answer and help.
Of course @Nomad, if you're testing for 3 spaces you have to check whether it's not equal to 3 spaces!
|

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.