Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2012
    Posts
    1

    Unanswered: Conditional count from sql queries

    Hi there,

    is it possible to do this?

    Select count(enabled = 1) from user

  2. #2
    Join Date
    Nov 2004
    Location
    out on a limb
    Posts
    13,692
    Provided Answers: 59
    yes, but not as you have styled it
    MySQL :: MySQL 5.0 Reference Manual :: 13.2.8 SELECT Syntax
    use a SELECT to select the columns
    use count to aggregate a column
    use a WHERE clause to limit the rows processed
    I'd rather be riding on the Tiger 800 or the Norton

  3. #3
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    Quote Originally Posted by alvin567 View Post
    is it possible to do this?
    of course it's possible -- it will not generate a syntax error

    (at least, not in mysql -- in other databases, you might have to use a CASE expression)

    however...

    it may not do what you think it does

    for questions like this, it's a good idea to get in the habit of running a simple test yourself

    here, allow me to help you by giving you this free script --
    Code:
    CREATE TABLE conditional
    ( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT
    , foo VARCHAR(37)
    , enabled TINYINT
    );
    INSERT INTO conditional ( foo , enabled ) VALUES
     ( 'curly'     , 0 )
    ,( 'larry'     , 1 )
    ,( 'moe'       , 1 )
    ,( 'shemp'     , 1 )
    ,( 'joe'       , NULL )
    ,( 'curly joe' , NULL )
    ;
    SELECT COUNT(*) AS rows
         , COUNT( enabled ) AS not_null
         , COUNT( enabled = 1 ) AS conditional
      FROM conditional;
    okay, when you ran this, what did you get?

    do you understand why you got what you did?
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •