Note that there are some explanatory texts on larger screens.

plurals
  1. POIs converting everything to varbinary the correct way to compare character data?
    primarykey
    data
    text
    <p>I was using a MIN function to compare character data in a column that allowed nulls, with disastrous results. ;-) Here's a much simplified example that shows the same kind of thing:</p> <ol> <li><p>Determine the number of rows in sys.indexes:</p> <pre><code>select count(*) from sys.indexes; </code></pre></li> <li><p>Run this SQL:</p> <pre><code>select count(name), substring(cast(min(name) as varbinary),1,1) from sys.indexes; </code></pre> <p>If count matches #1, stop here. Try a different database (with more objects) instead.</p></li> <li><p>Go to the Messages tab. You should see: Warning: Null value is eliminated by an aggregate or other SET operation.</p></li> <li><p>How would you handle the nulls in the "name" column in order to resolve that Warning? with coalesce?</p></li> <li><p>Replace "name" with "coalesce(name,char(0x7e))" and run the SQL:</p> <pre><code>select count(coalesce(name,char(0x7e))), substring(cast(min(coalesce(name,char(0x7e))) as varbinary),1,1) from sys.indexes; </code></pre></li> <li><p>Note the result of the MIN function in #5 (0x7e rather than 0x63).</p></li> </ol> <p>Questions:</p> <p>A. Is coalesce the proper way to handle the Warning and missing (null) data per #4?</p> <p>B. Since the result in #6 is not what's expected, what is the correct way to compare character data in SQL Server? Convert everything to varbinary?</p> <p>[Edited...]</p> <p>In the discussions below, there was some confusion and discussion about the relationship between the null replacement via COALESCE and the results of the comparisons. The relationship between the two is this: when you select a string (including a single character) as a null replacement placeholder (steps #4 and #5 above), that string must satisfy the expected results of the comparison(s) that are being performed against values of other data in the query. With some collations, finding a suitable string may be more difficult than with other collations.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload