Skip to main content

What is a function in SQL?

A function in SQL is a ready-made command or set of commands that performs a specific action and returns a result.

Functions come in two kinds:

  1. Built-in, already part of SQL. For example:
  • COUNT(), counts the number of rows;
  • SUM(), computes a total;
  • NOW(), returns the current time;
  • UPPER(), converts text to uppercase.
  1. User-defined, created by a developer to reuse logic.

Example

sql
CREATE FUNCTION get_full_name(first_name VARCHAR, last_name VARCHAR) RETURNS VARCHAR AS BEGIN RETURN CONCAT(first_name, ' ', last_name); END;

You can then call it like this:

sql
SELECT get_full_name('Ivan', 'Petrov');

Functions help you avoid repeating the same code and make queries shorter and clearer.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.