A select statement cannot include both a group by and an order by clause.

Error ORA-00937 occurs when the GROUP BY command is improperly used. The GROUP BY command allows the user to view rows having a common field value in a single row. For example, a small business CEO wants to view employees who worked the highest number of hours by department last month. Another instance could be when a school superintendent wants to view students on the honor roll by homeroom. In such cases, the user may run a GROUP BY statement to view the results.

GROUP BY is used in conjunction with aggregate functions to filter the results by a value. The GROUP BY command can be very useful for viewing a select set of results. It is commonly used, which deems it essential to utilize the proper syntax when running the statement.      

The Problem

When faced with ORA-00923, the error message you will see is

ORA-00923: not a single-group group function

Oracle documentation states the cause as the following:

A SELECT list cannot include both a group function, such as AVG, COUNT, MAX, MIN, SUM, STDDEV, or VARIANCE, and an individual column expression, unless the individual column expression is included in a GROUP BY clause.

In other words, you tried to execute a SELECT statement that requires a GROUP BY clause without including the GROUP BY clause. If you are using an aggregate function in your select query (e.g. AVG, COUNT, MAX, MIN…), you must have a GROUP BY clause.

The Solution

To resolve the error, you can either remove the group function or column expression from the SELECT clause or you can add a GROUP BY clause that includes the column expressions.

If you choose to add the GROUP BY clause, make sure to include the column expressions and follow the correct order. Take the example of the small business CEO who wants to view a list of employees who worked the most number of hours, organized by department. The correct syntax that includes the GROUP BY clause would be

SELECT department, MAX(hours) AS “most hours”

FROM employees

GROUP BY department;

Looking Forward 

Remember, if you are using an aggregate function in your select query then you must also have a GROUP BY clause. You cannot refer to a nonaggregated column in SELECT that is not also named in the GROUP BY clause. For the query to run successfully you must either remove the group function or column expression from SELECT or you must add a GROUP BY clause that includes the column expression.

Following this rule and ensuring proper query syntax should prevent error ORA-00937 from occurring in the future. Even though the process of correcting this error is not too difficult, contact your database administrator or licensed Oracle consultant if you continue to face problems with ORA-00937.

Are you making these errors with GROUP BY in SQL? Find out what they are, how to avoid them, and how to fix them.

SQL’s

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 statement can quickly uncover powerful data insights. At first, using
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 can seem easy – e.g. when creating basic SQL reports that you’ll present to business decision-makers. But while learning this powerful feature, you could become trapped in weird errors or get incorrect results caused by improperly written
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 statements. If you’re feeling like things aren’t quite adding up with your use of GROUP BY, keep reading. In this article, I will explain the most common
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 mistakes and how you can avoid them.

Stop Making These 7 Common GROUP BY Mistakes

1. Forgetting GROUP BY with Aggregate Functions

You use

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
WHERE count(*) > 10 
GROUP BY meal_category ;
1 statements with the
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 clause when you want to group and organize rows into specific groups and then perform a specific calculation of each group.

The most common

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 error is forgetting to write
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 inside the SELECT statement.

Here is one example. Imagine that you have the table recipes, which contains 100 records and six columns. This table stores the number of views (

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
WHERE count(*) > 10 
GROUP BY meal_category ;
5) per each recipe published on a famous culinary website:

meal_categorynameauthorno_of_viewsno_of_views_lst_mthauthor_idCold appetizerMarinated CheeseMarta107104906211SoupsPumpkin soupJohn68856693772dessertsBanana CheesecakeAlly131944NULL3drinksPaloma PicanteLuke72027713124Bread and pastrySour Cream DoughnutsJohn50935527912dessertsReal Strawberry CupcakesLisa17626811693911Soupspotato soupMary64796643886......................................................Bread and pastryCider DoughnutsTim53896511608

recipe table

