Перейти к содержимому

Как узнать сколько записей в таблице sql

  • автор:

Count table rows

What is the MySQL command to retrieve the count of records in a table?

TimCodes.NET's user avatar

12 Answers 12

will count the number of rows in the table.

Because nobody mentioned it:

lists all tables along with some additional information, including estimated rows for each table. This is what phpMyAdmin is using for its database page.

This information is available in MySQL 4, probably in MySQL 3.23 too — long time prior information schema database.

The number shown is estimated for InnoDB and TokuDB but it is absolutely correct for MyISAM and Aria (Maria) storage engines.

The number of rows. Some storage engines, such as MyISAM, store the exact count. For other storage engines, such as InnoDB, this value is an approximation, and may vary from the actual value by as much as 40% to 50%. In such cases, use SELECT COUNT(*) to obtain an accurate count.

This also is fastest way to see the row count on MySQL, because query like:

Doing full table scan what could be very expensive operation that might take hours on large high load server. It also increase disk I/O.

The same operation might block the table for inserts and updates — this happen only on exotic storage engines.

SQL COUNT()

In this tutorial, you will learn about the SQL COUNT() function with the help of examples.

The SQL COUNT() function returns the number of rows in the result set.

Example

Here, the above SQL command counts and returns the number of rows in the Orders table.

Count() Syntax

The syntax of the SQL COUNT() function is:

  • COUNT is the function to count the number of rows in a table
  • table is the name of the table whose number of rows is to be counted

Here, the above SQL command counts and returns the number of rows in the Customers table.

How to use COUNT() Function in SQL

Example: SQL COUNT() Function

Aliases With COUNT()

In the above example, the field name in the result set is COUNT(*) .

It is also possible to give custom names to these fields using the AS keyword. For example,

Here, the field name COUNT(*) is replaced by total_customers in the result set.

How to use alias in SQL with COUNT() function

Example: COUNT() in SQL with Alias

COUNT() With WHERE

We can use COUNT() with WHERE to count rows that have certain column values:

Here, the SQL command returns the count of customers whose country is UK.

How to use COUNT() with WHERE in SQL

Example: SQL COUNT() Function with WHERE

COUNT() With DISTINCT

If we need to count the number of unique rows, we can use the COUNT() function with the DISTINCT clause. For example,

Here, the SQL command returns the count of unique countries.

DISTINCT and COUNT used together to count unique values

Example: Counting unique countries

COUNT() With GROUP BY

The COUNT() function can be used with the GROUP BY clause to count the rows with similar values. For example,

Here, the SQL command returns the number of customers in each country.

How to use COUNT() Function with GROUP BY in SQL

Example: SQL COUNT() Function with GROUP BY

SQL SELECT statement with COUNT() function

SQL SELECT statement with COUNT() function

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Hey, folks! In this article, we will be focusing on SQL SELECT statement along with COUNT() function.

What is SQL SELECT statement?

SQL SELECT statement helps us select and display the data values from the particular table of the database.

Syntax:

Example:

SELECT * statement helps select all the data values from the provided table.

Output:

What is SQL COUNT() function?

SQL COUNT() function counts the total number of rows present in the database.

Syntax:

Example:

In this example, we have displayed the count of all the data rows under the column — ‘city’ of table — ‘Info’.

Output:

Variations of SQL SELECT statement with COUNT() function

You can use the SQL SELECT statement with the COUNT() function to select and display the count of rows in a table of a database.

Along with this, we can club SQL SELECT statement with COUNT() function in various different ways.

Having understood the working of SQL SELECT COUNT(), let us now understand different variations associated with the same through examples.

Examples of SQL SELECT with COUNT() function

To display the variations in SQL SELECT COUNT(), we have used SQL CREATE query to create a Table and SQL INSERT query to input data to the database.

We will be using the below table and its data in the further examples.

Output:

1. SQL SELECT COUNT with WHERE clause

SQL SELECT COUNT() can be clubbed with SQL WHERE clause.

Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.

Example:

Output:

2. SQL SELECT COUNT(*) function

SQL SELECT statement can be used along with COUNT(*) function to count and display the data values.

The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).

Example:

Output:

3. SQL SELECT COUNT with DISTINCT clause

The DISTINCT clause helps exclude the redundant data and displays only the unique values from the selected column.

SQL SELECT COUNT() function can be used along with DISTINCT clause to count and display the number of rows representing unique(non-repeated) values.

Example:

Output:

4. SQL SELECT COUNT with HAVING and GROUP BY clause

SQL SELECT COUNT() function can be clubbed with GROUP BY and HAVING clause to add conditions before the selection of data as well as grouping of data rows by a particular column value.

Example:

Output:

Conclusion

By this, we have come to an end of this topic. Please feel free to comment below in case you come across any doubt.

For more such posts related to SQL, please do visit SQL JournalDev.

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Как узнать сколько записей в таблице sql

Агрегатные функции вычисляют некоторые скалярные значения в наборе строк. В MySQL есть следующие агрегатные функции:

AVG : вычисляет среднее значение

SUM : вычисляет сумму значений

MIN : вычисляет наименьшее значение

MAX : вычисляет наибольшее значение

COUNT : вычисляет количество строк в запросе

Все агрегатные функции принимают в качестве параметра выражение, которое представляет критерий для определения значений. Зачастую, в качестве выражения выступает название столбца, над значениями которого надо проводить вычисления.

Выражения в функциях AVG и SUM должно представлять числовое значение (например, столбец, который хранит числовые значения). Выражение в функциях MIN , MAX и COUNT может представлять числовое или строковое значение или дату.

Все агрегатные функции за исключением COUNT(*) игнорируют значения NULL.

Функция Avg возвращает среднее значение на диапазоне значений столбца таблицы.

Например, пусть есть следующая таблица товаров Products:

Найдем среднюю цену товаров из базы данных:

Для поиска среднего значения в качестве выражения в функцию передается столбец Price. Для получаемого значения устанавливается псевдоним Average_Price, хотя в принципе устанавливать псевдоним необязательно.

Функция avg и поиск среднего значения в MySQL

На этапе выборки можно применять фильтрацию. Например, найдем среднюю цену для товаров определенного производителя:

Также можно находить среднее значение для более сложных выражений. Например, найдем среднюю сумму всех товаров, учитывая их количество:

Count

Функция Count вычисляет количество строк в выборке. Есть две формы этой функции. Первая форма COUNT(*) подсчитывает число строк в выборке:

Функция count в MySQL и вычисление количества строк

Вторая форма функции вычисляет количество строк по определенному столбцу, при этом строки со значениями NULL игнорируются:

Min и Max

Функции Min и Max вычисляют минимальное и максимальное значение по столбцу соответственно. Например, найдем минимальную цену среди товаров:

MIN и MAX в MySQL

Данные функции также игнорируют значения NULL и не учитывают их при подсчете.

Функция Sum вычисляет сумму значений столбца. Например, подсчитаем общее количество товаров:

Также вместо имени столбца может передаваться вычисляемое выражение. Например, найдем общую стоимость всех имеющихся товаров:

All и Distinct

По умолчанию все вышеперечисленных пять функций учитывают все строки выборки для вычисления результата. Но выборка может содержать повторяющие значения. Если необходимо выполнить вычисления только над уникальными значениями, исключив из набора значений повторяющиеся данные, то для этого применяется оператор DISTINCT .

По умолчанию вместо DISTINCT применяется оператор ALL , который выбирает все строки:

В данном случае мы видим, что производители могут повторяться в таблице, так как некоторые товары могут иметь одних и тех же производителей. Поэтому чтобы подсчитать количество уникальных производителей, необходимо использовать оператор DISTINCT.

Так как этот оператор неявно подразумевается при отсутствии DISTINCT, то его можно не указывать.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Car Rental HPN Inside the Terminal