How To Use SQL Functions

Published:22 December 2023 - 8 min. read

Nicholas Xuan Nguyen Image

Nicholas Xuan Nguyen

Read more tutorials by Nicholas Xuan Nguyen!

As your dataset expands, the demand for sophisticated data manipulation techniques naturally increases. In such cases, SQL functions emerge as a powerful avenue to elevate your queries, enabling you to execute intricate calculations and transformations on your data.

In this tutorial, you will learn the basics of SQL functions and how to use them in your queries, whether for basic or large datasets.

Bring clarity to the complex, and turn your data challenges into triumphs with SQL functions!


Before you dive into the details of SQL functions, ensure you have the following to follow along in the hands-on demonstrations:

  • A server that supports MySQL – This tutorial uses Ubuntu 20.04 for demonstrations.
  • MySQL is installed and configured on your server.

What are SQL Functions?

In MySQL, a function is a versatile and reusable block of code designed to perform specific tasks on your data. These functions accept one or more parameters and return a single value as their output. They are indispensable tools for data manipulation in SQL queries.

Below are some compelling reasons to leverage MySQL functions in your database:

  • Promotes code reusability – Functions, once created, can be invoked multiple times in various queries. This capability significantly reduces code duplication and enhances maintainability.
  • Enhances query efficiency – By encapsulating logic into functions, you streamline your code, which often results in improved query performance.

💡 Functions and procedures are reusable blocks of code in MySQL but serve different purposes. While functions return a single value as output, procedures can perform multiple tasks and return multiple values. Additionally, functions can be used directly in SQL queries, while procedures must be called separately.

Setting Up a Sample Database

After laying the foundation for your journey into SQL functions, you’ll delve into the practical side. Instead of just wondering how those complex SQL functions operate in a real-world scenario, why not demystify the magic?

But first, you need a playground—a place to experiment, make mistakes, and learn. In this example, you’ll set up a sample database as your repository.

To set up your sample database, follow these steps:

1. Connect to your MySQL Server.

2. Once connected, execute the following command to CREATE a new DATABASE named electronics_catalog (arbitrary) to store electronic product data.

CREATE DATABASE electronics_catalog;
Creating a new database
Creating a new database

3. Execute the following command to switch (USE) to your new database and ensure that any subsequent SQL operations are applied.

USE electronics_catalog;
Switching to the newly-created database
Switching to the newly-created database

4. Now, run the command below to CREATE a sample TABLE named electronic_products (arbitrary) to store electronic product data. The data includes product ID, gadget name, price, stock quantity, and date added.

