-1

I have an update query like this:

update table 
set col = 'hello hi' 
where col = 'hi hello'

But it is not updating the column which has the value as 'hi hello' (more than one space in between hi and hello). Any suggestions?

3 Answers3

1

If you need to update every row with various numbers of spaces, you need to use this command instead:

update table 
set col = 'hello hi' 
where col LIKE 'hi %hello'

The % is the placeholder for "any character, any number of repetitions"

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • This will also update rows with a `col` value of `'hi SOME_OTHER_STRINGhello'`. Not sure this is what OP was gunning for. – Mureinik Sep 18 '14 at 06:01
  • @Mureinik: true - but most databases that use SQL as their query language don't really have much in terms of regex support, so this is probably the best you can achieve ... – marc_s Sep 18 '14 at 06:01
1

In Postgres you can use a regular expression for that:

update the_table
set col = 'hello hi'
where col ~ '^(hello)\s+(hi)$';

The ^ at the beginning and the $ at the end are needed to avoid updating a row where the column contains e.g. 'here hello hi' or 'hello hi there'

If there can be spaces before hello or after the hi then you can add additional wildcards:

update the_table
set col = 'hello hi'
where col ~ '^\s*(hello)\s+(hi)\s*$';

Another option would be to use trim() on the column itself with the first regular expression:

update the_table
set col = 'hello hi'
where trim(col) ~ '^(hello)\s+(hi)$';

More details about regular expressions are in the manual: http://www.postgresql.org/docs/current/static/functions-matching.html

0

To avoid the problems with wildcards

update table 
set col = 'hello hi' 
where LEFT(col, 3) = 'hi ' 
      AND
      RIGHT(col, 6) = ' hello'
      AND
      SUBSTRING(col, 3, LEN(col)-7) = REPLICATE(' ',  LEN(col)-7)
Dale M
  • 2,453
  • 1
  • 13
  • 21
  • This has the same problem as my answer - it would also update a row with `hi SOME_OTHER_STRING hello` – marc_s Sep 18 '14 at 06:03