Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I'm currently learning how to build a site in PHP mysql. However, I seem to fail to understand COUNT() as count and wouldn't mind some further explanation.

I get the principles of COUNT, 0 || 1, and how it returns all the values that pertain to that query. But, don't see how COUNT as count works.

Anyhow, this is how the code I'm writing goes - so we have a working example - and where I first became perplexed.

SELECT COUNT(`id`) as `count`, 
       `id` 
FROM `user` 
WHERE `email`='$email' 
AND `password`='".md5$password."'";

If anyone can explain be a great help!

share|improve this question
add comment

2 Answers 2

up vote 9 down vote accepted

That is called a column alias.

An alias is used to give columns a new name for the result set. This can be used to name a column based on an expressions (because otherwise the expression wouldn't "have" a name) or to rename columns, e.g. because the select list contains columns from different tables with the same name:

select t1.foo as t1_foo,
       t2.foo as t2_foo
from t1
   join t2 on ...

returns a result with the columns t1_foo and t2_foo

or

select avg(salary) as avg_salary
from employees

Btw: using a reserved word as an object name (count) isn't such a good idea in the first place.

share|improve this answer
    
Thanks for the help – yep understood alias', was just a bit baffled as to why the example used count – as you point out it is a reserved. –  edlee Apr 30 '13 at 12:44
add comment
$query = "select count(*) as `count` from tbl_name";
$result = mysql_query($query);
$data = mysql_fetch_array($result);

Now you can easily get the value of count as

echo $data['count'];

instead of

echo $data['count(*)'];

So as you see count is just an alias of count(*).

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.