keepcalculator

06 Numbers and Powers

Formulas to Query a Table? SQL Basics

Card No. 06·8196 · Updated · Standard formula, shown below

This article explains the core formulas and functions used to query a table in SQL, covering everything from simple SELECT statements to aggregate functions and JOINs. You’ll learn the syntax, see concrete examples, and understand how to choose the right formula for your data retrieval needs.

What Is a SQL Query Formula?

In SQL, a “formula” isn’t a single equation but a structured command, or query, that tells the database exactly what data to retrieve, filter, calculate, or combine. The most basic query formula is the SELECT statement, which has the form: SELECT column1, column2 FROM table_name WHERE condition;. Each part of this statement acts like a variable in a formula, determining the final result set.

The Anatomy of a SELECT Query

Every SQL query, no matter how complex, is built from a few fundamental clauses. Understanding these is key to writing effective formulas.

  • SELECT – Specifies which columns to return. Use * to return all columns.
  • FROM – Identifies the table(s) to query.
  • WHERE – Filters rows based on a condition (e.g., WHERE age > 18).
  • GROUP BY – Groups rows that have the same values in specified columns, often used with aggregate functions.
  • HAVING – Filters groups after aggregation (like WHERE, but for groups).
  • ORDER BY – Sorts the result set by one or more columns (ASC or DESC).
  • LIMIT (or TOP) – Restricts the number of rows returned.

Aggregate Functions: The Core Formulas

When you need to calculate a single value from a column, you use aggregate functions. These are the closest thing to traditional math formulas in SQL.

  • COUNT() – Returns the number of rows (e.g., SELECT COUNT(*) FROM orders;).
  • SUM() – Adds up all values in a numeric column (e.g., SELECT SUM(amount) FROM payments;).
  • AVG() – Calculates the average of a numeric column (e.g., SELECT AVG(price) FROM products;).
  • MIN() and MAX() – Return the smallest and largest values (e.g., SELECT MIN(stock), MAX(stock) FROM inventory;).

These functions ignore NULL values (except COUNT(*), which counts all rows). They are typically used with GROUP BY to get per-category results.

Filtering and Calculating with WHERE and Arithmetic

You can use arithmetic operators (+, -, *, /) directly in SELECT to create calculated columns. For example, to calculate total price with tax:

SELECT quantity, price, quantity * price AS subtotal FROM order_items;

The WHERE clause filters rows before any calculation. For instance, to get only orders over $100:

SELECT order_id, total FROM orders WHERE total > 100;

You can also use string functions like CONCAT(), UPPER(), or LOWER() to manipulate text, and date functions like YEAR() or DATEDIFF() to work with dates.

Joining Tables: Combining Data from Multiple Sources

Real-world data is often spread across multiple tables. JOIN clauses are the formulas that bring them together.

  • INNER JOIN – Returns rows where there is a match in both tables.
  • LEFT JOIN – Returns all rows from the left table, and matched rows from the right table; if no match, NULLs appear.
  • RIGHT JOIN – The opposite of LEFT JOIN.
  • FULL OUTER JOIN – Returns all rows when there is a match in either table.

Example: SELECT customers.name, orders.amount FROM customers INNER JOIN orders ON customers.id = orders.customer_id;

How to Choose the Right Query Formula

Selecting the correct formula depends on your goal:

  1. Retrieve specific rows? Use SELECT with WHERE.
  2. Summarize data? Use aggregate functions with GROUP BY.
  3. Combine tables? Use JOIN.
  4. Filter groups? Use HAVING after GROUP BY.
  5. Sort results? Add ORDER BY.

Always test your query on a small dataset first, and use aliases (AS) to make output readable.

Common Mistakes and How to Avoid Them

  • Forgetting WHERE vs. HAVING – WHERE filters rows before grouping; HAVING filters groups after. Use HAVING with aggregate functions.
  • Mixing data types – Ensure you compare compatible types (e.g., numbers with numbers, strings with strings).
  • NULL handling – Use IS NULL or COALESCE() to deal with NULLs; NULL = NULL is not true.
  • Missing GROUP BY columns – When using GROUP BY, every selected column must either be in the GROUP BY clause or inside an aggregate function.
  • Using SELECT * in production – It can slow down queries and return unnecessary data. Specify columns explicitly.

Frequently Asked Questions

What is the difference between WHERE and HAVING?

WHERE filters individual rows before any grouping or aggregation occurs. HAVING filters groups after aggregation. For example, to find products with an average price above $50, you use HAVING AVG(price) > 50, not WHERE.

How do I use a formula to count distinct values?

Use COUNT(DISTINCT column_name). For example, SELECT COUNT(DISTINCT customer_id) FROM orders; returns the number of unique customers.

Can I use arithmetic in a WHERE clause?

Yes, you can use arithmetic in WHERE, but it’s often more efficient to calculate on the column side. For example, WHERE price * quantity > 100 is valid. However, using functions on columns can prevent index usage, so test performance.

How do I join more than two tables?

You can chain JOINs: SELECT ... FROM table1 JOIN table2 ON ... JOIN table3 ON .... Each JOIN builds on the previous result.

What does the LIMIT clause do?

LIMIT restricts the number of rows returned. For example, LIMIT 10 returns only the first 10 rows. It’s often used with ORDER BY to get top-N results.

Is there a formula to find duplicate rows?

Use GROUP BY with HAVING COUNT(*) > 1. For example: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1; lists duplicate emails.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →