Skip to main content
April 2, 2026Dan Rodney/5 min read

Exercise- Aggregate Function and ROUND in SQL

Master SQL aggregates and precise number formatting

Core SQL Aggregate Functions

MAX and MIN

Find the highest and lowest values in a dataset. Perfect for price analysis and data range discovery.

COUNT

Count rows or non-null values. Essential for data validation and understanding dataset completeness.

SUM and AVG

Calculate totals and averages. Critical for financial calculations and statistical analysis.

Many In, One Out Principle

Aggregate functions take multiple values from a column and return a single result. This is the fundamental concept that drives all SQL aggregation operations.

Setting Up Your SQL Environment

1

Choose Server

Select your database server from the connection dropdown. Most work will be done in the company data database.

2

Select Database

Default to company data for most exercises. Occasionally switch to jeopardy database for specific examples.

3

Identify Data

Examine your tables and columns to understand the data structure before writing aggregate queries.

Single Column vs Multiple Aggregates

FeatureSingle AggregateMultiple Aggregates
ResultOne valueMultiple values in one row
UsageBasic analysisComprehensive overview
ExampleMAX(price)MAX(price), MIN(price), AVG(price)
Recommended: Use multiple aggregates on the same column to get comprehensive analysis in a single query.
Critical Aggregation Rule

If you aggregate one column, you must aggregate all columns in your SELECT statement. You cannot mix aggregated and non-aggregated columns.

COUNT Behavior with NULL Values

Total Users
100
Non-NULL Passwords
99

COUNT vs COUNT(column) vs COUNT DISTINCT

Pros
COUNT(*) gives total rows including nulls
COUNT(column) excludes null values
COUNT DISTINCT eliminates duplicates
Performance is generally excellent
Cons
COUNT(column) may give unexpected results with nulls
Must understand null handling behavior
Can be misleading without proper context

State Count Comparison

Total State Records
100
Distinct States
43

Revenue Calculation Impact

FeaturePrice OnlyPrice × Quantity
Total Revenue$39,000$99,000
Business ImpactUnderestimatedAccurate
Decision MakingPoor decisionsInformed decisions
Recommended: Always multiply price by quantity for accurate revenue calculations.

Average Analysis Results

$54
Average Product Price
$135
Average Line Item Value

Professional Column Naming

1

Use Aliases

Add meaningful names to calculated columns using AS keyword for clarity and professionalism.

2

Handle Spaces

Use double quotes for column names with spaces. Single quotes are reserved for string values.

3

Be Descriptive

Choose names that clearly explain what the calculation represents, especially for exported data.

Number Formatting Options

FeatureROUND FunctionCAST to MONEY
Default BehaviorWhole numbers2 decimal places
Decimal ControlSpecify placesFixed at 2
Display FormatPlain numberDollar sign prefix
Use CaseGeneral roundingFinancial display
Recommended: Use ROUND for flexible decimal control, CAST to MONEY for financial presentation.
ROUND Function Parameters

The ROUND function accepts two parameters: the number to round and optionally the number of decimal places. Without the second parameter, it rounds to whole numbers.

This lesson is a preview from our SQL Course Online (includes software) and SQL Certification Online (includes software & exam). Enroll in a course for detailed lessons, live instructor support, and project-based training.

Understanding SQL aggregate functions and rounding techniques is essential for transforming raw data into meaningful business insights. This tutorial demonstrates how to extract summary statistics from databases and present them in professional formats.

Before diving into aggregate functions, ensure you've selected the appropriate database server. Most operations will occur within the company database, though we'll occasionally reference the jeopardy database for specific examples. This workspace configuration remains consistent across modern SQL environments.

Consider a typical product catalog with hundreds of price entries. Rather than examining each individual price point, aggregate functions allow you to extract meaningful summary statistics. You can instantly identify the maximum price across all products or find the minimum value in your inventory. This represents the core principle of aggregation: multiple data points enter the function, but only one summary value emerges.

The true power of SQL becomes apparent when you realize you can reference the same column multiple times within a single query, applying different aggregate functions to each instance. For example, you might want both the maximum and minimum prices displayed simultaneously. By selecting the price column twice—once with MAX() and once with MIN()—you create a comprehensive summary view in a single result set.

Expanding this concept further, you can add average calculations to display maximum, minimum, and mean values together. This approach demonstrates SQL's flexibility: you're not merely viewing database records, but actively manipulating data to create custom analytical reports. These calculated result sets don't exist as stored tables—they're dynamically generated based on your specific requirements.

