DBA Magic -- Doing Math with SQL
SQL (Structured Query Language) is not just for querying data; it also has robust mathematical capabilities that allow you to perform various calculations directly within your queries. Here’s an overview of how to perform mathematical operations in SQL, along with examples.
1. Basic Arithmetic Operations
SQL supports the four basic arithmetic operations: addition, subtraction, multiplication, and division. You can use these operators directly in your SQL queries.
- Addition (+):
SELECT price, quantity, (price * quantity) AS total_cost
FROM products;
SELECT employee_id, salary, (salary - deductions) AS net_salary
FROM employees;
SELECT item, price, quantity, (price * quantity) AS total_price
FROM inventory;
SELECT sales, expenses, (sales / expenses) AS profit_margin
FROM financials;
2. Aggregate Functions
SQL provides built-in aggregate functions that perform calculations on a set of values and return a single value. Common aggregate functions include SUM(), AVG(), COUNT(), MIN(), and MAX().
- SUM(): Calculates the total sum of a numeric column.
SELECT SUM(sales) AS total_sales
FROM orders;
SELECT AVG(salary) AS average_salary
FROM employees;
SELECT COUNT(*) AS total_orders
FROM orders
WHERE status = 'completed';
SELECT MIN(price) AS lowest_price, MAX(price) AS highest_price
FROM products;
3. Using Mathematical Functions
SQL also includes various mathematical functions that can be used for more advanced calculations.
- ROUND(): Rounds a number to a specified number of decimal places.
SELECT ROUND(price, 2) AS rounded_price
FROM products;
SELECT item, price, POWER(price, 2) AS price_squared
FROM products;
SELECT price, SQRT(price) AS sqrt_price
FROM products;
SELECT amount, ABS(amount) AS absolute_value
FROM transactions;
4. Combining Calculations with GROUP BY
SELECT category, SUM(sales) AS total_sales, AVG(price) AS average_price
FROM products
GROUP BY category;
5. Filtering with HAVING
SELECT category, SUM(sales) AS total_sales
FROM products
GROUP BY category
HAVING SUM(sales) > 1000;
6. Using Calculated Columns
SELECT employee_id, salary, (salary * 0.1) AS bonus
FROM employees;
7. Working with Dates and Times
- Date Arithmetic: Add or subtract intervals from dates.
SELECT order_date, (order_date + INTERVAL '30 DAY') AS delivery_date
FROM orders;
SELECT DATEDIFF(NOW(), hire_date) AS days_since_hired
FROM employees;
Conclusion
Doing math with SQL allows you to perform a variety of calculations, from simple arithmetic to complex aggregations and functions. Understanding how to leverage these capabilities can help you analyze data more effectively and generate meaningful insights directly from your database.

Comments
Post a Comment