What's the most efficient way to count rows in a table? - php

Is it more efficient to use:
$sql = 'SELECT COUNT(*) AS count FROM users';
$odbcResult = OdbcExec($sql);
#odbc_fetch_row($odbcResult);
$count = #odbc_result($odbcResult, 'count');
or to use:
$sql = 'SELECT * FROM users';
$odbcResult = OdbcExec($sql);
$count = odbc_num_rows($odbcResult);

The former. The server is doing the work. It may already know the answer without counting,
The later requires all the rows to be returned to your program over the network (and into memory).

Populate a table with 10^x elements with x>=6 and see the time that takes.

$sql = 'SELECT COUNT(id) AS count FROM users';
$odbcResult = OdbcExec($sql);
#odbc_fetch_row($odbcResult);
$count = #odbc_result($odbcResult, 'count');
or some other index field besides id. Its a little faster than COUNT(*), but the count method is the way to go. If you need to do something with the results, method 2 is faster, but only needing count this is the one you want.
-edit- Added keyword of index before field. True comment below, made the assumption that there was an id index column (should have an index somewhere at any rate)

The first method is definitely faster. But COUNT(id) being faster than COUNT(*) - questionable. They usually are exactly the same, and there are cases when COUNT(id) is actually slower (see: http://www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol/)

Related

Get the last Id from database to a string/Int variable

I have to get the biggest id to a string or an int variable.
That is how I'm doing it:
$sql = "SELECT id FROM table ORDER BY id DESC LIMIT 1";
$list = mysql_query($sql) or die (mysql_error());
$lst = mysql_fetch_array($list);
$resId= $lst[0];
ResId is that variable.
Is this going to work?
Is there a better way to do it?
There is no AUTO_INCREACMENT!
If you don't auto increment or in any other way organize your id:s, there is no way to know which was the last one. (Unless you get the last inserted id when you're doing an insert query.)
Your query returns the greatest id, but if you haven't structured your code/table so that the greatest id is the last - then it won't return the last id obviously (oh well, it could).
As for your question if it will work. Why don't you simply try it out? You're much more likely to learn from trying your self than asking people for answers all the time.
If last id is the biggest id (as I see from your query), then you can also use:
$q = 'select max(id) as max_id from `b_iblock_element`';
$q_res = mysql_query($q);
$row = mysql_fetch_assoc($q_res);
$max_id = intval($row['max_id']);
And don't forget that mysql_* functions are deprecated and will be removed soon.

Which MySQL query is effective to get the total number of records

To get the total number of records, I usually use this query:
$total= mysql_num_rows(mysql_query("SELECT id FROM t_statistic WHERE pageid = $pid"));
but I got one the other query like below:
$data = mysql_fetch_object(mysql_query("SELECT COUNT(id) AS num_rows FROM t_statistic WHERE pageid = $pid"));
$total = $data->num_rows;
Between the two queries above. Which is more quickly and effectively (when the total number of records in the millions)?
I prefer the second query. It gives you already the record count, while the first query gives you the list of IDs (not the count), although it has been filtered but there are some cases when ID exist more than once in the table.
The Second query is quick and efficient:
SELECT COUNT(id) AS num_rows FROM t_statistic WHERE pageid = $pid
If you know about query optimisation. The query will only keeps only count in memory while calculating the answer. And directly gives number of rows.
Where as first query:
SELECT id FROM t_statistic WHERE pageid = $pid
Keeps all the selected rows in memory. then number of rows are calculated in further operation.
So second query is best in both ways.
Definitely the second one.
Some engines, like MySQL can do a count just by looking at an index rather than the table's data.
I've used something like the following on databases with millions of records.
SELECT count(*) as `number` FROM `table1`;
Way faster than: mysql_num_rows($res);
BTW: The * in Count(*) basically means it won't look at the data, it will just count the records, as opposed to Count(colname).
1) SELECT COUNT(*) FROM t_statistic WHERE pageid = $pid" --> count(*) counts all rows
2)SELECT COUNT(id) FROM t_statistic WHERE pageid = $pid" --> COUNT(column) counts non-NULLs only
3) SELECT COUNT(1) FROM t_statistic WHERE pageid = $pid" -->COUNT(1) is the same as COUNT(*) because 1 is a non-null expressions
Your use of COUNT(*) or COUNT(column) should be based on the desired output only.
So. Finally we have result is count(column) is more faster compare to count(*) .

php sql multiple queries into one

