Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is the use of COUNT() function in MySQL?

    • 0
    • 1
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 498
    Comment on it

    In MySQL, COUNT() function used to return the number of rows that matches with a specified criteria.

    Syntax:

    COUNT(column_name)

    When we use COUNT(column_name) function in select query it returns the number of rows for the specified column:

    SELECT COUNT(column_name) FROM table_name;
    

    COUNT(*)

    When we use COUNT(column_name) function in select query it returns the number of records in a table:

    SELECT COUNT(*) FROM table_name;
    

    COUNT(DISTINCT column_name)

    When we use COUNT(DISTINCT column_name) function in select query it returns the number of rows(distinct values) of the specified column:

    SELECT COUNT(DISTINCT column_name) FROM table_name;
    

    Example:

    We have a table "user" as below:

        user
        id  first_name            last_name       country
        .......................................................
        1   John                     Simp         Canada
        2   Chris                    Hely         Korea
        3   Joy                      Roy          Canada
        4   Jenny                    Mill         Canada
    

    COUNT(column_name)

    The below query counts the number of user where country is Canada from the "user" table:

    SELECT COUNT(country) AS count FROM user
    WHERE country="Canada";
    

    Result

    count
    ........
    3
    

    COUNT(*)

    The below query counts the total number of users in the "user" table:

    SELECT COUNT(*) AS totalUser FROM users;
    

    Result

    totalUser
    ........
    4
    

    COUNT(DISTINCT column_name) Example

    The below query counts the number of unique users in the "user" table:

    SELECT COUNT(DISTINCT country) AS count FROM Orders;

    Result

    count
    ........
    2
    

    Hope this will help you :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: