SQL: Expressions

SQL: Expressions

In SQL, expressions are combinations of values, operators, and functions that produce a single value.
They are used in queries to compute, filter, transform, or return results from database data.


1. Types of SQL Expressions


a) Constant Expressions

Return a fixed value; do not depend on table data.

SELECT 100 AS FixedValue;
SELECT 'Hello SQL' AS Message;


b) Column Expressions

Use column names directly.

SELECT first_name, last_name FROM employees;


c) Arithmetic Expressions

Perform mathematical calculations.
Operators: +, -, *, /, %

SELECT salary, salary * 0.1 AS Bonus
FROM employees;


d) String Expressions

Manipulate or combine text.

SELECT CONCAT(first_name, ' ', last_name) AS FullName
FROM employees;


e) Comparison Expressions

Used in conditions to compare values.
Operators: =, !=, <>, <, >, <=, >=

SELECT * FROM employees
WHERE salary > 50000;


f) Logical Expressions

Combine conditions to return TRUE/FALSE.
Operators: AND, OR, NOT

SELECT * FROM employees
WHERE department = 'Sales' AND salary > 40000;


g) Case Expressions (Conditional)

Return values based on conditions.

SELECT name,
       CASE 
           WHEN marks >= 90 THEN 'A'
           WHEN marks >= 75 THEN 'B'
           ELSE 'C'
       END AS Grade
FROM students;


h) Aggregate Expressions

Use aggregate functions to return a single computed value.

SELECT AVG(salary) AS AvgSalary
FROM employees;


i) Date and Time Expressions

Work with date/time values.

SELECT NOW() AS CurrentTime;
SELECT DATEDIFF('2025-08-08', '2025-01-01') AS DaysDifference;


2. Where Expressions Are Used in SQL

  • SELECT clause → to calculate or display computed values.

  • WHERE clause → to filter rows.

  • ORDER BY clause → to sort results.

  • GROUP BY and HAVING clauses → for aggregated results.

  • UPDATE statements → to modify column values.

Example:

UPDATE employees
SET salary = salary * 1.05
WHERE department = 'IT';