0% found this document useful (0 votes)
32 views13 pages

An Introduction To SQL Functions (Slides)

SQL functions allow for complex calculations and data manipulations directly in queries. They provide efficiency, reliability, extensive functionality, and ease of use. Aggregate functions summarize column values, scalar functions operate on each row individually, and window functions have aspects of both. An example uses the SUM aggregate function to find the total expenditure in the Free State province by summing the values in the Free State column.

Uploaded by

Nyero Akporehe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
32 views13 pages

An Introduction To SQL Functions (Slides)

SQL functions allow for complex calculations and data manipulations directly in queries. They provide efficiency, reliability, extensive functionality, and ease of use. Aggregate functions summarize column values, scalar functions operate on each row individually, and window functions have aspects of both. An example uses the SUM aggregate function to find the total expenditure in the Free State province by summing the values in the Free State column.

Uploaded by

Nyero Akporehe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

SQL numeric functions

An introduction to SQL functions


Please do not copy without permission. © ExploreAI 2023.
Introduction to SQL functions

What are SQL functions? 01.

|
SQL functions are built-in operations that can be used to perform various calculations,
manipulations, or transformations on data within a SQL database. Advantages of using these
functions include:

01.
01. Efficiency 01.
04. Extensive functionality
They take advantage of internal algorithms and data Database management systems provide a wide range of
structures which results in faster query execution times and built-in functions that allow for complex calculations, string
improved overall performance. manipulations, and date and time operations.

01.
02. Reliability and compatibility 01.
05. Portability
They adhere to the SQL standards and are implemented SQL queries use standard functions, therefore they can be
consistently across different database platforms. easily migrated or executed on different database systems
without significant modifications.

01.
03. Documentation and built-in support 06. Ease of use
They come with extensive documentation provided by the They are readily available for use without any additional
database management system vendors, making them configuration. This saves you from reinventing the wheel by
easier for developers to understand and use effectively. implementing common operations from scratch.
2
Introduction to SQL functions

Syntax of SQL functions

| The output of a function in SQL is treated as a derived column and appears in the SELECT
clause of a query. The general syntax of an SQL function is:

This defines the specific SQL function we


want to use, such as SUM or COUNT.

These are the input arguments that the


SELECT function requires. Some functions do not
Column1, require any arguments while others require
Function_name (Arguments) AS Named_result one or more arguments.
FROM
Database_name.Table_name
It is good practice to name function results
descriptively with prefixes that explain the
function, e.g. total_sales for SUM(sales).

3
Introduction to SQL functions

Function types

| Functions can be categorised by what input they take.

123 Numeric
These functions perform calculations on a set of values in a
abc column and return a numerical value.
SUM(), AVG(), COUNT(), MAX(), MIN(), POWER(),
SQRT(), ROUND()

String
These functions operate on string values and perform operations
such as concatenation, manipulation, and text formatting.
CONCAT(), LENGTH(), SUBSTRING(), UPPER(), LOWER()

4
Introduction to SQL functions

Function types
Datetime
These are functions used to handle date and time values and
perform operations like formatting, extraction, and manipulation.
CURRENT_DATE(), DATEADD(), FORMAT()

123

Conditional flow
Misc abc
These functions allow for conditional logic in your SQL queries.
CASE(), IF(), IIF()

IF()
Miscellaneous
This category represents a variety of functions that do a variety
Many functions do not fit this classification! For example,
MIN() works with strings, numbers, and dates. Focus on of things such as converting data types and dealing with NULL
understanding how each function works, rather than classifying values.
them. CONVERT(), CAST(), NULLIF(), IFNULL()

5
Introduction to SQL functions

How functions behave

| SQL functions vary in behaviour. Aggregate functions summarise data at a column level. Scalar
functions manipulate data at the row level.

Patient_id Born FLOOR(Born) Scalar functions take a row and return a single value for each
row, e.g. UPPER(), LOWER(), CONVERT(), CAST(), IF(),
1 1969 1960
FORMAT() and arithmetic operators () +, -, *, /
3 1972 1970
Example:
7 1954 1950
FLOOR(Born) rounds the values in each row down to the nearest
8 2004 2000 integer. Each row has a new decade column with the output of
FLOOR().

