15 Oct 2024 Ekre Ceannmor 19 Aggregate Function Exercises Solve these 19 SQL aggregate function exercises and sharpen your SQL skills! Practice using aggregate functions with GROUP BY, HAVING, subqueries, and more. Includes a solution and detailed explanation for each exercise. Aggregate functions are an important part of SQL. They allow you to calculate different statistics and generate reports that you would not have been able to with single-row operations like filtering. It’s important to practice aggregate functions often, as they are a crucial part of your SQL skill set. Read more 30 Apr 2024 Jill Thornhill The SQL MIN() Function SQL has a variety of powerful aggregate tools, including the SQL MIN() function. This article is a quick reference guide to extracting and using minimum values in your queries. In today’s cutthroat business environment, it’s vital to be able to analyze your organization’s data effectively to make informed decisions. SQL’s aggregate functions let you carry out all kinds of statistical analysis on your data. This article is a reference guide to the SQL MIN() function, which extracts the smallest item from a column of data. Read more 18 Apr 2024 Tihomir Babic GROUP BY and Aggregate Functions: A Complete Overview SQL’s GROUP BY and aggregate functions are essential in data aggregation – and for analyzing data and creating reports. Let’s explore them together! In SQL, GROUP BY and aggregate functions are one of the language’s most popular features. Data aggregation is critical for data analysis and reporting; to make sense of all the data in a dataset, it often needs to be aggregated. But what is data aggregation? Put simply, it’s when you group data based on common values and perform a calculation for each data group. Read more 16 Apr 2024 Agnieszka Kozubek-Krycuń SQL MAX Function Learn about the SQL MAX function, which is used to find the highest value in your dataset. This article explains how to use the syntax of MAX function and shows typical usage examples. The SQL MAX function is an aggregate function that returns the maximum value in a column. MAX function, together with its counterpart MIN function, is useful for summarizing data in data analysis. It can help you to compute the range of values in a dataset. Read more 19 Mar 2024 Jill Thornhill SQL Aggregate Functions Cheat Sheet A quick reference guide to using SQL aggregate functions. This SQL Aggregate Functions Cheat Sheet is designed to be your companion whenever you’re using SQL for data analysis. Aggregating data is essential for any meaningful data analysis. SQL provides a set of functions that allow you to include totals, averages, and counts in your reports and to extract the minimum and maximum value of any column of data. Read more 21 Nov 2023 Maria Durkin SQL Aggregate Functions: A Comprehensive Guide for Beginners Are you curious about SQL aggregate functions and how they apply to real-world scenarios? In this article, we'll explore SQL aggregate functions, showcase real-world examples, and offer valuable insights on how to master them. Data aggregation is the process of taking several rows of data and condensing them into a single result or summary. When dealing with large datasets, this is invaluable because it allows you to extract relevant insights without having to scrutinize each individual data point. Read more 29 Jun 2023 Radu Gheorghiu How to Use COUNT() with GROUP BY: 5 Practical Examples Using the COUNT() function with GROUP BY is one of the most common SQL constructs in aggregate queries. Read this article to find out how to use COUNT() with GROUP BY correctly using 5 examples. In this article, we will explain the importance of using COUNT with GROUP BY. We’ll talk about why it is essential in SQL and how it enables data analysis and summarization based on specific criteria. Read more 30 May 2023 Gustavo du Mortier How to Use SUM() with GROUP BY: A Guide with 8 Examples Explore some real-world examples of using SUM() and GROUP BY in SQL, from the most basic to the most sophisticated. SUM() is a SQL aggregate function that computes the sum of the given values. GROUP BY is a SQL clause that partitions rows into groups and computes a stated aggregate function for each group. Using these two functions together, you can compute total sums for a group of rows. In this article, we’ll see 8 different examples of how you can combine SUM() and GROUP BY to create many different reports. Read more 16 Mar 2023 Tihomir Babic The SQL COUNT() Function: A Detailed Guide This guide will give you a detailed explanation (with examples) of all the typical uses of the COUNT() function. Exercises included! The COUNT() function in SQL is one of the most commonly used aggregate functions. Aggregate functions in SQL are used to calculate statistics for a group of rows: counting the number of rows in each group, computing the sum of values in a group, finding the minimum or maximum value in a group, and so on. Read more 11 Aug 2022 Tihomir Babic How to Use Aggregate Functions in WHERE Clause Filtering data according to the result of an aggregate function is a common data analysis task. So how do you use aggregates in the WHERE clause? We’ll dedicate this whole article to answering that question. Combining aggregate functions and filtering based on their results is often used in data analysis – e.g. showing branches with total sales above X, countries where the number of posts is lower than Y, students with an average score below Z, and so on. Read more 7 Jun 2022 Tihomir Babic How to Combine Two Aggregate Functions in SQL Having trouble using two aggregate functions in one query? This article will show you how to do it the right way – actually, the two right ways. In data analysis and reporting, we often need to count the number of records or sum them up and then calculate the average of this count or sum. Translated to SQL logic, this is the aggregation of aggregated data, or multi-level aggregation. For aggregation purposes, there are the SQL aggregate functions. Read more 30 Dec 2021 Tihomir Babic How to Include Zero in a COUNT() Aggregate Explaining how to include zero (0) counts in your SQL query result. Here’s the problem: you want to count something that doesn’t exist, and you want to show your result as zero. How do you do that in SQL? Using the COUNT() aggregate function is a reasonable first step. It will count all the data it finds and return the number of occurrences. But what if there are no occurrences of certain data? Read more 11 Nov 2021 Martyna Sławińska What Are Aggregate Functions in SQL, and How Do I Use Them? Data is your source of knowledge. And thanks to SQL aggregate functions, you can extract the precise knowledge you need from your data efficiently. Read along to find out more. The core SQL aggregate functions are the following: COUNT(column_name | *) returns the number of rows in a table. SUM(column_name) returns the sum of the values of a numeric column. AVG(column_name) returns the average value of a numeric column. Read more 21 Oct 2021 Himanshu Kathuria The SQL Count Function Explained With 7 Examples One of the most useful aggregate functions in SQL is the COUNT() function. If you are new to SQL and want to learn about the various ways to use the COUNT() function with some practical examples, this article is for you. The COUNT() function is one of the most useful aggregate functions in SQL. Counting the total number of orders by a customer in the last few days, the number of unique visitors who bought a museum ticket, or the number of employees in a department, can all be done using the COUNT() function. Read more 31 Aug 2021 Dorota Wdzięczna SQL MIN and MAX Functions Explained in 6 Examples What are the SQL MIN() and MAX() functions? When should you use them as aggregate functions, and when should you use them with window functions? We explain using practical examples. SQL includes several aggregate functions. These aggregate functions compute calculations on numerical data. This article focuses on only two of these functions: MIN() and MAX(). I will explain what each function does and discuss several use cases. If you want to practice SQL aggregate functions, I recommend our interactive SQL Practice Set course. Read more 19 Aug 2021 Himanshu Kathuria The SQL AVG() Function Explained With Examples We explain the SQL AVG() function with practical examples, covering how and where you can and cannot use it. The average is probably one of the most widely used metrics to describe some characteristics of a group. It is so versatile and useful that it can describe something about almost anything. If you like sports, you see things like average runs per game in baseball, average assists per game or per season in basketball, and so on. Read more 23 Jul 2021 Dorota Wdzięczna SQL SUM() Function Explained with 5 Practical Examples Aggregate functions are an important part of SQL knowledge – and there’s no better place to start learning them than with the SUM() function. In this article, you can expand or refresh your SQL with 5 practical examples of SUM(). SQL allows us to do more than select values or expressions from tables. Most operations on relational databases use aggregate functions like SUM() to do computations on data. Read more 15 Dec 2020 Tihomir Babic How to Use CASE WHEN With SUM() in SQL This article will teach you what a CASE WHEN expression is in SQL and how to use it with a SUM() function and a GROUP BY statement. The examples are included to bolster your understanding. The best way to learn about CASE WHEN and how to use it with SUM() is our hands-on course Creating Basic SQL Reports. It contains over 90 interactive exercises that will teach you different techniques how to create complex reports in SQL. Read more 26 Nov 2020 Kateryna Koidan Aggregate Functions vs Window Functions: A Comparison If you aren’t familiar with SQL’s window functions, you may wonder how they differ from aggregate functions. When should you use window functions? In this article, we’ll review window functions and aggregate functions, examine their similarities and differences, and see which one to choose depending on what you need to do. After you’ve tackled basic SQL, you’ll probably want to get into some of its more advanced functions. That’s great; these functions make reporting and analysis easier. Read more 29 Oct 2020 Tihomir Babic What is COUNT(*), COUNT(1), COUNT(column), and COUNT(DISTINCT) in SQL? Have you noticed there are different variations of the SQL COUNT() function? This article explains the various arguments and their uses. As a SQL user, you’re probably quite familiar with the COUNT() function. Even though it’s relatively simple, it can be used in several different ways. Each way has a very different use. I imagine you’ve seen code that contains the function COUNT(*) or COUNT(1). You’ve probably also seen some other uses of the COUNT() function, such as COUNT(column name) and COUNT(DISTINCT column name), even if you haven’t used them. Read more 15 Feb 2020 How to Find Rows with Minimum Value Problem You want to find rows which store the smallest numeric value in a column. Example Our database has a table named weather with data in the following columns: id, city, and temperature. You want to find cities with the lowest temperature. idcitytemperature 1Houston23 2Atlanta20 3Boston15 4Cleveland15 5Dallas34 6Austin28 Solution SELECT id, city, temperature FROM weather WHERE temperature = (SELECT MIN(temperature) FROM weather); Here’s the result: Read more 15 Feb 2020 How to Find Rows with Maximum Value Problem You want to find rows which store the largest numeric value in a given column. Example Our database has a table named student with data in the following columns: id, first_name, last_name, and grade. You want to find the students who have the highest grades. idfirst_namelast_namegrade 1LisaJackson3 2GaryLarry5 3TomMichelin2 4MartinBarker2 5EllieBlack5 6MarySimpson4 Solution SELECT id, first_name, last_name, grade FROM student WHERE grade = (SELECT MAX(grade) FROM student); Here’s the result: Read more 15 Feb 2020 How to Filter Records with Aggregate Function SUM Problem You need to filter groups of rows by the sum of a given column. Example Our database has a table named company with data in the following columns: id, department, first_name, last_name, and salary. iddepartmentfirst_namelast_namesalary 1marketingLoraBrown2300 2financeJohnJackson3200 3marketingMichaelThomson1270 4productionTonyMiller6500 5productionSallyGreen2500 6financeOlivierBlack3450 7productionJenifferMichelin2800 8marketingJeremyLorson3600 9marketingLouisSmith4200 Let’s find the names of departments that have sums of salaries of its employees less than 7000. Read more 15 Feb 2020 How to Filter Records with Aggregate Function COUNT Problem You want to find groups of rows with a specific number of entries in a group. Example Our database has a table named product with data in the following columns: id, name and category. idnamecategory 1sofafurniture 2glovesclothing 3T-Shirtclothing 4chairfurniture 5deskfurniture 6watchelectronics 7armchairfurniture 8skirtclothing 9radio receiverelectronics Let’s find the category of products with more than two entries. Read more 15 Feb 2020 How to Filter Records with Aggregate Function AVG Problem You want to filter groups of rows in by the average value of a given column. Example Our database has a table named product with data in the following columns: id, name, store and price. idnamestoreprice 1milkGreen Shop2.34 2breadClark’s Grocery3.56 3breadSuper Market4.15 4milkSuper Market1.80 5breadGrocery Amanda2.26 6milkViolet Grocery3.45 7milkClark’s Grocery2.10 8breadViolet Grocery2. Read more 9 Feb 2020 How to Find the Minimum Value of a Column in SQL Problem You’d like to find the smallest numeric value in a column. Example Our database has a table named employment with data in the following columns: id, first_name, last_name, department, and salary. idfirst_namelast_namedepartmentsalary 1EllieMartinesmarketing1200 2MartinJohnsonfinance2300 3MichaelJacobsproduction1100 4StephenKowalskimarketing4300 5StanleyMillermarketing3500 6JenyBrownfinance5000 7MargaretGreenmarketing1500 8LisaThomasproduction2800 Let’s find the lowest salary among all employees. Read more 9 Feb 2020 How to Find the Maximum Value of a Numeric Column in SQL Problem You’d like to find the maximum value of a numeric column. Example Our database has a table named product with data in the following columns: id, name, year, and items. idnameyearitems 1bread roll2018345 2chocolate2017123 3butter201934 4bread roll2019456 5butter201856 6butter201778 7chocolate201987 8chocolate201876 Let’s find the maximum number of items sold over all years. Read more 9 Feb 2020 How to Find the Average of a Numeric Column in SQL Problem You’d like to calculate the average of numbers in a given column. Example Our database has a table named sale with the following columns: id, city, year, and amount. We want to calculate the average sales, regardless of city or year. idcityyearamount 1Los Angeles20172345.50 2Chicago20181345.46 3Annandale2016900.56 4Annandale201723230.22 5Los Angeles201812456.20 6Chicago201789000.40 7Annandale201821005. Read more 26 Nov 2019 How to Sum Values of a Column in SQL? Problem: You’d like to compute the sum the values of a column. Example 1: Computing the Total Sum for a Column Our database has a table named game with the following columns: id, player, and score. You want to find the total score obtained by all players. idplayerscore 1John134 2Tom 146 3Lucy20 4Tom 118 5Tom 102 6Lucy90 7Lucy34 8John122 Solution: SELECT SUM(score) as sum_score FROM game; Here’s the result: Read more 26 Nov 2019 How to Count the Number of Rows in a Table in SQL Problem You’d like to determine how many rows a table has. Example Our database has a table named pet with data in the following columns: id, eID (electronic identifier), and name. ideIDname 123456sparky 223457mily 3NULLlessy 4NULLcarl 534545maggy Let’s count all rows in the table. Solution COUNT(*) counts the total number of rows in the table: Read more 25 Nov 2019 How to Order by Count in SQL? Problem: You aggregated data into groups, but you want to sort the records in descending order by the number of elements in the groups. Example: Our database has a table named user with data in the following columns: id, first_name, last_name, and country. idfirst_namelast_namecountry 1LisaWilliamsEngland 2GaryAndersPoland 3TomWilliamsPoland 4MichaelBrownFrance 5SusanSmithUSA 6AnneJonesUSA 7EllieMillerPoland Let’s create a report on our users. Read more 25 Nov 2019 How to Count Distinct Values in SQL Problem You’d like to count how many different non-NULL values there are in a given column. Example Our database has a table named customer with data in the following columns: id, first_name, last_name, and city. idfirst_namelast_namecity 1JohnWilliamsChicago 2TomBrownAustin 3LucyMillerChicago 4EllieSmithDallas 5BrianJonesAustin 6AllanDavisNULL Let’s find the number of different (and non-NULL) cities. Read more 27 Nov 2017 Ignacio L. Bisso SQL Date and Interval Arithmetic: Employee Lateness Computing Tardiness: Date, Time, and Interval SQL Arithmetic In this article, we’re going to discuss some interesting operations we can perform with date-related data types in SQL. The SQL standard, which most relational databases comply with these days, specifies the date-related data types that must be present in relational databases. The most important of such data types are date, time, timestamp, and interval. Here’s a brief rundown of the differences between these data types: Read more 31 Aug 2017 Aldo Zelen Common SQL Window Functions: Positional Functions Positional SQL window functions deal with data's location in the set. In this post, we explain LEAD, LAG, and other positional functions. SQL window functions allow us to aggregate data while still using individual row values. We've already dealt with ranking functions and the use of partitions. In this post, we'll examine positional window functions, which are extremely helpful in reporting and summarizing data. Specifically, we'll look at LAG, LEAD, FIRST_VALUE and LAST_VALUE. Read more 11 Jul 2017 Dejan Sarka Statistics in SQL: Measuring Spread of Distribution Besides knowing the centers of a distribution in your data, you need to know how varied the observations are. In this article, we’ll explain how to find the spread of a distribution in SQL. Are you dealing with a very uniform or a very spread population? To really understand what the numbers are saying, you must know the answer to this question. In the second part of this series, we discussed how to calculate centers of distribution. Read more 6 Jul 2017 Francisco Claria An Introduction to Using SQL Aggregate Functions with JOINs Previously, we've discussed the use of SQL aggregate functions with the GROUP BY statement. Regular readers of the our blog will also remember our recent tutorial about JOINs. If you're a bit rusty on either subject, I encourage you to review them before continuing this article. That's because we will dig further into aggregate functions by pairing them with JOINs. This duo unleashes the full possibilities of SQL aggregate functions and allows us to perform computations on multiple tables in a single query. Read more 27 Apr 2017 Maria Alcaraz NULL Values and the GROUP BY Clause We've already covered how to use the GROUP BY clause and some aggregation functions like SUM(), AVG(), MAX(), MIN(), COUNT(). In this article, we will explain how the GROUP BY clause works when NULL values are involved. We will also explain about using NULLs with the ORDER BY clause. The best way to master GROUP BY and NULL in SQL is through practice. I recommend the SQL Practice track at LearnSQL. Read more