Junior — Middle
Can you explain what an aggregate function is in the context of databases and how it is used in query execution?
sobes.tech AI
Answer from AI
An aggregate function in databases is a function that takes a set of values from one or more rows and returns a single summary value. It is used for calculating summary data, such as sum, average, maximum, or count of records.
Examples of aggregate functions:
COUNT()— number of rowsSUM()— sum of valuesAVG()— average valueMAX()— maximum valueMIN()— minimum value
In queries, aggregate functions are often used together with GROUP BY to group data by certain fields.
Example in Node.js using an SQL query:
const { Client } = require('pg');
const client = new Client();
async function getAverageSalary() {
await client.connect();
const res = await client.query('SELECT AVG(salary) AS avg_salary FROM employees');
console.log('Average salary:', res.rows[0].avg_salary);
await client.end();
}
getAverageSalary();
Here, AVG(salary) calculates the average salary of all employees.