Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL & PHP - Which is faster mysql_num_rows() or 'select count()'?

I'm just wondering which method is the most effective if I'm literally just wanting to get the number of rows in a table.

$res = mysql_query("SELECT count(*) as `number` FROM `table1`"); $count = mysql_fetch_result($res,0,'number'); 

or

$res = mysql_query("SELECT `ID` FROM `table1`"); $count = mysql_num_rows($res); 

Anyone done any decent testing on this?

like image 272
Joel Avatar asked Mar 20 '10 23:03

Joel


People also ask

What is SQL used for?

SQL is used to communicate with a database. According to ANSI (American National Standards Institute), it is the standard language for relational database management systems. SQL statements are used to perform tasks such as update data on a database, or retrieve data from a database.

Is SQL similar to Python?

SQL vs. The significant difference between SQL and Python is that SQL is used to access and extract data from a database. At the same time, Python is used to analyse and manipulate data by using regression tests, time-series tests, and other computations.

Is SQL easy to learn?

How Quickly Can You Learn SQL? Generally speaking, SQL is an easy language to learn. If you understand programming and already know some other languages, you can learn SQL in a few weeks. If you're a beginner, completely new to programming, it can take longer.

What is SQL for beginners?

SQL is a standard language for storing, manipulating and retrieving data in databases. Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other database systems.


1 Answers

mysql_query() transfers all result records from the MySQL into the php pcrocess before it returns (unlike mysql_unbufferd_query()). That alone would make the mysql_num_rows() version slower.

Furthermore for some engines (like MyISAM) MySQL can serve a Count(*) request from the index of the table without hitting the actual data. A SELECT * FROM foo on the other hand results in a full table scan and MySQL has to read every single dataset.

like image 119
VolkerK Avatar answered Sep 25 '22 02:09

VolkerK