39

How can I find all column values in a column which have trailing spaces? For leading spaces it would simply be

select col from table where substring(col,1,1) = ' ';
gotqn
  • 42,737
  • 46
  • 157
  • 243
atricapilla
  • 2,560
  • 12
  • 36
  • 39

14 Answers14

82

You can find trailing spaces with LIKE:

SELECT col FROM tbl WHERE col LIKE '% '
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Jaxidian
  • 13,081
  • 8
  • 83
  • 125
  • 1
    I know this is a very old post, but i would like to know, if i would like to check if any columns in my table contain trailing spaces? Btw i got 45 fields in the table...how can i do so? – 10e5x Jan 28 '13 at 03:03
  • 3
    @10e5x That is a different question. I recommend you post it as a different question. :-) – Jaxidian Feb 05 '13 at 00:37
  • @rodrigocprates: It depends. One option could be to create an additional BIT column to store a calculated value (trigger time?) of whether or not the field ends with a space. Another option would be to create a Computed Column to do the same thing. Or perhaps an indexed View to do the same thing. Lastly, something to try (it might be worse, or not) would be to use substrings to grab the last character and see if it is a space, although I suspect it would be slower. – Jaxidian Jul 08 '14 at 13:16
  • 2
    To remove it: `UPDATE tablename SET columnname = RTRIM(columnname)`. See [this answer](https://stackoverflow.com/a/14782025/1494454). – totymedli Feb 27 '20 at 18:52
9

SQL Server 2005:

select col from tbl where right(col, 1) = ' '

As a demo:

select 
    case when right('said Fred', 1) = ' ' then 1 else 0 end as NoTrail,
    case when right('said Fred ', 1) = ' ' then 1 else 0 end as WithTrail

returns

NoTrail WithTrail
0       1  
Neil Moss
  • 6,598
  • 2
  • 26
  • 42
6

This is what worked for me:

select * from table_name where column_name not like RTRIM(column_name)

This will give you all the records that have trailing spaces.

If you want to get the records that have either leading or trailing spaces then you could use this:

select * from table_name where column_name not like LTRIM(RTRIM(column_name))
5

A very simple method is to use the LEN function. LEN will trim trailing spaces but not preceeding spaces, so if your LEN() is different from your LEN(REVERSE()) you'll get all rows with trailing spaces:

select col from table where LEN(col) <> LEN(REVERSE(col));

this can also be used to figure out how many spaces you have for more advanced logic.

Allan S. Hansen
  • 4,013
  • 23
  • 25
2
SELECT * FROM tbl WHERE LEN(col) != DATALENGTH(col)

Should work also.

Hubbitus
  • 5,161
  • 3
  • 41
  • 47
2

There's a few different ways to do this...

My favorite option, assuming your intention is to remove any leading and / or trailing spaces, is to execute the following, which will dynamically create the T-SQL to UPDATE all columns with an unwanted space to their trimmed value:

SELECT 
'UPDATE [<DatabaseName>].[dbo].['+TABLE_NAME+']
SET ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']))
WHERE ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']));'+CHAR(13)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<TableName>%' 
    AND DATA_TYPE!='date'
ORDER BY TABLE_NAME,COLUMN_NAME

If you really need to identify them though, try one of these queries:

SELECT *
FROM [database].[schema].[table]
WHERE [col1]!=LTRIM(RTRIM([col1]))

More dynamic SQL:

SELECT 'SELECT ''['+TABLE_NAME+'].['+COLUMN_NAME+']'',*
FROM [<your database name>].[dbo].['+TABLE_NAME+']
WHERE ['+COLUMN_NAME+'] LIKE ''% ''
    OR ['+COLUMN_NAME+'] LIKE '' %'';
GO
'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<filter table name as desired>%'
    AND DATA_TYPE!='date'
SQL_Deadwood
  • 491
  • 5
  • 14
0

Spaces are ignored in SQL Server so for me even the leading space was not working .

select col from table where substring(col,1,1) = ' '

wont work if there is only one space (' ') or blank ('')

so I devised following:

select * from [table] where substring(REPLACE(col, ' ', '#'),1,1) = '#'
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Thunder
  • 10,366
  • 25
  • 84
  • 114
  • What do you mean by "spaces are ignored in SQL Server..."? Perhaps you mean in the context of the substring function? – SQL_Deadwood Mar 29 '17 at 23:40
  • @SQL_Underworld Not sure what OP meant, but for an actual db value of 'test ', I had the row returned for all of 1. `where test like 'test'`, 2. `'where test like 'test '`, 3. `where test = 'test'` and 4. `where test='test '`. I also found that `len(test)` was 4 instead of 5. So it seems like all of len, like and = simply ignored the trailing space. The substring trick that Thunder suggests did replace the space with a #, so that len, like and = could be used. This is possibly encoding-specific. – Hutch Nov 14 '17 at 23:12
0

Here is another alternative for trailing spaces.

DECLARE @VALUE VARCHAR(50) = NULL

DECLARE @VALUE VARCHAR(50) = '  '

IF ((@VALUE IS NOT NULL) AND (LTRIM(RTRIM(@VALUE)) != ''))

BEGIN
   SELECT 'TRUE'
END
ELSE
BEGIN
   SELECT 'FALSE'
END
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
0

Try this:

UPDATE Battles
SET name = CASE WHEN (LEN(name+'a')-1)>LEN(RTRIM(name))
THEN REPLICATE(' ', (LEN(name+'a')-1)- LEN(RTRIM(name)))+RTRIM(name)
ELSE name
END
besartm
  • 558
  • 1
  • 7
  • 14
0

I have found the accepted answer a little bit slower:

SELECT col FROM tbl WHERE col LIKE '% ';

against this technique:

SELECT col FROM tbl WHERE ASCII(RIGHT([value], 1)) = 32;

The idea is to get the last char, but compare its ASCII code with the ASCII code of space instead only with ' ' (space). If we use only ' ' space, an empty string will yield true:

DECLARE @EmptyString NVARCHAR(12) = '';

SELECT IIF(RIGHT(@EmptyString, 1) = ' ', 1, 0); -- this returns 1

The above is because of the Microsoft's implementation of string comparisons.

So, how fast exactly?

You can try the following code:

CREATE TABLE #DataSource 
(
    [RowID] INT PRIMARY KEY IDENTITY(1,1)
   ,[value] NVARCHAR(1024)
);

INSERT INTO #DataSource ([value])
SELECT TOP (1000000) 'text ' + CAST(ROW_NUMBER() OVER(ORDER BY t1.number) AS VARCHAR(12)) 
FROM master..spt_values t1 
CROSS JOIN master..spt_values t2

UPDATE #DataSource
SET [value] = [value] + ' '
WHERE [RowID] = 100000;


SELECT *
FROM #DataSource
WHERE ASCII(RIGHT([value], 1)) = 32;

SELECT *
FROM #DataSource
WHERE [value] LIKE '% ';

On my machine there is around 1 second difference:

enter image description here

I have test it on table with 600k rows, but larger size, and the difference was above 8 seconds. So, how fast exactly will depend on your real case data.

gotqn
  • 42,737
  • 46
  • 157
  • 243
0

Another way to achieve this by using CHARINDEX and REVERSE like below:

select col1 from table1
WHERE charindex(' ', reverse(col1)) = 1

See example Here

Md. Suman Kabir
  • 5,243
  • 5
  • 25
  • 43
0

Simple use below query to get values having any number of spaces in begining or at end of values in column.

 select * from table_name where column_name like ' %' or column_name like '% ';
Shashank.gupta40
  • 915
  • 1
  • 8
  • 26
0

Here's an alternative to find records with leading or trailing whitespace, including tabs etc:

SELECT * FROM tbl WHERE NOT TRIM(col) = col
Jonatan
  • 3,752
  • 4
  • 36
  • 47
  • 4
    There is no `TRIM` function in SQL Server and trailing spaces are ignored in `=` comparisons anyway. – Martin Smith Jan 30 '12 at 10:55
  • 1
    Ok, sorry, I thought that was standard SQL. It works in PostgreSQL as expected though, and I found this question because i was trying to solve the same problem with PostgreSQL, so perhaps it can help someone else. – Jonatan Jan 30 '12 at 11:11
-1

We can try underscore to find the entries which are blanks,though not an accurate solution like using '% %' or ' ', But I could find entries which are blanks.

select col_name from table where col_name like '_'

mimix
  • 29
  • 3