Part of my page I have lots of small little queries, probably about 6 altogether, grabbing data from different tables. As an example:
$sql_result = mysql_query("SELECT * FROM votes WHERE voted_on='$p_id' AND vote=1", $db);
$votes_up = mysql_num_rows($sql_result);
$sql_result = mysql_query("SELECT * FROM votes WHERE voted_on='$p_id' AND vote=0", $db);
$votes_down = mysql_num_rows($sql_result);
$sql_result = mysql_query("SELECT * FROM kids WHERE (mother_id='$p_id' OR father_id='$p_id')", $db);
$kids = mysql_num_rows($sql_result);
Would it be better if these were all grabbed in one query to save trips to the database? One query is better than 6 isn't it?
Would it be some kind of JOIN or UNION?
Its not about number of queries but amount of useful datas you transfer. If you are running database on localhost, is better to let sql engine to solve queries instead computing results in additional programs. The same if you are thinking about who should be more bussy. Apache or mysql :)
Of course you can use some conditions:
SELECT catName,
SUM(IF(titles.langID=1, 1, 0)) AS english,
SUM(IF(titles.langID=2, 1, 0)) AS deutsch,
SUM(IF(titles.langID=3, 1, 0)) AS svensk,
SUM(IF(titles.langID=4, 1, 0)) AS norsk,
COUNT(*)
FROM titles, categories, languages
WHERE titles.catID = categories.catID
AND titles.langID = languages.
example used from MYSQL Bible :)
If you really want to lower the number of queries, you can put the first two together like this:
$sql_result = mysql_query("SELECT * FROM votes WHERE voted_on='$p_id'", $db);
while ($row = mysql_fetch_array($sql_result))
{
extract($row);
if ($vote=='0') ++$votes_up; else ++$votes_down;
}
The idea of joining tables is that these tables are expected to have something in between (a relation, for example).
Same is for the UNION SELECTS, which are prefered to be avoided.
If you want your solution to be clean and scalable in future, I suggest you to use mysqli, instead of mysql module of PHP.
Refer to: mysqli::multi_query. There is OOP variant, where you create mysqli object and call the function as method.
Then, your query should look like:
// I use ; as the default separator of queries, but it might be different in your case.
// The above could be set with sql statement: DELIMITER ;
$query = "
SELECT * FROM votes WHERE voted_on='$p_id' AND vote=1;
SELECT * FROM votes WHERE voted_on='$p_id' AND vote=0;
SELECT * FROM kids WHERE (mother_id='$p_id' OR father_id='$p_id');
";
$results = mysqli_multi_query($db, $query); // Returns an array of results
Fewer queries are (generally, not always) better, but it's also about keeping your code clear enough that others can understand the query. For example, in the code you provided, keep the first two together, and leave the last one separate.
$sql_result = mysql_query("SELECT vote, COUNT(*) AS vote_count
FROM votes
WHERE voted_on='$p_id'
GROUP BY vote", $db);
The above will return to you two rows, each containing the vote value (0 or 1) and the vote count for the value.

how to return array for mysql_query?

// make empty array
$sqlArray=array();
$jsonArray=array();
// START NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// first 20 vistors
$query = "SELECT user_id FROM vistors LIMIT 20";
$result = mysql_query ($query) or die ($query);
// make vistors user query array
while ($vstr_line = mysql_fetch_array($result)){
array_push($sqlArray, $vstr_line['user_id']);
}
// implode vistors user array
$sqlArray_impl = implode("', '", $sqlArray);
// END NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN ('$sqlArray_impl')";
$qry_result = mysql_query($query) or die($query);
while ($usr_line = mysql_fetch_array($qry_result)){
array_push($jsonArray, $usr_line['id'].' - '.$usr_line['username'].' - '.$usr_line['picture']);
}
print_r($sqlArray);
echo '<br><br>';
print_r($jsonArray);
see this my functions..
i need a replacement for fast working alternatives..
function within the range specified above, to me, running faster than the alternative.
the query will return back array ?
thx for all helpers !
Can you use a JOIN or SUB SELECT to reduce the query count from 2 to 1? Might not give much of a boost but worth a shot and a cleaner implementation.
Where is the bottleneck? Most likely the db and not the php code.
Are the tables/columns properly indexed? Run EXPLAIN on both queries.
Easiest would be to include first query as subquery eliminating one turn to the DB and a lot of code:
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN (SELECT user_id FROM vistors LIMIT 20)";
$qry_result = mysql_query($query) or die($query);
Unless there is more reason to have the first one seperate, but that is not visible in your code example.
If you use PDO (recommended anyway...), you can return the result array all at once using fetchAll().
For your second query, you can use string concatenation in MySQL to directly return the result you want.

Faster way to know the total number of rows in MySQL database?

If I need to know the total number of rows in a table of database I do something like this:
$query = "SELECT * FROM tablename WHERE link='1';";
$result = mysql_query($query);
$count = mysql_num_rows($result);
Updated: I made a mistake, above is my actual way. I apologize to all
So you see the total number of data is recovered scanning through the entire database.
Is there a better way?
$query = "SELECT COUNT(*) FROM tablename WHERE link = '1'";
$result = mysql_query($query);
$count = mysql_result($result, 0);
This means you aren't transferring all your data between the database and PHP, which is obviously a huge waste of time and resources.
For what it's worth, your code wouldn't actually count the number of rows - it'd give you 2x the number of columns, as you're counting the number of items in an array representing a single row (and mysql_fetch_array gives you two entries in the array per column - one numerical and one for the column name)
SELECT COUNT(*) FROM tablename WHERE link='1';
You could just do :
SELECT count(*) FROM tablename;
for your query. The result will be a single column containing the number of rows.
If I need to know the total number of rows in a table of database
Maybe I'm missing something here but if you just want to get the total number of rows in a table you don't need a WHERE condition. Just do this:
SELECT COUNT(*) FROM tablename
With the WHERE condition you will only be counting the number of rows that meet this condition.
use below code
$qry=SHOW TABLES FROM 'database_name';
$res=mysql_query($qry);
$output=array();
$i=0;
while($row=mysql_fetch_array($res,MYSQL_NUM)){
++$i;
$sql=SELECT COUNT(*) FROM $row[0];
$output[$i]=mysql_query($sql);
}
$totalRows=array_sum($ouptput);
echo $totalRows;
http://php.net/manual/en/function.mysql-num-rows.php You need this i think.
If you are going to use the following SQL statement:
SELECT COUNT(*) FROM tablename WHERE link='1';
Make sure you have an index on the 'link' column

Categories