Here is a short description of the table’s columns:

  • SELECT 
      meal_category,
      count(*) AS total_recipes 
    FROM recipes
    WHERE count(*) > 10 
    GROUP BY meal_category ;
    
    6 – The recipe category (soup, drinks, desserts, etc.).
  • SELECT 
      meal_category,
      count(*) AS total_recipes 
    FROM recipes
    WHERE count(*) > 10 
    GROUP BY meal_category ;
    
    7 – The recipe’s name.
  • SELECT 
      meal_category,
      count(*) AS total_recipes 
    FROM recipes
    WHERE count(*) > 10 
    GROUP BY meal_category ;
    
    8 – The author’s name.
  • SELECT 
      meal_category,
      count(*) AS total_recipes 
    FROM recipes
    WHERE count(*) > 10 
    GROUP BY meal_category ;
    
    5 – The number of views (total pages/recipes viewed) in the current month.
  • SELECT 
      meal_category,
      count(*) AS total_recipes 
    FROM recipes
               GROUP BY meal_category
    HAVING count(*) > 10  ;
    
    0 – The number of views (total pages/recipes viewed) in the previous month.
  • SELECT 
      meal_category,
      count(*) AS total_recipes 
    FROM recipes
               GROUP BY meal_category
    HAVING count(*) > 10  ;
    
    1 – The author’s unique ID number.

Let's say that you want to count the number of recipes in each meal category. If you write the statement like this (without

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 at the end) ...

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes ;

... most SQL engines will give you an error. Some engines, however, will output weird, unwanted results. I’m using MySQL and when I run this statement, I get this:

meal_categorytotal_recipesCold appetizer100

Result without GROUP BY

