1

How to find space after words in postgresql:

I have two same strings in my database :

string1
  string1 

I am trying to find the one with 2 spaces before and one space after.

here are some of the queries I used with their results:

SELECT * FROM table WHERE "column" LIKE '__string1_';  -->   *no result*
SELECT * FROM part1 WHERE "column" LIKE '__string1%';

Results:

1)  string1 and xyx

2)  string1 and string2

3)  string1

but I only need string1 with no strings after or before.

2
  • why don't you just use like ' string1'? Commented Sep 18, 2013 at 17:33
  • 1
    some test input and output would be nice Commented Sep 18, 2013 at 18:10

2 Answers 2

3

I will just complement the above answer:

Suppose you want to find any space in the column Name in the demo table, then the code would be like:

SELECT * FROM demo 
WHERE Name LIKE '% %'
ORDER BY Name

Now, if you want any string 'a' for example inside the column, you would just have the following:

SELECT * FROM demo 
WHERE Name LIKE '%a%'
ORDER BY Name

and also, for words that begin with a space, you would just use '_' (in a certain position):

SELECT * FROM demo 
WHERE Name LIKE '_a%'
ORDER BY Name
Sign up to request clarification or add additional context in comments.

Comments

2

There are likely several ways to accomplish this. See PostgreSQL's pattern matching documentation for some examples.

However, I use % to find patterns: select * from table where column ILIKE '%string1%'; would return anything with string1 in it, including the cols with spaces.

You can also try escaping the spaces: select * from table where column ILIKE '\ \ string1\ ';

or, even simpler select * from table where column ILIKE ' string1';

I also use the case insensitive ILIKE as an alternative for a case sensitive LIKE, so case will not matter in your query.

3 Comments

If I use % I am getting results like: "string1 and string2" but I only need string1 . If I use escaping the space I am getting this error :ERROR: unterminated quoted string at or near "'\\string1\';" and for the ' string1' I got no result.
You shouldn't get string 2 with % unless you remove the 1 and place the % in its place - i.e. string%. You would return string 12 however as % matches anything after the provided string, or before depending on if its the pre or postfix. the \ is an escape character, so its escaping the space and ensures it gets processed as a character and not whitespace. Ensure its \ \ (there is a space between the slashes and one after).
Is there a specific use case for the spaces though, couldn't you just trim the data to ensure spaces are removed if required?

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.