0

I use oracle 11g , so i read alot of artics about it but i dont understand how exactly its happened in database , so lets say that have two tables:

select * from Employee

result is here

select * from student

result is here

so when we want to make group by in multi columns :

SELECT SUBJECT, YEAR, Count(*)
FROM Student
GROUP BY SUBJECT, YEAR;

so my question is: what exactly happened in database ? i mean the query count(*) do first in every column in group by and then sort it ? or what? can any one explain it in details ?.

Hadi
  • 36,233
  • 13
  • 65
  • 124
learn2222
  • 25
  • 3
  • It counts the number of occurrences of every unique combination of subject and year. – Joakim Danielson Mar 30 '19 at 21:17
  • Possible duplicate of [How does GROUP BY work?](https://stackoverflow.com/questions/7434657/how-does-group-by-work) – GMB Mar 30 '19 at 21:32
  • guys i already read this :https://stackoverflow.com/questions/7434657/how-does-group-by-work but i dont understand too , so please dont close it !! @JoakimDanielson – learn2222 Mar 30 '19 at 21:40

1 Answers1

1

SQL is a descriptive language, not a procedural language.

What the query does is determine all rows in the original data where the group by keys are the same. It then reduces them to one row.

For example, in your data, these all have the same data:

subject   year    name
English    1      Harsh
English    1      Pratik
English    1      Ramesh

You are saying to group by subject, year, so these become:

Subject    Year   Count(*)
English    1      3

Often, this aggregation is implemented using sorting. However, that is up to the database -- and there are many other algorithms. You cannot assume that the database will sort the data. But, if it easier for you to think of it, you can think of the data being sorted by the group by keys, in order to identify the groups. Just one caution, the returned values are not necessarily in any particular order (unless your query includes an order by).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786