100 is the total count of all the recipes in the whole data set and the meal category ‘Cold appetizer’ is just one category out of ten. To correct this type of error, you need to add a

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
3 at the end of the statement. (Otherwise, your result in MySQL just doesn't make sense.)

The correct SELECT looks like this:

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;

Here is a short explanation of what’s going on:

  • Records are merged based on meal category. For example, desserts are one group, soups another, main dishes yet another, etc. The column
    SELECT 
      meal_category,
      count(*) AS total_recipes 
    FROM recipes
    WHERE count(*) > 10 
    GROUP BY meal_category ;
    
    6 is specified after
    SELECT 
      meal_category,
      count(*) AS total_recipes 
    FROM recipes
    GROUP BY meal_category ;
    
    7; it is also listed in
    SELECT 
      meal_category,
      count(*) AS total_recipes 
    FROM recipes
    WHERE count(*) > 10 
    GROUP BY meal_category ;
    
    1.
  • For each group, we are using
    SELECT 
      meal_category,
      count(*) AS total_recipes 
    FROM recipes
               GROUP BY meal_category
    HAVING count(*) > 10  ;
    
    7 to count the total number of recipes in that group.

I'm not going to dive deeply into the syntax here, but I would definitely suggest you read GROUP BY in SQL Explained or Using GROUP BY in SQL for more details.

As you can see, the result is like we expected:

meal_categorytotal_recipesBread and pastry7Cold appetizer6desserts20drinks7Main dishes20Salads8Side dishes12Soups17Warm appetizer3

Valid GROUP BY result

2. Confusing WHERE and HAVING

Maybe you’d like to see only those meal categories that have more than 10 recipes. A  lot of beginners would write this query:

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
WHERE count(*) > 10 
GROUP BY meal_category ;

This statement will return an error because you cannot use aggregate functions in a

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
8 clause.
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
8 is used with
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 when you want to filter rows before grouping them.

In our example, we want to filter rows after grouping; in cases like this, we need to use the

SELECT 
  meal_category,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category
HAVING sum(no_of_views) >1000000;
1 clause:

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;

This misunderstanding about the difference between

SELECT 
  meal_category,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category
HAVING sum(no_of_views) >1000000;
1 and
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
8 is the second most common error with
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7.

Let's clarify this difference with two more examples.

Example 1 -  How to Display Meal Categories with 1M+ Views 

A statement that displays only categories with more than 1 million total page views can be written like this:

SELECT 
  meal_category,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category
HAVING sum(no_of_views) >1000000;

Here we are using

SELECT 
  meal_category,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category
HAVING sum(no_of_views) >1000000;
1 because we want to filter records after they have been grouped. The result is presented below:

meal_categorytotaldesserts2969324Main dishes1323981Side dishes1662910Soups1100911

Example with HAVING

Example 2 – John’s Performance in Each Meal Category

This query extracts only John's recipes and calculates his performance:

SELECT 
  meal_category, 
  sum(no_of_views) AS total 
FROM recipes 
WHERE author = ‘John’ 
GROUP BY meal_category;

We’re using WHERE because we need to filter records (so we only get John’s data) before we put the records into groups by meal category. Here is how the result looks:

meal_categorytotalBread and pastry50935desserts301869drinks147745Main dishes279934Salads88097Side dishes415864Soups393253Warm appetizer85570

John’s KPIs

SELECT 
  meal_category,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category
HAVING sum(no_of_views) >1000000;
1 and
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
8 are nicely described in our articles What Is the Difference Between WHERE and HAVING Clauses in SQL? and 5 Examples of GROUP BY. If you would like to see more examples on this topic, I suggest starting there.

3. Listing a Column Inside SELECT but Not in GROUP BY

Now suppose you want to see the total number of views per

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
WHERE count(*) > 10 
GROUP BY meal_category ;
6 and
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
WHERE count(*) > 10 
GROUP BY meal_category ;
8. We can do that? – ?we only need to add the author column to our previous query:

SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category;

Does this look okay to you?  Of course not; it will throw an error in most SQL engines. For example, Oracle will tell you. Why this confusing error? What is missing here?

Well, the SQL engine doesn't know how to calculate the total for each author because we didn't include it in the GROUP BY clause; the attribute author is not listed inside the GROUP BY clause. This is another common error with GROUP BY.

Let's fix this query and run it one more time:

SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category, author;

The result is:

meal_categoryauthortotalBread and pastryDino53789Bread and pastryJohn50935Bread and pastryMarta52998Bread and pastryMary52904Bread and pastryPatricia51451Bread and pastryTim106226...........................SoupsMary125731SoupsMonte128356SoupsPatricia255574SoupsTim132532Warm appetizerJohn85570Warm appetizerLisa82960Warm appetizerMary87560

Now this looks okay. Remember, unaggregated columns that are listed in

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
WHERE count(*) > 10 
GROUP BY meal_category ;
1 must also be listed in
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7.  In our case, the unaggregated columns are
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
WHERE count(*) > 10 
GROUP BY meal_category ;
6 and
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
WHERE count(*) > 10 
GROUP BY meal_category ;
8, which are now in
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
WHERE count(*) > 10 
GROUP BY meal_category ;
1 and
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7.

You don't list columns that are inside aggregate functions in

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7. In our example, the column
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
WHERE count(*) > 10 
GROUP BY meal_category ;
5 is used in the aggregate function
SELECT 
  meal_category, 
  sum(no_of_views) AS total 
FROM recipes 
WHERE author = ‘John’ 
GROUP BY meal_category;
8 and thus is not listed in the
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 clause.

 If you would like to learn more about this topic, check out our article GROUP BY Clause: How Well Do You Know It?. It explains why SELECTed columns need to appear in the GROUP BY clause. Also, How to Fix a ‘Not a GROUP BY Expression’ Error gives more examples related to this type of error.

4. Not Grouping by a Unique Key

Now let’s try something else. Suppose we want to get the average number of page views for each recipe author. The following query calculates the average total number of page views for each author using the author name:

SELECT 
  author,
  avg(no_of_views) 
FROM recipes 
GROUP BY author;

When you look at the result, you will notice that Lisa averages 116101.5 page views:

authoravg(NO_OF_VIEWS)Ally106545Dino94667.9091John88163.35Lisa116101.5Luke104591Marta119789.1667Mary101040.0588Monte84794Patricia81911.1333Tim76185.375

GROUP BY author – but names are not unique

However, we actually have two authors named Lisa in our table. When we group the results by the author column, both Lisas are averaged together. Why? Because we are using a non-unique column in the

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7. This means that not all the grouping values have to be unique. If we want to see each Lisa’s average separately, we should add
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
1 (a unique column) to the
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 list:

SELECT 
  author, author_id
  avg(no_of_views) 
FROM recipes 
GROUP BY author, author_id;

Now we see how recipes from Lisa (id=11) are much more viewed than recipes by Lisa (id=5):

authorauthor_idavg(no_of_views)Ally3106545Dino794667.9091John288163.35Lisa585798Lisa11146405Luke4104591Marta1119789.1667Mary6101040.0588Monte984794Patricia1081911.1333Tim876185.375

GROUP BY with author and author_id

It is important to always think about grouping keys. Grouping values should be unique and must represent each group in the desired way. Otherwise, you’ll get inaccurate, confusing results and possibly a GROUP BY error.

5. Confusing COUNT(distinct) and COUNT(*)

If you’re curious to see the total number of authors for each meal category, you can write a

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 statement to calculate that. Let's use
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7 and retrieve the number of authors in each category:

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
0

Here’s the result – but it’s not what you expected, is it?

meal_categorycount(*)Bread and pastry7Cold appetizer6desserts20drinks7Main dishes20Salads8Side dishes12Soups17Warm appetizer3

This is the total number of recipes in each category, not the total number of authors. Why is that? Well,

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7 counts all the rows in each group. The table recipe contains information on a
SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category;
6 level -  each record is one recipe. This query counts the recipes (rows) in each category, not the recipe authors.

One author can have many recipes in each category, so to get the information you want, you must count distinct authors (using

SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category;
7 instead of
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7)  inside each group. This is a very common
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 error.

So, when should you use

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7,
SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category, author;
1 and
SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category, author;
2?

Let's take a look at an example:

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
1meal_categorycount(distinct author)count(author)count(*)Bread and pastry677Cold appetizer266desserts82020drinks577Main dishes92020Salads688Side dishes81212Soups61717Warm appetizer333

The difference between

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7 and
SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category, author;
1 is visible if we are doing calculations on a column that has some missing values. When missing values are present, 
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7 will count all the records in a group and
SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category, author;
1 will count only non-null values.

In the above example,

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7 and
SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category, author;
8 give the exact same result because the author column doesn’t have any NULL values. 

SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category;
7 gives us the number of distinct authors for each category, which is not the same as
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7. For example, the cold appetizer meal category contains six recipes from two distinct authors.
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7 counts the number of recipes (records) in each category, while
SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category;
7 counts the number of distinct authors.

So, if you would like to display the total number of distinct authors per each meal category, use

SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category;
7. Here is the correct query:

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
2

For a more detailed explanation, see What is the Difference Between COUNT(*), COUNT(1), COUNT(column name), and COUNT(DISTINCT column name)?

6. Problems Using Aggregate Functions With NULLs

This is another ‘missing value’ problem. Let's say that you want to calculate the average total number of views from the previous month for each category. Your colleague calculated those figures, but they’d like you to double check the result.

Here is your query:

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
3

And what you get is ...

meal_categoryaverageBread and pastry52274.8571Cold appetizer95584.2desserts144349.7222drinks72551.7143Main dishes61350.8889Salads90798.875Side dishes139765.25Soups64978.8824Warm appetizer78390.6667

The result looks okay and you are confident when it comes to the correctness of your query. However, your colleague got slightly different figures:

meal_categoryaverageBread and pastry52274.8571Cold appetizer79653.5desserts129914.75drinks72551.7143Main dishes55215.8Salads90798.875Side dishes139765.25Soups64978.8824Warm appetizer78390.6667

What just happened? Why the different results?

 In a nutshell, the differing results arise from different interpretations of missing values.

The column

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
0 represents the number of total page views in the previous month. If a recipe was created in the current month, this column will be NULL for that row.

For example, Ally’s Banana Cheesecake recipe was written in the current month, so there are no statistics for the previous month:

meal_categorynameauthorno_of_viewsno_of_views_lst_mthauthor_iddessertsBanana CheesecakeAlly131944NULL3

Banana cheesecake was published in current month

Now, let's get back to those averages and their different results. Averages are calculated as the total sum of

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
0 divided by the total number of records. If you use the AVG() function and NULLs are present, the engine just ignores the NULLs and does calculations without them. This is what happened when you ran your query – the NULLs were omitted. In some cases, you’ll want to replace NULLs with 0 (because business logic dictates); this is what your colleague did, which produced slightly different figures. Here is your colleague’s query:

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
4

Notice how the averages from these two queries treat NULLs differently. For example, the ‘desserts’ category contains NULLs. Thus, the first query omits these rows and does not count them towards the total number of rows; this gives the value 144349.72. The second query replaces all NULLs with zero and counts these rows in the average, giving a smaller value  of 129914.75.

I would say that both queries could be valid, depending on how you want to calculate averages.

7. Using COUNT(*) with GROUP BY and a LEFT JOIN

Using

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 with a
SELECT 
  author,
  avg(no_of_views) 
FROM recipes 
GROUP BY author;
7 statement can be quite confusing – especially with
SELECT 
  author,
  avg(no_of_views) 
FROM recipes 
GROUP BY author;
8. Let's see how
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7 and
SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category, author;
1 function in a
SELECT 
  author,
  avg(no_of_views) 
FROM recipes 
GROUP BY author;
7.

Let’s suppose that someone in marketing has the following table,

SELECT 
  author, author_id
  avg(no_of_views) 
FROM recipes 
GROUP BY author, author_id;
2. It contains information about the number of campaigns run on each meal category in the current month:

meal_categorycampaignsBread and pastry2Cold appetizer1desserts3drinks0Main dishes3Salads1Side dishes2Soups3Warm appetizer0brunch1sandwiches0

recipes_campaign

In addition to the data in

SELECT 
  author, author_id
  avg(no_of_views) 
FROM recipes 
GROUP BY author, author_id;
3, the marketer also wants to see the number of recipes for each meal category. For that, we’ll need information from the
SELECT 
  author, author_id
  avg(no_of_views) 
FROM recipes 
GROUP BY author, author_id;
4 table. So let’s left join these two tables and calculate the number of recipes using
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7, like so:

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
5

Here’s the result:

meal_categorycount(*)Bread and pastry7brunch1Cold appetizer6desserts20drinks7Main dishes20Salads8sandwiches1Side dishes12Soups17Warm appetizer3

This isn’t what we expected. The table

SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category;
6 does not contain any recipes in the ‘brunch’ category, so why then did we get that 1 in the result? This happens because
SELECT 
  author,
  avg(no_of_views) 
FROM recipes 
GROUP BY author;
8 is applied to the
SELECT 
  author,
  avg(no_of_views) 
FROM recipes 
GROUP BY author;
7 result! When you
SELECT 
  author,
  avg(no_of_views) 
FROM recipes 
GROUP BY author;
7 two tables, the ‘brunch’ category will be present in the output – even if there are no matching recipes or categories in the
SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category;
6 table.

How can we fix this? If we use

SELECT 
  meal_category,
  author,
  sum(no_of_views) AS total 
FROM recipes 
GROUP BY meal_category, author;
1 instead of
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
7, we’ll get the result we want:

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
6

Once you run this, you get:

meal_categorycount(author_id)Bread and pastry7brunch0Cold appetizer6desserts20drinks7Main dishes20Salads8sandwiches0Side dishes12Soups17Warm appetizer3

Here,

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
03 counts only the non-NULL values in
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
1 after the
SELECT 
  author,
  avg(no_of_views) 
FROM recipes 
GROUP BY author;
7 is performed. There is no
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
           GROUP BY meal_category
HAVING count(*) > 10  ;
1 value for the ‘brunch’ category; in other words, it’s NULL and the result for that category is 0.

You Can Solve GROUP BY Errors!

Through several examples, we’ve explored GROUP BY and the most common errors that beginners often make. I hope that now you have a better sense of how

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 works and what’s causing those weird errors or confusing results.

SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 is really very important in report creation. If you want to learn how to construct good reports, I recommend our Creating Basic SQL Reports course. It has lots of interactive exercises that let you gain experience writing
SELECT 
  meal_category,
  count(*) AS total_recipes 
FROM recipes
GROUP BY meal_category ;
7 queries for reports. And more experience certainly reduces the possibility of mistakes!

When a SELECT statement includes WHERE HAVING and GROUP BY clauses the GROUP BY clause is always evaluated first?

Terms in this set (29) When the SELECT statement includes both WHERE and GROUP BY clauses, the GROUP BY clause is always evaluated first. The HAVING clause specifies which groups will be displayed in the results, while the WHERE clause restricts the records that are retrieved from the table for processing.

What is true for GROUP BY order by clause?

Answer: A. Processing order starts from FROM clause to get the table names, then restricting rows using WHERE clause, grouping them using GROUP BY clause, restricting groups using HAVING clause. ORDER BY clause is the last one to be processed to sort the final data set.

Which clause can be used to restrict or filter the groups returned by a query based on a group function?

The HAVING clause is used to restrict the groups returned by a query. If a group function is used in the SELECT clause, then any individual columns listed in the SELECT clause must also be listed in the ORDER BY clause.

Which line of the SELECT statement is used to group data stored in the database?

The Group By statement is used to group together any rows of a column with the same value stored in them, based on a function specified in the statement.