Create a MySQL function and find the average of values in a column

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable638 (Name varchar(100),Marks int);
Query OK, 0 rows affected (0.68 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable638 values('John',67);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable638 values('John',90);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable638 values('David',99);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable638 values('John',60);
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable638;

This will produce the following output −

+-------+-------+
| Name  | Marks |
+-------+-------+
| John  | 67    |
| John  | 90    |
| David | 99    |
| John  | 60    |
+-------+-------+
4 rows in set (0.00 sec)

Following is the query to create a function that returns an average −

mysql> set global log_bin_trust_function_creators=1;
Query OK, 0 rows affected (0.28 sec)
mysql> DELIMITER //
mysql> CREATE FUNCTION getAverageDemo()
   RETURNS INT
   BEGIN DECLARE value INT;
      SELECT AVG(Marks) INTO value from DemoTable638 WHERE Name="John";
      RETURN value;
   END;
   //
Query OK, 0 rows affected (0.35 sec)
mysql> DELIMITER ;

Now you can call the function using select statement −

mysql> select getAverageDemo();

This will produce the following output −

+------------------+
| getAverageDemo() |
+------------------+
| 72               |
+------------------+
1 row in set (0.01 sec)
raja
Published on 23-Aug-2019 08:36:27
Advertisements