Spaces in WHERE clause for SQL Server [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
11
down vote

favorite
1













This question already has an answer here:



  • Why the SQL Server ignore the empty space at the end automatically?

    2 answers



I want to find out the records in which a certain column contains exactly one space and nothing else. So I wrote the first of the following queries:



select COUNT(*)
from mytable
where col = ' ' -- One space

select COUNT(*)
from mytable
where col = ' ' -- Two spaces

select COUNT(*)
from mytable
where col = ' ' -- Three spaces


However, all three queries return the exact same records. Does Microsoft SQL Server not distinguish between the amount of spaces? How can I query exactly for one, two or more spaces?










share|improve this question















marked as duplicate by Salman A sql
Users with the  sql badge can single-handedly close sql questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Oct 3 at 7:36


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • dba.stackexchange.com/questions/10510/…
    – Ivan Starostin
    Oct 1 at 13:22










  • Its simple: looks into empty string. doesnt matter if its one or two spaces. try it this way 'value ' and check result set
    – Hadrian
    Oct 1 at 13:24










  • If SQL Server would adhere to Standard SQL it would be really simple:where col like ' '
    – dnoeth
    Oct 1 at 14:02














up vote
11
down vote

favorite
1













This question already has an answer here:



  • Why the SQL Server ignore the empty space at the end automatically?

    2 answers



I want to find out the records in which a certain column contains exactly one space and nothing else. So I wrote the first of the following queries:



select COUNT(*)
from mytable
where col = ' ' -- One space

select COUNT(*)
from mytable
where col = ' ' -- Two spaces

select COUNT(*)
from mytable
where col = ' ' -- Three spaces


However, all three queries return the exact same records. Does Microsoft SQL Server not distinguish between the amount of spaces? How can I query exactly for one, two or more spaces?










share|improve this question















marked as duplicate by Salman A sql
Users with the  sql badge can single-handedly close sql questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Oct 3 at 7:36


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • dba.stackexchange.com/questions/10510/…
    – Ivan Starostin
    Oct 1 at 13:22










  • Its simple: looks into empty string. doesnt matter if its one or two spaces. try it this way 'value ' and check result set
    – Hadrian
    Oct 1 at 13:24










  • If SQL Server would adhere to Standard SQL it would be really simple:where col like ' '
    – dnoeth
    Oct 1 at 14:02












up vote
11
down vote

favorite
1









up vote
11
down vote

favorite
1






1






This question already has an answer here:



  • Why the SQL Server ignore the empty space at the end automatically?

    2 answers



I want to find out the records in which a certain column contains exactly one space and nothing else. So I wrote the first of the following queries:



select COUNT(*)
from mytable
where col = ' ' -- One space

select COUNT(*)
from mytable
where col = ' ' -- Two spaces

select COUNT(*)
from mytable
where col = ' ' -- Three spaces


However, all three queries return the exact same records. Does Microsoft SQL Server not distinguish between the amount of spaces? How can I query exactly for one, two or more spaces?










share|improve this question
















This question already has an answer here:



  • Why the SQL Server ignore the empty space at the end automatically?

    2 answers



I want to find out the records in which a certain column contains exactly one space and nothing else. So I wrote the first of the following queries:



select COUNT(*)
from mytable
where col = ' ' -- One space

select COUNT(*)
from mytable
where col = ' ' -- Two spaces

select COUNT(*)
from mytable
where col = ' ' -- Three spaces


However, all three queries return the exact same records. Does Microsoft SQL Server not distinguish between the amount of spaces? How can I query exactly for one, two or more spaces?





This question already has an answer here:



  • Why the SQL Server ignore the empty space at the end automatically?

    2 answers







sql sql-server






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 1 at 17:25









Peter Mortensen

13k1983111




13k1983111










asked Oct 1 at 13:20









Koruba

907




907




marked as duplicate by Salman A sql
Users with the  sql badge can single-handedly close sql questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Oct 3 at 7:36


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by Salman A sql
Users with the  sql badge can single-handedly close sql questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Oct 3 at 7:36


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • dba.stackexchange.com/questions/10510/…
    – Ivan Starostin
    Oct 1 at 13:22










  • Its simple: looks into empty string. doesnt matter if its one or two spaces. try it this way 'value ' and check result set
    – Hadrian
    Oct 1 at 13:24










  • If SQL Server would adhere to Standard SQL it would be really simple:where col like ' '
    – dnoeth
    Oct 1 at 14:02
















  • dba.stackexchange.com/questions/10510/…
    – Ivan Starostin
    Oct 1 at 13:22










  • Its simple: looks into empty string. doesnt matter if its one or two spaces. try it this way 'value ' and check result set
    – Hadrian
    Oct 1 at 13:24










  • If SQL Server would adhere to Standard SQL it would be really simple:where col like ' '
    – dnoeth
    Oct 1 at 14:02















dba.stackexchange.com/questions/10510/…
– Ivan Starostin
Oct 1 at 13:22




dba.stackexchange.com/questions/10510/…
– Ivan Starostin
Oct 1 at 13:22












Its simple: looks into empty string. doesnt matter if its one or two spaces. try it this way 'value ' and check result set
– Hadrian
Oct 1 at 13:24




Its simple: looks into empty string. doesnt matter if its one or two spaces. try it this way 'value ' and check result set
– Hadrian
Oct 1 at 13:24












If SQL Server would adhere to Standard SQL it would be really simple:where col like ' '
– dnoeth
Oct 1 at 14:02




If SQL Server would adhere to Standard SQL it would be really simple:where col like ' '
– dnoeth
Oct 1 at 14:02












4 Answers
4






active

oldest

votes

















up vote
7
down vote



accepted










Yes, it ignores trailing spaces in comparisons.



You can try to append a delimiting character.



SELECT count(*)
FROM mytable
WHERE col + 'X' = ' X';





share|improve this answer




















  • Technically the standard requires the shorter string be padded with spaces until it has the same length as the longer string. In practice though, I've never found a situation where that would produce a different outcome than trimming/ignoring the trailing spaces.
    – Damien_The_Unbeliever
    Oct 1 at 13:30







  • 4




    Unfortunately, this precludes the use of indexes.
    – Gordon Linoff
    Oct 1 at 13:59






  • 2




    @GordonLinoff Could that be solved with WHERE col = ' ' AND col+'X' = ' X'? The first part is indexed, then it applies the refinement.
    – Barmar
    Oct 1 at 15:48






  • 1




    @barmar . . . I would go with col = ' ' and len(col) = 1.
    – Gordon Linoff
    Oct 1 at 18:01










  • @Damien_The_Unbeliever An off the cuff first thought with no experimentation: Maybe unicode spaces?
    – Izkata
    Oct 1 at 18:11

















up vote
3
down vote













The link posted by Ivan Starostin in the comments of the OP provides a good explanation and I think it deserves a full answer instead of just a comment.



To summarize, try using LIKE instead of equality:



select COUNT(*)
from mytable
where col LIKE ' ' -- one space


And you can also use DATALENGTH to calculate how many bytes are in the field to double-check field length:



select col, DATALENGTH(col)
from mytable;


Please note that DATALENGTH will return a different value if col is a VARCHAR vs NVARCHAR. VARCHAR stores each character as 1 byte where NVARCHAR stores each character as 2 bytes since NVARCHAR is stored in Unicode.






share|improve this answer



























    up vote
    2
    down vote













    You can combine DATALENGTH clause with your query:



     select COUNT(*)
    from mytable
    where col = ' '
    and DATALENGTH(col) = 1





    share|improve this answer



























      up vote
      0
      down vote













      You can replace the single space with a single character (for exampe §) and then put this character in your where condition:



      declare @tmp table(col varchar(50))

      insert into @tmp values
      (' '),
      (' '),
      (' ')

      select COUNT(*) as one_space_count
      from @tmp
      where replace(col,' ','§')='§'

      select COUNT(*) as two_space_count
      from @tmp
      where replace(col,' ','§')='§§'

      select COUNT(*) as three_space_count
      from @tmp
      where replace(col,' ','§')='§§§'


      Results:



      enter image description here






      share|improve this answer



























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        7
        down vote



        accepted










        Yes, it ignores trailing spaces in comparisons.



        You can try to append a delimiting character.



        SELECT count(*)
        FROM mytable
        WHERE col + 'X' = ' X';





        share|improve this answer




















        • Technically the standard requires the shorter string be padded with spaces until it has the same length as the longer string. In practice though, I've never found a situation where that would produce a different outcome than trimming/ignoring the trailing spaces.
          – Damien_The_Unbeliever
          Oct 1 at 13:30







        • 4




          Unfortunately, this precludes the use of indexes.
          – Gordon Linoff
          Oct 1 at 13:59






        • 2




          @GordonLinoff Could that be solved with WHERE col = ' ' AND col+'X' = ' X'? The first part is indexed, then it applies the refinement.
          – Barmar
          Oct 1 at 15:48






        • 1




          @barmar . . . I would go with col = ' ' and len(col) = 1.
          – Gordon Linoff
          Oct 1 at 18:01










        • @Damien_The_Unbeliever An off the cuff first thought with no experimentation: Maybe unicode spaces?
          – Izkata
          Oct 1 at 18:11














        up vote
        7
        down vote



        accepted










        Yes, it ignores trailing spaces in comparisons.



        You can try to append a delimiting character.



        SELECT count(*)
        FROM mytable
        WHERE col + 'X' = ' X';





        share|improve this answer




















        • Technically the standard requires the shorter string be padded with spaces until it has the same length as the longer string. In practice though, I've never found a situation where that would produce a different outcome than trimming/ignoring the trailing spaces.
          – Damien_The_Unbeliever
          Oct 1 at 13:30







        • 4




          Unfortunately, this precludes the use of indexes.
          – Gordon Linoff
          Oct 1 at 13:59






        • 2




          @GordonLinoff Could that be solved with WHERE col = ' ' AND col+'X' = ' X'? The first part is indexed, then it applies the refinement.
          – Barmar
          Oct 1 at 15:48






        • 1




          @barmar . . . I would go with col = ' ' and len(col) = 1.
          – Gordon Linoff
          Oct 1 at 18:01










        • @Damien_The_Unbeliever An off the cuff first thought with no experimentation: Maybe unicode spaces?
          – Izkata
          Oct 1 at 18:11












        up vote
        7
        down vote



        accepted







        up vote
        7
        down vote



        accepted






        Yes, it ignores trailing spaces in comparisons.



        You can try to append a delimiting character.



        SELECT count(*)
        FROM mytable
        WHERE col + 'X' = ' X';





        share|improve this answer












        Yes, it ignores trailing spaces in comparisons.



        You can try to append a delimiting character.



        SELECT count(*)
        FROM mytable
        WHERE col + 'X' = ' X';






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Oct 1 at 13:25









        sticky bit

        10.7k51629




        10.7k51629











        • Technically the standard requires the shorter string be padded with spaces until it has the same length as the longer string. In practice though, I've never found a situation where that would produce a different outcome than trimming/ignoring the trailing spaces.
          – Damien_The_Unbeliever
          Oct 1 at 13:30







        • 4




          Unfortunately, this precludes the use of indexes.
          – Gordon Linoff
          Oct 1 at 13:59






        • 2




          @GordonLinoff Could that be solved with WHERE col = ' ' AND col+'X' = ' X'? The first part is indexed, then it applies the refinement.
          – Barmar
          Oct 1 at 15:48






        • 1




          @barmar . . . I would go with col = ' ' and len(col) = 1.
          – Gordon Linoff
          Oct 1 at 18:01










        • @Damien_The_Unbeliever An off the cuff first thought with no experimentation: Maybe unicode spaces?
          – Izkata
          Oct 1 at 18:11
















        • Technically the standard requires the shorter string be padded with spaces until it has the same length as the longer string. In practice though, I've never found a situation where that would produce a different outcome than trimming/ignoring the trailing spaces.
          – Damien_The_Unbeliever
          Oct 1 at 13:30







        • 4




          Unfortunately, this precludes the use of indexes.
          – Gordon Linoff
          Oct 1 at 13:59






        • 2




          @GordonLinoff Could that be solved with WHERE col = ' ' AND col+'X' = ' X'? The first part is indexed, then it applies the refinement.
          – Barmar
          Oct 1 at 15:48






        • 1




          @barmar . . . I would go with col = ' ' and len(col) = 1.
          – Gordon Linoff
          Oct 1 at 18:01










        • @Damien_The_Unbeliever An off the cuff first thought with no experimentation: Maybe unicode spaces?
          – Izkata
          Oct 1 at 18:11















        Technically the standard requires the shorter string be padded with spaces until it has the same length as the longer string. In practice though, I've never found a situation where that would produce a different outcome than trimming/ignoring the trailing spaces.
        – Damien_The_Unbeliever
        Oct 1 at 13:30





        Technically the standard requires the shorter string be padded with spaces until it has the same length as the longer string. In practice though, I've never found a situation where that would produce a different outcome than trimming/ignoring the trailing spaces.
        – Damien_The_Unbeliever
        Oct 1 at 13:30





        4




        4




        Unfortunately, this precludes the use of indexes.
        – Gordon Linoff
        Oct 1 at 13:59




        Unfortunately, this precludes the use of indexes.
        – Gordon Linoff
        Oct 1 at 13:59




        2




        2




        @GordonLinoff Could that be solved with WHERE col = ' ' AND col+'X' = ' X'? The first part is indexed, then it applies the refinement.
        – Barmar
        Oct 1 at 15:48




        @GordonLinoff Could that be solved with WHERE col = ' ' AND col+'X' = ' X'? The first part is indexed, then it applies the refinement.
        – Barmar
        Oct 1 at 15:48




        1




        1




        @barmar . . . I would go with col = ' ' and len(col) = 1.
        – Gordon Linoff
        Oct 1 at 18:01




        @barmar . . . I would go with col = ' ' and len(col) = 1.
        – Gordon Linoff
        Oct 1 at 18:01












        @Damien_The_Unbeliever An off the cuff first thought with no experimentation: Maybe unicode spaces?
        – Izkata
        Oct 1 at 18:11




        @Damien_The_Unbeliever An off the cuff first thought with no experimentation: Maybe unicode spaces?
        – Izkata
        Oct 1 at 18:11












        up vote
        3
        down vote













        The link posted by Ivan Starostin in the comments of the OP provides a good explanation and I think it deserves a full answer instead of just a comment.



        To summarize, try using LIKE instead of equality:



        select COUNT(*)
        from mytable
        where col LIKE ' ' -- one space


        And you can also use DATALENGTH to calculate how many bytes are in the field to double-check field length:



        select col, DATALENGTH(col)
        from mytable;


        Please note that DATALENGTH will return a different value if col is a VARCHAR vs NVARCHAR. VARCHAR stores each character as 1 byte where NVARCHAR stores each character as 2 bytes since NVARCHAR is stored in Unicode.






        share|improve this answer
























          up vote
          3
          down vote













          The link posted by Ivan Starostin in the comments of the OP provides a good explanation and I think it deserves a full answer instead of just a comment.



          To summarize, try using LIKE instead of equality:



          select COUNT(*)
          from mytable
          where col LIKE ' ' -- one space


          And you can also use DATALENGTH to calculate how many bytes are in the field to double-check field length:



          select col, DATALENGTH(col)
          from mytable;


          Please note that DATALENGTH will return a different value if col is a VARCHAR vs NVARCHAR. VARCHAR stores each character as 1 byte where NVARCHAR stores each character as 2 bytes since NVARCHAR is stored in Unicode.






          share|improve this answer






















            up vote
            3
            down vote










            up vote
            3
            down vote









            The link posted by Ivan Starostin in the comments of the OP provides a good explanation and I think it deserves a full answer instead of just a comment.



            To summarize, try using LIKE instead of equality:



            select COUNT(*)
            from mytable
            where col LIKE ' ' -- one space


            And you can also use DATALENGTH to calculate how many bytes are in the field to double-check field length:



            select col, DATALENGTH(col)
            from mytable;


            Please note that DATALENGTH will return a different value if col is a VARCHAR vs NVARCHAR. VARCHAR stores each character as 1 byte where NVARCHAR stores each character as 2 bytes since NVARCHAR is stored in Unicode.






            share|improve this answer












            The link posted by Ivan Starostin in the comments of the OP provides a good explanation and I think it deserves a full answer instead of just a comment.



            To summarize, try using LIKE instead of equality:



            select COUNT(*)
            from mytable
            where col LIKE ' ' -- one space


            And you can also use DATALENGTH to calculate how many bytes are in the field to double-check field length:



            select col, DATALENGTH(col)
            from mytable;


            Please note that DATALENGTH will return a different value if col is a VARCHAR vs NVARCHAR. VARCHAR stores each character as 1 byte where NVARCHAR stores each character as 2 bytes since NVARCHAR is stored in Unicode.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Oct 1 at 14:07









            Mike Bruesch

            4719




            4719




















                up vote
                2
                down vote













                You can combine DATALENGTH clause with your query:



                 select COUNT(*)
                from mytable
                where col = ' '
                and DATALENGTH(col) = 1





                share|improve this answer
























                  up vote
                  2
                  down vote













                  You can combine DATALENGTH clause with your query:



                   select COUNT(*)
                  from mytable
                  where col = ' '
                  and DATALENGTH(col) = 1





                  share|improve this answer






















                    up vote
                    2
                    down vote










                    up vote
                    2
                    down vote









                    You can combine DATALENGTH clause with your query:



                     select COUNT(*)
                    from mytable
                    where col = ' '
                    and DATALENGTH(col) = 1





                    share|improve this answer












                    You can combine DATALENGTH clause with your query:



                     select COUNT(*)
                    from mytable
                    where col = ' '
                    and DATALENGTH(col) = 1






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Oct 1 at 13:35









                    S.K.

                    2,022718




                    2,022718




















                        up vote
                        0
                        down vote













                        You can replace the single space with a single character (for exampe §) and then put this character in your where condition:



                        declare @tmp table(col varchar(50))

                        insert into @tmp values
                        (' '),
                        (' '),
                        (' ')

                        select COUNT(*) as one_space_count
                        from @tmp
                        where replace(col,' ','§')='§'

                        select COUNT(*) as two_space_count
                        from @tmp
                        where replace(col,' ','§')='§§'

                        select COUNT(*) as three_space_count
                        from @tmp
                        where replace(col,' ','§')='§§§'


                        Results:



                        enter image description here






                        share|improve this answer
























                          up vote
                          0
                          down vote













                          You can replace the single space with a single character (for exampe §) and then put this character in your where condition:



                          declare @tmp table(col varchar(50))

                          insert into @tmp values
                          (' '),
                          (' '),
                          (' ')

                          select COUNT(*) as one_space_count
                          from @tmp
                          where replace(col,' ','§')='§'

                          select COUNT(*) as two_space_count
                          from @tmp
                          where replace(col,' ','§')='§§'

                          select COUNT(*) as three_space_count
                          from @tmp
                          where replace(col,' ','§')='§§§'


                          Results:



                          enter image description here






                          share|improve this answer






















                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            You can replace the single space with a single character (for exampe §) and then put this character in your where condition:



                            declare @tmp table(col varchar(50))

                            insert into @tmp values
                            (' '),
                            (' '),
                            (' ')

                            select COUNT(*) as one_space_count
                            from @tmp
                            where replace(col,' ','§')='§'

                            select COUNT(*) as two_space_count
                            from @tmp
                            where replace(col,' ','§')='§§'

                            select COUNT(*) as three_space_count
                            from @tmp
                            where replace(col,' ','§')='§§§'


                            Results:



                            enter image description here






                            share|improve this answer












                            You can replace the single space with a single character (for exampe §) and then put this character in your where condition:



                            declare @tmp table(col varchar(50))

                            insert into @tmp values
                            (' '),
                            (' '),
                            (' ')

                            select COUNT(*) as one_space_count
                            from @tmp
                            where replace(col,' ','§')='§'

                            select COUNT(*) as two_space_count
                            from @tmp
                            where replace(col,' ','§')='§§'

                            select COUNT(*) as three_space_count
                            from @tmp
                            where replace(col,' ','§')='§§§'


                            Results:



                            enter image description here







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Oct 1 at 14:20









                            Andrea

                            6,952144249




                            6,952144249












                                Popular posts from this blog

                                How to check contact read email or not when send email to Individual?

                                Displaying single band from multi-band raster using QGIS

                                How many registers does an x86_64 CPU actually have?