Sponsored
GitHubTabLearn by Projects — Programming tutorials for C, C#, Python, Javascript, Typescript, React, Go, HTML/CSS, Java, PHP and more
Show repository
Lesson 11

SQL functions and expressions

Built-in SQL functions: string functions, date functions, and more

SQL provides a variety of built-in functions to transform and manipulate data in queries without needing client-side post-processing. Expressions allow computing derived values similarly. Leveraging these can simplify data extraction logic significantly.

SQL Functions

Common categories of functions:

Text Functions

Manipulate string data:

SELECT UPPER(name), LENGTH(comments)
FROM reviews;

UPPER cases to upper, LENGTH gets length.

UPPER(name)LENGTH(comments)
JOHN DOE45
JANE SMITH30
ALEX JONES60
EMILY BLAKE50

Date Functions

Date processing:

SELECT DAY(created_date), DATEDIFF(NOW(), created_date)
FROM accounts;

DAY gets day-of-month, DATEDIFF difference between dates.

DAY(created_date)DATEDIFF(NOW(), created_date)
1510
322
255
818

Aggregates

We saw aggregates for summarization like COUNT(), AVG(), SUM() earlier.

Conversions

Convert between data types:

SELECT CAST(price AS VARCHAR)
FROM products;

Casts price to text.

Case Expressions

Compare values and return based on conditions:

SELECT name,
  CASE WHEN price < 100 THEN 'Affordable'
       WHEN price < 500 THEN 'Expensive'
       ELSE 'Ultra-Premium' END AS category
FROM wines;

Categories wines based on pricing.

namecategory
ChardonnayAffordable
Pinot NoirExpensive
MerlotAffordable
CabernetUltra-Premium

Expressions

SQL allows writing expressions with common math and programming operators like +, - , * , / , % etc. Parentheses control order of evaluation.

For example to compute an order total:

SELECT *, quantity * unit_price AS total_cost
FROM order_lines;

This avoids needing to compute line costs in application code.

Boolean expressions can leverage AND/OR/NOT operators combined with comparison operators like =, !=, > etc:

SELECT *
FROM contests
WHERE end_date > NOW() AND status = 'Open';

Finds currently open contests.

Leveraging functions like LENGTH, DATE_DIFF and expressions for calculations, boolean logic etc. allows doing significantly more data manipulation directly in SQL with less backend programming.

Practice integrating functions and expressions to push data processing into the database engine for faster and simpler analysis.

©2026 SQLZap - Learn SQL Interactively

Twitter