Generally speaking, we all hear about the functions or procedures in programming languages. However, I just found out that I use these terms almost interchangeably (which is probably very wrong).
So, my question is:
What is the difference in terms of their functionality, their purpose and use?
An example would be appreciated.
A function returns a value and a procedure just executes commands.
The name function comes from math. It is used to calculate a value based on input.
A procedure is a set of command which can be executed in order.
In most programming languages, even functions can have a set of commands. Hence the difference is only in the returning a value part.
But if you like to keep a function clean, (just look at functional languages), you need to make sure a function does not have a side effect.
In general, a procedure is a sequence of instructions.
A function can be the same, but it usually returns a result.
This depends on the context.
In Pascal-like languages, functions and procedures are distinct entities, differing in whether they do or don't return a value. They behave differently wrt. the language syntax (eg. procedure calls form statements; you cannot use a procedure call inside an expression vs. function calls don't form statements, you must use them in other statements). Therefore, Pascal-bred programmers differentiate between those.
In C-like languages, and many other contemporary languages, this distinction is gone; in statically typed languages, procedures are just functions with a funny return type. This is probably why they are used interchangeably.
In functional languages, there is typically no such thing as a procedure - everything is a function.
Procedures and functions are both subroutines the only difference between them is that a procedure returns multiple (or at least can do) values whereas a function can only return one value (this is why function notation is used in maths as usually only one value is found at one given time) although some programming languages do not follow these rules this is their true definitions
Basic Differences
Advanced Differences
In SQL:
SELECT
as well as DML (INSERT
,UPDATE
,DELETE
) statements in it, whereas Function allows onlySELECT
statement in it.SELECT
statement, whereas Functions can be embedded in aSELECT
statement.WHERE
(or aHAVING
or aSELECT
) block, whereas Functions can.JOIN
block with other tables.JOIN
blocks and other Rowset operations.In the context of db: Stored procedure is precompiled execution plan where as functions are not.