Basic Functions | Dataplexa

Basic SQL Functions

SQL functions allow us to perform calculations, transformations, and summaries directly inside queries. Instead of manually processing data, SQL functions let the database do the work efficiently.

In this lesson, we’ll focus on basic SQL functions that are commonly used in everyday queries.


What is a SQL Function?

A SQL function takes input values, performs an operation, and returns a single output value.

Basic structure:

FUNCTION_NAME(column_name)
  

Functions can be used in the SELECT clause, WHERE clause, and many other parts of a query.


COUNT Function

The COUNT() function returns the number of rows. It is often used to understand how much data exists.

Example: Count total employees.

SELECT COUNT(*) AS total_employees
FROM employees;
  

Important notes:

  • COUNT(*) counts all rows
  • COUNT(column) ignores NULL values

SUM Function

The SUM() function adds all numeric values in a column.

Example: Total salary of all employees.

SELECT SUM(salary) AS total_salary
FROM employees;
  

SUM works only with numeric columns.


AVG Function

The AVG() function calculates the average (mean) value.

Example: Average employee salary.

SELECT AVG(salary) AS average_salary
FROM employees;
  

AVG automatically ignores NULL values.


MIN and MAX Functions

The MIN() and MAX() functions return the smallest and largest values in a column.

Example: Lowest and highest salaries.

SELECT MIN(salary) AS lowest_salary,
       MAX(salary) AS highest_salary
FROM employees;
  

Using Functions with WHERE

Functions can be combined with WHERE to analyze specific data.

Example: Average salary of IT department employees.

SELECT AVG(salary) AS avg_it_salary
FROM employees
WHERE department = 'IT';
  

Common Aggregate Functions

Function Purpose Example
COUNT() Count rows COUNT(*)
SUM() Add values SUM(salary)
AVG() Calculate average AVG(salary)
MIN() Find smallest value MIN(salary)
MAX() Find largest value MAX(salary)

Common Beginner Mistakes

  • Using SUM or AVG on text columns
  • Forgetting that COUNT(column) ignores NULLs
  • Mixing aggregate functions with normal columns incorrectly

We will learn how to correctly combine aggregates with other columns in the upcoming GROUP BY lesson.


Why Functions Matter

SQL functions allow you to:

  • Analyze data quickly
  • Generate reports
  • Summarize large datasets
  • Answer business questions efficiently

What’s Next?

In the next lesson, we will explore aggregate functions in depth and understand how they behave with grouped data.