MySQL query to find the average of only first three values from a column with five values


For this, you can use a subquery. Let us first create a table −

mysql> create table DemoTable
(
   Score int
);
Query OK, 0 rows affected (0.62 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(80);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(45);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(55);
Query OK, 1 row affected (0.33 sec)
mysql> insert into DemoTable values(78);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Score |
+-------+
|    80 |
|    45 |
|    55 |
|    78 |
|    88 |
+-------+
5 rows in set (0.00 sec)

Following is the query to find the average of only the first three column values. Here, we are using LIMIT 3 to find the average of only three records −

mysql> select avg(Score)
   from ( select Score from DemoTable limit 3) tbl;

This will produce the following output −

+------------+
| avg(Score) |
+------------+
| 60.0000    |
+------------+
1 row in set (0.00 sec)

Updated on: 04-Oct-2019

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements