SQL Counting Rows

Counting All Rows:

To count all rows in a table, you can use the following query:

                                  
                                    SELECT COUNT(*) FROM table_name;
                                  
                                

Replace table_name with the name of your table. This will give you the total number of rows in the table.


Example:

Assuming you have a table called "employees":

                                  
                                    CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    department VARCHAR(50),
    salary DECIMAL(10, 2)
);

INSERT INTO employees VALUES
    (1, 'John', 'Doe', 'HR', 50000.00),
    (2, 'Jane', 'Smith', 'IT', 60000.00),
    (3, 'Bob', 'Johnson', 'Finance', 55000.00);              
                                  
                                

To count all rows in the employees table:

                                
                                    SELECT COUNT(*) FROM employees;
                                
                              

COUNT(*)
3

Counting Rows Based on a Condition:

To count rows based on a condition, use the COUNT function with a WHERE clause:

                                  
                                    SELECT COUNT(*) FROM employees WHERE department = 'IT';
                                  
                                

This will give you the count of employees in the IT department.


Counting Distinct Values:

You can use COUNT(DISTINCT column_name) to count the number of distinct values in a column:

                                  
                                    SELECT COUNT(DISTINCT department) FROM employees;
                                  
                                

This will give you the count of distinct departments in the employees table.


Tips:

  • COUNT(*) counts all rows.
  • Use COUNT(column_name) to count non-null values in a specific column.
  • Use COUNT(DISTINCT column_name) to count distinct values in a column.
  • Combine COUNT with other aggregate functions or conditions as needed.