Currious thing about Count

  • I accidently had an unfinished piece of SQL code in my query window during execution. The code was

    select count(*)

    Now to my supprise it returned 1. Anyone know why it returns 1? The only thing i can think of is that its counting itself.

    /T

  • tommyh (7/24/2013)


    I accidently had an unfinished piece of SQL code in my query window during execution. The code was

    select count(*)

    Now to my supprise it returned 1. Anyone know why it returns 1? The only thing i can think of is that its counting itself.

    /T

    Yes. That is a nature of COUNT(*) as it returns number of affected rows.

    If you execute SELECT 'A' - it returns 1 row with 'A' in it.

    For SELECT COUNT(*), SQL Server can see that only one row will be returned so: it returns 1.

    Sometime, you may hear the question on interview: What is the shortest select query which will return 1 without using digits/numbers. In this question, most of interviewers are actually expecting this SELECT COUNT(*) thing. Althought it's not the shortest SELECT query to do so, it's a most expected one.

    P.S. There are few shorter ways to get 1 returned:

    SELECT DAY($)

    or

    SELECT EXP(£)

    😉

    _____________________________________________
    "The only true wisdom is in knowing you know nothing"
    "O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D
    (So many miracle inventions provided by MS to us...)

    How to post your question to get the best and quick help[/url]

  • I'm not sure what the point of this interview question would be, since in the real world if you needed a query that always returned 1 you would use SELECT 1.

  • dan-572483 (7/24/2013)


    I'm not sure what the point of this interview question would be, since in the real world if you needed a query that always returned 1 you would use SELECT 1.

    There is none!

    As well as in many other common interview questions...

    _____________________________________________
    "The only true wisdom is in knowing you know nothing"
    "O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D
    (So many miracle inventions provided by MS to us...)

    How to post your question to get the best and quick help[/url]

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply