From the course: Learning SQL Programming

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Grouping results

Grouping results - SQL Tutorial

From the course: Learning SQL Programming

Start my 1-month free trial

Grouping results

- [Instructor] When we need to divide results in various ways, we can use the GROUP BY keyword to change the way that a query works. Let's say we wanted to count up how many of each first name we have in our database. I'll write SELECT first_name, COUNT (first_name) FROM people. That should work, right? Hmm. That's a lot of Jameses. Why isn't this working like I expect? That's because when we ask the database to give us a count of the items in the first name field, we get one result, the number 1,000, and then that informs the size of the response, so we just get the first name value from the last record in the set. But if we add a clause to the end using the GROUP BY keyword, we can tell the database to run our SELECT clause against each individual grouping by the field that we specify. So I'll add that on the end here. At the end of the query, I'll write GROUP BY first_name, and then I'll run the query again. And that looks like what we want. This is a count of how many times each…

Contents