AVG(Born) Aggregate functions take a set of rows as input and return a


single summary value, e.g. SUM(), AVG(), COUNT(), MAX(),
1973.5 MIN()

Window functions are a third way in which functions Example:


can behave which is a “hybrid” of aggregate and scalar AVG(Born) calculates the average of the values in born, and
functions. returns a single summary value of the column.
6
Introduction to SQL functions

Example data

To find the total amount of income expenditure in the Free State province in South Africa, we are going to use
the South African Household Income and Expenditure Survey dataset (SAHIES).

The table is named Income_expenditure_2020 in the Sahies database:

Expenditure_group Western Northern Free_state Kwazulu_natal North_west … Mpumalanga Limpopo


_cape _cape

Housing 16400 20000 24799 21200 21200 … 22799 23599

Recreation 1521 989 1255 1217 1179 … 1065 912

Transport 17974 15406 11983 13481 12625 … 12839 13481

7
Introduction to SQL functions

Example: Aggregate functions

| SUM() is an aggregate function that returns the total sum of a numeric column.

Free_state

24799
SELECT
SUM(Free_state) AS Total_free_state SUM 1255 = 38037
Query
` FROM
Sahies.Income_expenditure_2020; 11983

Total_free_state We see that our query returns a


Output single value which is the sum of all
38037 rows of the Free_state column.

8
Introduction to SQL functions

Example: Multiple aggregate functions

| We can aggregate multiple columns or the same column using a different function.

Suppose we want to calculate the total income spent for the Western and Free State provinces and the average spent for the Free
State province.

SELECT
By not naming the
SUM(Western_cape) AS Total_spent_western_cape,
average spent in the
SUM(Free_state) AS Total_spent_Free_state, Free State, it is assigned
Query AVG(Free_state) a default name that may
FROM not be as descriptive.
Sahies.Income_expenditure_2020;

Total_spent_western_cape Total_spent_Free_state AVG(Free_state)


Output
35895 38037 12679.0000

9
Introduction to SQL functions

Example: Multiple aggregate functions

| Since aggregate functions produce a single row, we cannot use them with the columns in our
main table.

SELECT
Free_state, Free_state has 3 rows,
AVG(Free_state) and AVG(Free_state)
Query FROM
has 1, so running this
query results in an error.
Sahies.Income_expenditure_2020;

Output Error!

10
Introduction to SQL functions

Example: Scalar functions

| Suppose we want to calculate the difference in income expenditure between the Free State
and the Northern Cape province.

SELECT Free_state Northern_cape

Expenditure_group,
24799
- 20000
(Free_state
Query -
- Northern_cape) AS Diff_fs_and_nc 1255 989
FROM -
Sahies.Income_expenditure_2020; 11983 15406

Expenditure_group Diff_fs_and_nc
Note how this name is slightly harder to
Housing 4799 understand because we used abbreviations.

Output Recreation 266


We see that the calculation occurred on a row level because
Transport -3423 the results set includes a value for each row.

11
Introduction to SQL functions

Using functions together

|
We can use functions within functions, known as nesting. SQL evaluates the innermost function first
and then works its way outwards. The result of each inner function is used as the input for the outer
function.

SELECT ROUND() rounds a value


SUM(Western_cape) AS Total_spent_western_cape, to the specified amount of
decimals.
SUM(Northern_cape) AS Total_spent_northern_cape,
AVG(Free_state) is
Query ROUND(AVG(Free_state),0) AS Average_spent_free_state
calculated first, then
FROM rounded to 0 decimal
Sahies.Income_expenditure_2020; places.

Total_spent_western_cape Total_spent_northern_cape Average_spent_free_state


Output
35895 36395 12679

12
Introduction to SQL functions

SQL functions without input arguments

| Some SQL built-in functions do not require any arguments. They are used to perform
calculations or retrieve information.

CURRENT_DATE()
Returns the current date. Output:
CURRENT_DATE()
SELECT
Query: 2023-06-20
CURRENT_DATE();

Output:
RAND()
Generates a random number between 0 and 1. Limpopo Random_number

23599 0.81247…
SELECT
Query: Free_state, 912 0.01824…

RAND() AS Random_number FROM…; 13481 0.55863…

13

You might also like