What is a function?
- SQL course
- Advanced
- Lesson 42/81
- 4 min
Learn routines that return a scalar value.
What is a function?
A function is SQL code that returns a value. Called inside a query.
CREATE FUNCTION get_tax(price DECIMAL)
RETURNS DECIMAL
LANGUAGE SQL
AS $$
SELECT price * 0.18;
$$;Function that computes tax.
The function get_tax is created. The expression price * 0.18 is evaluated and returned.
What is a function? — details
A function returns a value; a procedure does work. A function is used inside queries.
For example, get_tax(price) computes the tax for each row and is used like a column in SELECT name, get_tax(price) FROM products.
Practice What is a function?
Create a get_tax function: return 18% of the price.
Starter code
-- create function
CREATESample solution
CREATE FUNCTION get_tax(price DECIMAL)
RETURNS DECIMAL
LANGUAGE SQL
AS $$
SELECT price * 0.18;
$$;Expected output
Function oluşturuldu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a function return?
- A table
- A value Correct answer
- A view
- An index
Explanation: A function returns a value.
2 Add RETURNS
CREATE FUNCTION get_tax(price DECIMAL)
____ DECIMAL
CREATE FUNCTION get_tax(price DECIMAL)
RETURNS DECIMAL
Explanation: RETURNS is the right answer.
3 What is a function: match the terms
| Term | Meaning |
|---|---|
function |
function |
RETURNS |
returns |
procedure |
procedure |
value |
result |