SQL Puzzle – SELECT ~ 1 : Guess the Answer

While waiting for an index rebuild process to complete a client of mine Comprehensive Database Performance Health Check recently asked me if I have any puzzles to discuss. Of course, I have one where you have to guess the answer for a simple select statement. Let us see if you can guess it correctly or not.

Before running the following select statement in SSMS, guess the answer.

SELECT ~ 1

Please note that right before 1 sign there is Tilde sign and not a minus sign.

Guess the Answer

Now, run the same select statement in any version of SQL Server Management Studio.

The answer is -2, now my question is that why the query above gives us an answer as -2 and not any other values. Please leave your answer in the comments section. I am very curious to know if you can find the answer to the same. I will publish answer to this puzzle sometime next week.

Technology Online

I hope you find these Learning paths helpful. If you have a Pluralsight subscription, you can watch it for free. If you do not have a Pluralsight subscription, you can still watch the course for FREE by signing up for a trial account. Please note that you do not need any credit card.

Reference: Pinal Dave (http://blog.SQLAuthority.com)

SQL Server
Previous Post
Solve Puzzle about Data type – SQL in Sixty Seconds #108
Next Post
SQL Puzzle – Unsolved CASE Expression

Related Posts

123 Comments. Leave new

  • Lyliana Calero
    April 14, 2021 10:02 pm

    it be very interesting, ~ ibitwise logical NOT for the expression, taking each bit in turn, then,
    in 2 bytes and in binary is

    1(decimal) = 01 (binary in 2 bytes)

    then logical NOT we have

    01 (binary) => – 10(binary not)

    in decimal is -2

    :D

    Reply
  • Ludo Bernaerts
    April 20, 2021 6:21 pm

    0000 0001 = Binary for 1, not 1 = ~ 1 = in binary 1111 1110 , this converted to decimal = -2

    Reply
  • Allen Shepard
    April 20, 2021 8:55 pm

    Perhaps not covernted but interpreted.
    You are right. to NOT each bit turns 0000 0001 into 1111 1110
    Then 1111 1110 is interpreted as -2 in signed integer or 254 in unsigned integer.
    This is also ASCII 254 or the black square.
    https://en.wikipedia.org/wiki/Two%27s_complement

    Reply

Leave a Reply

Menu
Exit mobile version