The Wayback Machine - https://web.archive.org/web/20240616072239/https://www.geeksforgeeks.org/sql-functions-aggregate-scalar-functions/
Open In App

SQL Functions (Aggregate and Scalar Functions)

Last Updated : 17 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

SQL Functions are built-in programs that are used to perform different operations on the database.

There are two types of functions in SQL:

  • Aggregate Functions
  • Scalar Functions

SQL Aggregate Functions

SQL Aggregate Functions operate on a data group and return a singular output. They are mostly used with the GROUP BY clause to summarize data. 

Some common Aggregate functions with Syntax and description are shown in the table below.

Aggregate Function Description Syntax
AVG() Calculates the average value SELECT AVG(column_name) FROM table_name;
COUNT() Counts the number of rows SELECT COUNT(column_name) FROM table_name
FIRST() Returns the first value in an ordered set of values SELECT FIRST(column_name) FROM table_name;
LAST() Returns the last value in an ordered set of values SELECT LAST(column_name) FROM table_name;
MAX() Retrieves the maximum value from a column SELECT MAX(column_name) FROM table_name;
MIN() Retrieves the minimum value from a column SELECT MIN(column_name) FROM table_name;
SUM() Calculates the total sum of values in a numeric column SELECT SUM(column_name) FROM table_name;

SQL Scalar functions

SQL Scalar Functions are built-in functions that operate on a single value and return a single value.

Scalar functions in SQL helps in efficient data manipulation and simplification of complex calculations in SQL queries.

Scalar function Description Syntax
UCASE() Converts a string to uppercase SELECT UCASE(column_name) FROM table_name;
LCASE() Converts a string to lowercase SELECT LCASE(column_name) FROM table_name;
MID() Extracts a substring from a string SELECT MID(column_name, start, length) FROM table_name;
LEN() Returns the length of a string SELECT LEN(column_name) FROM table_name;
ROUND() Rounds a number to a specified number of decimals SELECT ROUND(column_name, decimals) FROM table_name;
NOW() Returns the current date and time SELECT NOW();
FORMAT() Formats a value with the specified format SELECT FORMAT(column_name, format) FROM table_name;

SQL Functions Examples

Let’s look at some examples of SQL Functions. We will cover examples of SQL aggregate functions and scalar functions.

We will perform queries on the given SQL table:

student table

Aggregate Functions Examples

Let’s look at the examples of each aggregate function in SQL.

AVG() Function Example

Computing average marks of students. 

Query:

SELECT AVG(MARKS) AS AvgMarks FROM Students; 

Output: 

AvgMarks
80

COUNT() Function Example

Computing total number of students. 

Query: 

SELECT COUNT(*) AS NumStudents FROM Students;

Output: 

NumStudents
5

FIRST() Function Example

Fetching marks of first student from the Students table. 

Query:

SELECT FIRST(MARKS) AS MarksFirst FROM Students;

Output: 

MarksFirst
90

LAST() Function Example

Fetching marks of last student from the Students table. 

Query:

SELECT LAST(MARKS) AS MarksLast FROM Students;

Output: 

MarksLast
85

MAX() Function Example

Fetching maximum marks among students from the Students table. 

Query:

SELECT MAX(MARKS) AS MaxMarks FROM Students;

Output: 

MaxMarks
95

MIN() Function Example

Fetching minimum marks among students from the Students table. 

Query:

SELECT MIN(MARKS) AS MinMarks FROM Students;

Output: 

MinMarks
50

SUM() Function Example

Fetching summation of total marks among students from the Students table.

Query: 

SELECT SUM(MARKS) AS TotalMarks FROM Students;

Output: 

TotalMarks
400

Scalar Functions Examples

Let’s look at some examples of each Scalar Function in SQL.

UCASE() Function Example

Converting names of students from the table Students to uppercase. 

Query:

SELECT UCASE(NAME) FROM Students;

Output: 

NAME
HARSH
SURESH
PRATIK
DHANRAJ
RAM

LCASE() Function Example 

Converting names of students from the table Students to lowercase. 

Query:

SELECT LCASE(NAME) FROM Students;

Output: 

NAME
harsh
suresh
pratik
dhanraj
ram

MID() Function Example

Fetching first four characters of names of students from the Students table. 

Query:

SELECT MID(NAME,1,4) FROM Students; 

Output: 

NAME
HARS
SURE
PRAT
DHAN
RAM

LEN() Function Example 

Fetching length of names of students from Students table. 

Query:

SELECT LENGTH(NAME) FROM Students;

Output: 

NAME
5
6
6
7
3