A critical constraint governs aggregate function usage: you cannot mix aggregated and non-aggregated columns in the same query. If one column returns a single aggregated value (like MAX price), all other selected columns must also be aggregated. Attempting to combine aggregated columns with regular multi-row columns generates errors, as SQL cannot reconcile different row counts in a single result set.

This principle differs fundamentally from spreadsheet applications like Excel, where such mixing might be possible. In SQL, consistency rules apply: aggregate one column, aggregate them all. This constraint ensures logical result sets and prevents ambiguous data presentations.


The COUNT function exemplifies another crucial aggregate operation. Rather than downloading potentially millions of user records to determine database size, COUNT returns the total row number instantly. This efficiency becomes critical when working with large datasets—imagine the performance impact of downloading complete user profiles for millions of accounts versus receiving a single count value.

When applying COUNT to specific columns rather than entire tables, null value handling becomes important. COUNT ignores null values, which can produce unexpected results. For instance, if your users table contains 100 records but one password field is null, counting the password column returns 99 rather than 100. Empty strings are counted (they represent data), but null values represent true absence of data.

This behavior can be advantageous or problematic depending on your analytical goals. For total user counts, querying all columns (using COUNT(*)) provides more reliable results since entire rows are rarely null, especially when primary keys exist. However, when counting distinct values within specific columns, targeted counting becomes valuable.

The DISTINCT keyword adds another layer of analytical power. Without DISTINCT, counting user states returns the total number of users (since each user has a state). With COUNT(DISTINCT user_state), you receive the number of unique states represented in your user base. This distinction proves essential for geographical analysis and market segmentation.

Moving beyond counting to financial calculations, the SUM function aggregates numeric values. However, proper calculation requires careful consideration of related fields. Summing prices alone provides total pricing, but summing price multiplied by quantity yields actual revenue. The difference between these calculations can be substantial—potentially showing $39,000 versus $99,000 in revenue—making accurate formulation critical for business reporting.

Average calculations (AVG) offer similar considerations. Average price points help determine typical product positioning, while average line item values (price × quantity) reveal customer spending patterns. These metrics serve different strategic purposes: pricing new products versus understanding purchasing behavior.


Professional presentation requires meaningful column names. Rather than displaying generic labels like "avg," use descriptive aliases such as "Average Product Price" or "Average Line Item Value." Double quotes enable spaces and capitalization in column names, creating export-ready reports for executive presentations. The AS keyword, while optional, improves code readability.

Financial data often requires precise formatting, particularly regarding decimal places. The ROUND function provides this control, accepting two parameters: the value to round and the desired decimal places. Without specifying decimal places, ROUND defaults to whole numbers. For financial presentations, two decimal places typically provide appropriate precision.

Alternative formatting approaches include casting to money data types, which automatically applies currency symbols and two-decimal formatting. This approach not only ensures consistent presentation but also signals the data's financial nature to end users. Modern SQL implementations have refined these formatting options since the language's 1974 inception, though core functionality remains consistent.

Beyond standard rounding, specialized functions handle specific rounding requirements. FLOOR always rounds down (toward zero), while CEILING (or CEIL in some implementations) always rounds up. These functions prove essential for tax calculations, inventory planning, and other scenarios requiring directional rounding rather than mathematical rounding.

The abbreviated function names (CEIL rather than CEILING) reflect SQL's historical emphasis on efficiency. Developed when computer storage was measured in kilobytes rather than terabytes, every character mattered. While modern systems easily handle longer function names, the abbreviated conventions persist across programming languages, including contemporary languages like JavaScript.

Mastering these aggregate functions and formatting techniques enables sophisticated data analysis directly within your database queries. Rather than exporting raw data for external processing, you can generate publication-ready reports that combine multiple analytical perspectives in single, efficient queries. This approach reduces data transfer overhead while providing immediate analytical insights essential for data-driven decision making.


Key Takeaways

1Aggregate functions follow the 'many in, one out' principle, converting multiple values into a single result
2When using aggregate functions, all columns in SELECT must be aggregated - you cannot mix aggregated and non-aggregated columns
3COUNT behavior varies: COUNT(*) includes all rows, COUNT(column) excludes nulls, COUNT DISTINCT eliminates duplicates
4For accurate revenue calculations, always multiply price by quantity rather than summing prices alone
5ROUND function provides flexible decimal place control, while CAST to MONEY automatically formats currency with two decimal places
6Column aliases with meaningful names improve query readability and are essential for exported data
7Understanding null value handling is critical for accurate COUNT operations and data analysis
8Multiple aggregate functions can be applied to the same column in a single query for comprehensive analysis

RELATED ARTICLES