select count(*);
October 26th, 2009Quick trivia: what is the result of running SELECT COUNT(*);
?
That’s right, no FROM
clause, just COUNT(*)
. The answer may be a little bit surprising, is SELECT 1;
the result is, as expected, 1. And SELECT 2;
will return 2. So SELECT COUNT(2);
returns, as expected, 1, after all it counts how many rows are in the result set. But SELECT COUNT(*);
has a certain smell of voo-doo to it. Ok, is the * project operator, but project from… what exactly? It feels eerie, like a count is materialized out of the blue.
How about SELECT COUNT(*) [MyTable]
. Well, that’s actually just a shortcut for SELECT COUNT(*) AS [MyTable]
, so it still returns 1 but in a column named MyTable
. Now you understand why my heart missed a bit when I checked how I initialized a replication subscription and I forgot to type in FROM
…
This is the reson I strongly suggest the usage of AS before alias name http://sqlblogcasts.com/blogs/madhivanan/archive/2007/11/14/should-alias-names-be-preceded-by-as.aspx
When I used to work with DB2 on iSeries, I remeber that a simple “SELECT COUNT(*)” wouldn’t work. Not event a simple “SELECT CURRENT_TIMESTAMP”.
On that DBMS you must always specify the FROM clause, and there’s a table on the SYSIBM library just to deal with this situation. The table is called SYSDUMMY1 and has just one row, so the right way of getting the system data was “SELECT CURRENT_TIMESTAMP FROM SYSIBM.SYSDUMMY1”.
I suggest you use ssms tools pack from Mladen.
Its a great freeware