I have defined the following query:
select count((select * from producers)) from producers;
Assuming a producers table with 3 columns (A, B and C) and 2 rows:
A B C
-----
0 1 2
3 4 5
I’d expect the following output:
2
2
It doesn’t work. While the query itself is basically useless (even if it worked, it wouldn’t yield any useful output), I’d like to try to understand why this doesn’t run.
(select * from producers)
This would yield a list of rows with information on all the attributes on the producers table.
select count((select * from producers)) from producers;
This one will for each row on producers, show up the number 2 (the number of elements in producers).
Why doesn’t it work? SQL limitation? Is there anything wrong with the logic I’m following here?
Thanks
It is a limitation of SQL, as far as I know. Subqueries are not allowed in the
COUNTexpression. Obviously(select * from producers)is a subquery, so it’s not allowed there.I think your misunderstanding is that you’re thinking that you would call the function like
COUNT(SELECT * FROM producers)whereas in SQL it’s likeSELECT COUNT(*) FROM producers.Functions like
MAX,MIN,SUM, andCOUNTare aggregate functions, meaning that they take a scalar argument but execute once for each row, accumulating results every iteration. SoSELECT MAX(column) FROM tableexecutes theMAXfunction once for each row intable, while you might be thinking thatMAXexecutes once and gets passed in every row intable.Contrast this with operators like
IN,EXISTS,ANY, andALL, which have a subquery as an argument. They are effectively passed all the results of their subquery every time they are invoked.