CREATE TABLE electronic_products (
    gadget_name VARCHAR(255) NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    stock_quantity INT NOT NULL,
    date_added DATE NOT NULL
Creating a sample table to store electronic product data
Creating a sample table to store electronic product data

5. Lastly, execute the command below to INSERT data INTO the electronic_products table for demonstration purposes.

INSERT INTO electronic_products (gadget_name, price, stock_quantity, date_added)
    ('Smartphone X', 599.99, 50, '2021-01-15'),
    ('Laptop Pro', 1199.99, 25, '2022-02-10'),
    ('Tablet Mini', 349.99, 40, '2023-02-18'),
    ('Smart Speaker', 79.99, 75, '2023-03-05'),
    ('Camera HD', 449.99, 30, '2023-03-15');

You now have data to play around as you experiment with SQL functions.

Inserting data into the electronic_products table
Inserting data into the electronic_products table

Leveraging Mathematical/Numerical Functions

Having set up your sample database, you’ll shift your focus to a realm where numbers dance, and calculations take center stage— empowering your data analysis. Mathematical and numerical functions are invaluable when working with numeric data types, such as INT and DECIMAL.

In this example, you’ll apply these functions to your electronic products dataset’s ‘price’ and ‘stock_quantity’ columns.

To leverage mathematical functions for your data analysis, carry out the following:

Execute the query below to ROUND the price column data FROM your electronic_products table to the nearest whole number and display the result AS rounded_price.

Rounding is a fundamental mathematical operation crucial in SQL and data analysis. This operation simplifies numeric values by reducing them to the nearest whole number, making your data more reader-friendly.

SELECT gadget_name, price, ROUND(price) AS rounded_price FROM electronic_products;

If successful, you’ll see a similar output, as shown below. The new rounded_price column contains prices rounded to the nearest whole number based on the values in the price column.

Rounding a value to the nearest whole number
Rounding a value to the nearest whole number

Now, execute the following query to perform the following:

  • Calculate the total value for each gadget by multiplying (*) the price per unit by the total stock_quantity.
  • ROUND the result to one (1) decimal place and store the rounded number in the total_value column.

With this query, you can quickly get valuable insights into the total value of products in your inventory.

SELECT gadget_name, price, stock_quantity, ROUND(price * stock_quantity, 1) AS total_value FROM electronic_products;

The output below shows the total value of each gadget in stock, rounded off to one decimal point. Dealing with large or overly precise numbers can be cumbersome for the human eye.

Accomplishing this task manually on a large dataset would be time-consuming, but MySQL’s mathematical functions make life easier. Rounding significantly enhances data-readability in reports and presentations, making them more digestible.

Rounding the product of the total price and stock quantity
Rounding the product of the total price and stock quantity

Manipulating String Data with String Functions

You’ve seen how mathematical functions work like magic. But what if your database includes string data? Fortunately, MySQL also offers a way to manipulate string data in your database—string functions.

String functions let you perform various operations, such as concatenation (CONCAT()) and upper (UPPER())and lower (LOWER()) conversions.

To manipulate string data with string functions, proceed with these steps:

1. Execute the following query to concatenate (CONCAT()) the values from gadget_name, currency symbol ($), and price columns in a single column (product_details).

SELECT CONCAT(gadget_name, ' - $', price) AS product_details FROM electronic_products;

The output below confirms that you’ve successfully manipulated string data into a single column for better representation.

Leveraging concatenation string function
Leveraging concatenation string function

2. Next, run the following queries to convert the strings in your gadget_name column to UPPER or LOWER case and display them in a column named product_names.

The upper and lower conversions can be beneficial in data cleaning processes. For instance, you might have a dataset with inconsistent product names, with some written in uppercase and others in lowercase letters.

SELECT UPPER(gadget_name) AS product_names FROM electronic_products;
SELECT LOWER(gadget_name) AS product_names FROM electronic_products;
Converting all gadget names to uppercase
Converting all gadget names to uppercase
Converting all gadget names to lowercase
Converting all gadget names to lowercase

3. Moving on, execute any of the queries below to return a specified number of characters (i.e., 2) from either the start (LEFT()) or the end (RIGHT()) of a string. These queries display the returned characters in a column called prefixes.

The LEFT() and RIGHT() functions come in handy in cases where you need to extract specific parts of data for further analysis or display purposes. One example is having data that contains multiple values within a single column.

SELECT gadget_name, LEFT(gadget_name, 2) AS prefixes FROM electronic_products;
SELECT gadget_name, RIGHT(gadget_name, 2) AS suffixes FROM electronic_products;
Leveraging the LEFT() function
Leveraging the LEFT() function
Leveraging the RIGHT() function
Leveraging the RIGHT() function

Working with Date Values via the Date/Time Functions

Beyond the realm of string data, SQL functions open doors to a treasure trove of insights, especially when dealing with date values. The exciting part? SQL functions amplify your mastery over date and time manipulations, date format conversion, date part extraction, and more.

To work with date values via SQL functions, continue with the listed steps:

1. Execute the query below, which returns the name of the weekday (DAYNAME()) as a string from a given date (date_added) to a column called day_added.

This query lets you retrieve the day of the week each gadget was added to your dataset.

SELECT gadget_name, DAYNAME(date_added) AS day_added FROM electronic_products;

This information can be invaluable for tracking trends in product additions based on specific weekdays.

Leveraging the DAYNAME() function
Leveraging the DAYNAME() function

2. Similarly, run the following queries with the MONTHNAME(), YEAR(), and WEEK() functions to extract specific parts of a date. This approach allows you to analyze data trends over weeks, months, and years.

-- Query 1: Retrieve the gadget name and the month it was added.
SELECT gadget_name, MONTHNAME(date_added) AS month_added FROM electronic_products;

-- Query 2: Retrieve the gadget name and the year it was added.
SELECT gadget_name, YEAR(date_added) AS year_added FROM electronic_products;

-- Query 3: Retrieve the gadget name and the week of the year it was added.
SELECT gadget_name, WEEK(date_added) AS week_added FROM electronic_products;

These queries showcase the flexibility of SQL date functions in extracting specific temporal information, allowing for a more granular analysis of data trends.

Retrieve data based on the month it was added
Retrieve data based on the month it was added
Retrieve data based on the year it was added
Retrieve data based on the year it was added
Retrieve data based on the week it was added
Retrieve data based on the week it was added

3. Lastly, run the query below to calculate the difference (DATEDIFF()) between two dates to determine how many days have passed since a gadget was added.

This query returns a column named days_passed with the number of days since each gadget’s addition.

SELECT gadget_name, DATEDIFF(CURRENT_DATE(), date_added) AS days_passed FROM electronic_products;
Leveraging the DATEDIFF() function
Leveraging the DATEDIFF() function

Dealing with Large Datasets Using Aggregate Functions

In addition to individual record-level operations, MySQL offers a set of powerful aggregate functions. These functions allow you to perform calculations on groups of records and acquire valuable summary insights from your data.

Aggregate functions are handy when dealing with large datasets or when you need to derive aggregated information from your data.

To calculate large datasets using aggregate functions, perform the following:

Execute the following query to return a single value AS total_price representing the SUM of all prices in your dataset. This kind of aggregation provides a quick and essential overview of your data.

SELECT SUM(price) AS total_price FROM electronic_products;
Leveraging the SUM() function
Leveraging the SUM() function

Finally, run the query below to return the count of electronic products, minimum, maximum, and average prices in a single result set.

Below are the aggregate functions that make up the query for data manipulation and analysis:

COUNT()Returns the number of records in a dataset, including NULL values. For instance, find the total number of electronic products.
MIN()Returns the minimum value in a numeric column. In this case, discover the lowest-priced electronic product.
MAX()In contrast with the MIN() function, this function returns the maximum value in a numeric column. For this example, identify the highest-priced electronic product.
AVG()Calculates the average of a numeric column, like the average price of electronic products.

Combining these aggregate functions in a single query gives you a comprehensive summary of your data.

SELECT COUNT(gadget_name) AS count, MIN(price) as min_price, MAX(price) AS max_price, AVG(price) AS avg_price FROM electronic_products;
Leveraging aggregate functions
Leveraging aggregate functions


As the curtains draw on your journey through the intricacies of SQL functions, take a moment to reflect on the skills you’ve acquired. From mastering mathematical and numerical functions to seamlessly manipulating string data. You dived into the depths of date and time functions and conquered large datasets with aggregate functions.

You’ve explored SQL’s powerful capabilities comprehensively, but why not consider how you can apply these skills in your own unique projects? Perhaps learn more about MySQL’s advanced features, such as stored procedures, triggers, and views?

Keep practicing and experimenting to improve your database management capabilities!

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!