Tutorials Logic, IN info@tutorialslogic.com

MySQL Functions String, Date, Aggregate Functions

MySQL Function Semantics

MySQL functions transform values in expressions, filters, grouping, ordering, and projections. Scalar functions return one result per input row; aggregate functions summarize a group. NULL propagation, collation, time zone, and implicit conversion can change apparently simple results.

Query-Time Transformation

Reports often need month labels, totals, fallback values, rounded amounts, or combined names. Functions compute those values near the data.

  • String functions format text.
  • Date functions create reporting buckets.
  • Aggregate functions summarize rows.

Aggregates and GROUP BY

COUNT, SUM, AVG, MIN, and MAX turn many rows into summaries. GROUP BY defines the level of summary.

  • Count orders per customer.
  • Sum monthly revenue.
  • Average product ratings.

Performance Trade-offs

Functions are useful, but wrapping indexed columns in WHERE can make indexes harder to use. Large tables deserve EXPLAIN review.

  • Prefer range filters over DATE(column) filters on indexed timestamps.
  • Use generated columns for repeated computed filters.
  • Keep presentation-only formatting out of hot queries when possible.

Query Planning

Wrapping an indexed column in a function inside WHERE can prevent an ordinary index range lookup. Rewrite date filters as ranges when possible, or create an appropriate functional/generated-column index after measuring the query plan. Compare EXPLAIN output before and after the rewrite, including access type, chosen key, estimated rows, and any temporary sorting. Do not optimize by guesswork.

Aggregate functions ignore NULL except COUNT(*), which counts rows. Use GROUP BY to define the intended groups and HAVING for predicates on aggregate results. Store timestamps and convert zones deliberately rather than relying on a session default.

Function Families

Family Examples Result Scope
String CONCAT, LOWER, TRIM, SUBSTRING One value per input row.
Numeric ABS, ROUND, CEIL, MOD One value per input row.
Date and time DATE_ADD, TIMESTAMPDIFF, CONVERT_TZ Depends on type and session time-zone rules.
Conditional and NULL CASE, COALESCE, NULLIF Selects or replaces values deliberately.
Aggregate COUNT, SUM, AVG, MIN, MAX One value per group.
Window ROW_NUMBER, LAG, SUM OVER Keeps detail rows while calculating across a window.

NULL and Determinism

Most scalar expressions involving NULL return NULL. COALESCE chooses the first non-NULL expression, while NULLIF returns NULL when two expressions compare equal. Use IS NULL for tests; equality with NULL produces UNKNOWN.

Functions such as NOW depend on statement time, RAND is nondeterministic, and collation affects text comparisons. Those properties matter in generated columns, indexes, replication, caching, and repeatable tests. Keep stored values in a canonical form and format them for display at a deliberate boundary.

Aggregate and Window Choice

GROUP BY collapses rows to one result per group. A window function calculates over related rows without collapsing them, which is useful for ranking, running totals, and comparing with a previous row. Filter grouped results with HAVING; filter ordinary rows with WHERE before aggregation when possible.

Monthly Revenue Report

Monthly Revenue Report
SELECT DATE_FORMAT(created_at, "%Y-%m") AS month,
       COUNT(*) AS orders,
       SUM(total_amount) AS revenue
FROM orders
WHERE created_at >= "2026-01-01"
GROUP BY DATE_FORMAT(created_at, "%Y-%m")
ORDER BY month;

Compare Each Sale With Its Regional Average

A window function retains each row while calculating an aggregate for its region.

Compare Each Sale With Its Regional Average
SELECT
  region,
  order_id,
  amount,
  AVG(amount) OVER (PARTITION BY region) AS regional_average
FROM sales
ORDER BY region, order_id;
Output
Each order remains visible beside the average for its region.
  • GROUP BY would collapse orders into one row per region.
Before you move on

Function Query Review

5 checks
  • Choose functions by purpose.
  • Understand GROUP BY before aggregates.
  • Check EXPLAIN for function-heavy filters.
  • Account for NULL, collation, and time-zone behavior.
  • Choose GROUP BY or a window function by desired row shape.

Function Query Failures

  • DATE applied to an indexed filter column

    Use a half-open timestamp range and compare EXPLAIN plans.
  • COUNT(column) assumed to count rows

    Use COUNT(*) when rows with NULL must count.
  • WHERE used for aggregate result

    Use HAVING after grouping.
  • Session time zone assumed

    Set and document the time zone or convert explicitly.

MySQL Functions Questions Learners Ask

In SELECT queries, no. They compute result values. UPDATE can store computed values intentionally.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.