Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding summary of inner query

Tags:

sql

sqlite

Problem understanding subquery

I do not understand this example from www.sqlitetutorial.net/sqlite-subquery : enter image description here

Only one number is returned by the inner query: 1422138358

enter image description here

But the average of this number is different:

enter image description here

So why is the average of 1422138358 not 1422138358? The two queries are not independent? If I remove "ORDER BY albumid" the result is the same:

enter image description here

Example data:
http://www.sqlitetutorial.net/sqlite-sample-database/

Edit: Ok, there is probably some integer overflow going on as the columns are integer, but I still don't understand why the example take the average of a single number? enter image description here

like image 310
Rasmus Larsen Avatar asked Nov 07 '22 20:11

Rasmus Larsen


1 Answers

Very possibly that it was a mistake

1) From the text you can see that they wanted to 'sum the size of an album' and you`re querying Tracks table, which supposedly have an album_ID column

2) You cannot use ORDER BY if you`re using only aggregation column such as

select SUM(bytes)
from Tracks
Order by albumID

because it has nothing to order it by from.

Also note that you cannot use order by in subqueries

Finally what was missing here was this remaining of the query :

Select AVG(album.size) as [avg(album.size)]
from (
select albumID,SUM(bytes) as size
from Tracks
GROUP BY albumID

) as album

You can learn more about subqueries here

And if you want to play around with these, heres the code that you can replicate and use it for further exercies on that website:

    CREATE TABLE tracks (AlbumID int,bytes int)
    CREATE TABLE albums (AlbumID int, title nvarchar(50))
    insert into Tracks values (1,2),(2,10),(3,15)
    Select AVG(album.size) as [avg(album.size)]
    from (
    select AlbumID,SUM(bytes) as size
    from tracks
    GROUP BY albumID

) as album

Hope it helps

like image 56
S4V1N Avatar answered Nov 15 '22 06:11

S4V1N