ROUND() Function Example 

Fetching maximum marks among students from the Students table. 

Query:

SELECT ROUND(MARKS,0) FROM Students; 

Output: 

MARKS
90
50
80
95
85

NOW() Function Example 

Fetching current system time. 

Query:

SELECT NAME, NOW() AS DateTime FROM Students; 

Output: 

NAME DateTime
HARSH 1/13/2017 1:30:11 PM
SURESH 1/13/2017 1:30:11 PM
PRATIK 1/13/2017 1:30:11 PM
DHANRAJ 1/13/2017 1:30:11 PM
RAM 1/13/2017 1:30:11 PM

FORMAT() Function Example 

Formatting current date as ‘YYYY-MM-DD’. 

Query:

SELECT NAME, FORMAT(Now(),'YYYY-MM-DD') AS Date FROM Students; 

Output: 

NAME Date
HARSH 2017-01-13
SURESH 2017-01-13
PRATIK 2017-01-13
DHANRAJ 2017-01-13
RAM 2017-01-13

 Important Points About SQL Functions

  • SQL functions are built-in programs that are used to manipulate data in various ways.
  • There are different types of SQL functions – Aggregate functions and Scalar functions.
  • Aggregate functions perform calculations on a group of values and return a single value. Example SUM, AVG, COUNT.
  • Scalar functions operate on a single value and return a single value. Example UPPER, LOWER, SUBSTRING.
  • SQL functions can be used in different SQL statements, such as SELECT, WHERE, GROUP BY, and ORDER BY, to improve data processing and analysis.


Previous Article
Next Article

Similar Reads

SQL Date and Time Functions
In SQL, dates are complicated for newbies, since while working with a database, the format of the data in the table must be matched with the input data to insert. In various scenarios instead of date, datetime (time is also involved with date) is used. For storing a date or a date and time value in a database,MySQL offers the following data types:
3 min read
SQL using Python and SQLite | Set 2
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web, and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to S
3 min read
SQL software and query optimization tools
Introduction : SQL stands for Structured Query Language. SQL is a non-procedural language, so the Optimizer is free to merge, reorganize and process in any order. It is based on statistics collected about accessed data. It is very useful to perform query and to store and manage data in RDBMS. SQL is a language to operate databases. It includes data
4 min read
Performing Database Operations in Java | SQL CREATE, INSERT, UPDATE, DELETE and SELECT
In this article, we will be learning about how to do basic database operations using JDBC (Java Database Connectivity) API in Java programming language. These basic operations are INSERT, SELECT, UPDATE, and DELETE statements in SQL language. Although the target database system is Oracle Database, the same techniques can be applied to other databas
6 min read
Basic SQL Injection and Mitigation with Example
SQL injection is a code injection technique, used to attack data driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker). SQL Injection can be used in a range of ways to cause serious problems. By levering SQL Injection, an attacker could bypass authe
4 min read
SQL Interview Questions | Set 2
Difference between Locking, Blocking and Deadlocking Locking: Locking occurs when a connection needs access to a piece of data in a database and it locks it for certain use so that no other transaction is able to access it. Blocking: Blocking occurs when a transaction tries to acquire an incompatible lock on a resource that another transaction has
5 min read
SQL | Intersect & Except clause
1. INTERSECT clause : As the name suggests, the intersect clause is used to provide the result of the intersection of two select statements. This implies the result contains all the rows which are common to both the SELECT statements. Syntax : SELECT column-1, column-2 â€Ķâ€Ķ FROM table 1 WHEREâ€Ķ.. INTERSECT SELECT column-1, column-2 â€Ķâ€Ķ FROM table 2 WHE
1 min read
Program for Fibonacci numbers in PL/SQL
The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, â€Ķâ€Ķ.. In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-1 with seed values F0= 0 and F1 = 1. Given a number n, print n-th Fibonacci Number. Input : n = 2 Output : 1 Inpu
1 min read
SQL | Sub queries in From Clause
From clause can be used to specify a sub-query expression in SQL. The relation produced by the sub-query is then used as a new relation on which the outer query is applied. Sub queries in the from clause are supported by most of the SQL implementations.The correlation variables from the relations in from clause cannot be used in the sub-queries in
2 min read
Check if a number is Palindrome in PL/SQL
Given an integer, write a function that returns true if the given number is palindrome, else false. For example, 12321 is palindrome, but 1451 is not palindrome. Let the given number be num. A simple method for this problem is to first reverse digits of num, then compare the reverse of num with num. If both are same, then return true, else false. E
1 min read
Article Tags :
Practice Tags :