Sub topic 2
Literals and Operators
This chapter assumes you can write basic SELECT ... FROM ... WHERE queries and know the common column types (numbers, text, dates). The examples use an employees table with first_name, last_name, salary, commission, and department_id. They run as written on PostgreSQL. The chapter points out where other databases differ.
An expression in the SELECT list is built from two kinds of pieces. Literals are fixed values you type into the query. Operators combine values into new values. Once you know how each literal is read and how operators group, you can predict the result of any expression.
Literals
A literal is a value written directly in the SQL text, not read from a column. The database decides its type from how you write it.
| Kind | Examples | Notes |
|---|---|---|
| Integer | `42`, `-7` | The minus sign is really a unary operator applied to `7`. |
| Decimal | `3.14`, `0.5` | Usually an exact decimal type, not a floating-point type. |
| Scientific | `1.5e3` | Usually a floating-point type. |
| String | `'hello'`, `'O''Brien'` | Single quotes. A quote inside a string is doubled. |
| Date | `DATE '2026-11-27'` | Standard syntax. SQLite has no `DATE '...'` literal. |
| Boolean | `TRUE`, `FALSE` | Not available in SQL Server or older Oracle versions. |
| Null | `NULL` | A marker for "no value." The next chapter covers how it behaves. |
SELECT 42 AS answer,
3.14 AS pi,
'O''Brien' AS surname,
DATE '2026-11-27' AS example_date,
TRUE AS flag;This query has no FROM clause, so it returns one row. PostgreSQL, MySQL, SQL Server, and SQLite allow that. Oracle requires FROM dual.
Arithmetic operators
The arithmetic operators work on numeric values and return a number.
+adds,-subtracts,*multiplies,/divides.%gives the remainder in PostgreSQL, MySQL, SQL Server, and SQLite. The functionMOD(a, b)does the same in the standard and in Oracle, which has no%.- A leading
-or+is a unary operator that applies to a single value.
Arithmetic runs once per row. The expression salary * 12 multiplies each row's own salary by the literal 12.
SELECT first_name,
salary,
salary * 12 AS yearly,
salary / 4 AS quarter_share,
-salary AS negated
FROM employees;Integer division
When both operands are integers, many databases return an integer and drop the fraction. PostgreSQL, SQL Server, and SQLite do this. MySQL and Oracle return a decimal.
SELECT 7 / 2 AS int_div,
7 / 2.0 AS dec_div,
7 % 2 AS remainder,
MOD(7, 2) AS remainder_standard;On PostgreSQL the result is 3, 3.5000000000000000, 1, 1. If one operand is a decimal, the whole operation uses decimal arithmetic. When a column holds integers and you need a fractional result, change one operand: write total / 2.0, or use CAST(total AS DECIMAL(12, 2)) / count. Do not rely on your database's default. A query that works on MySQL can silently return truncated values on PostgreSQL.
Division by zero
Dividing by zero raises an error in most databases. MySQL is a notable exception in its default settings: it returns NULL and may only give a warning. The chapter on COALESCE and NULLIF shows the standard way to guard a divisor.
Operator precedence
An expression such as salary + bonus * 12 has more than one reading. Precedence rules decide which operator binds first. The database builds a tree from the expression and evaluates it from the bottom up.
From tightest to loosest binding, the usual order is:
| Level | Operators | Column | Column |
|---|---|---|---|
| 1 | Unary `+`, unary `-` | ||
| 2 | `*`, `/`, `%` | ||
| 3 | Binary `+`, binary `-` | ||
| 4 | `\ | \ | ` (concatenation), where supported as an operator |
| 5 | Comparisons: `=`, `<>`, `<`, `>`, `<=`, `>=`, plus `BETWEEN`, `IN`, `LIKE`, `IS NULL` | ||
| 6 | `NOT` | ||
| 7 | `AND` | ||
| 8 | `OR` |
Operators on the same level are evaluated left to right. The exact placement of a few operators, such as ||, varies by database. Parentheses always override precedence, so use them whenever the grouping is not obvious to a reader.
SELECT salary + 1000 * 2 AS raise_after_multiply,
(salary + 1000) * 2 AS raise_before_multiply
FROM employees;For a salary of 3000, the first column is 5000 and the second is 8000. The only difference is the parentheses.
Comparison operators
A comparison compares two values and returns a truth value:
=equal<>not equal (!=also works in most databases but is not standard)<,>,<=,>=
A comparison yields TRUE, FALSE, or UNKNOWN. UNKNOWN appears when either side is NULL. This is the basis of the behavior covered in the NULL chapter. For now, remember that commission = NULL never evaluates to TRUE, so you must write commission IS NULL.
PostgreSQL, MySQL, and SQLite let you return a comparison directly in the SELECT list:
SELECT first_name,
salary >= 100000 AS is_high_earner
FROM employees;SQL Server and Oracle do not treat a comparison as a value in the SELECT list. They need a CASE expression instead, which a later chapter introduces. In WHERE, every database accepts comparisons as conditions.
Related predicates, such as BETWEEN, IN, and LIKE, are also comparison-level operators. salary BETWEEN 50000 AND 100000 includes both endpoints and is equivalent to salary >= 50000 AND salary <= 100000.
Logical operators
AND, OR, and NOT combine truth values. NOT binds tightest, then AND, then OR. This ordering catches many people out:
SELECT first_name, department_id, salary
FROM employees
WHERE department_id = 10
OR department_id = 20 AND salary > 50000;Because AND binds first, the database reads this as department_id = 10 OR (department_id = 20 AND salary > 50000). It returns every employee in department 10, whatever their salary. If you meant the salary test to apply to both departments, add parentheses:
SELECT first_name, department_id, salary
FROM employees
WHERE (department_id = 10 OR department_id = 20)
AND salary > 50000;String concatenation
Joining two strings is the one text operation that is also an operator. The standard operator is ||. Databases disagree:
| Database | Concatenation | Column | Column |
|---|---|---|---|
| PostgreSQL, Oracle, SQLite | `a \ | \ | b` |
| SQL Server | `a + b`, or `CONCAT(a, b)` | ||
| MySQL | `CONCAT(a, b)`. `\ | \ | ` means logical OR unless the `PIPES_AS_CONCAT` mode is on. |
SELECT first_name || ' ' || last_name AS full_name
FROM employees;The space between the names is a string literal. Without it the names would run together.
The standard || returns NULL if either side is NULL. Oracle treats an empty string as NULL. SQL Server's CONCAT() function and PostgreSQL's CONCAT() function treat NULL as an empty string. Check which behavior your database uses before you build a name or address from columns that can be missing.
Operand types and result types
Each operator expects certain types. If the operands differ, the database often converts one to match the other. An integer plus a decimal gives a decimal. Adding a number to a string is a different story. PostgreSQL raises an error for '5' + 1, because it cannot guess whether + means addition or something else. MySQL silently converts '5' to the number 5 and returns 6. SQL Server converts the string to a number too, and it fails with a conversion error if the text is not numeric.
To avoid depending on implicit conversion, convert explicitly with CAST:
SELECT CAST('5' AS INTEGER) + 1 AS six;The last chapter of this tutorial returns to type conversion and dialect differences in more detail.
Common mistakes
- Writing a string with double quotes. Use single quotes.
- Expecting
7 / 2to be3.5. Check whether both operands are integers. - Writing
a OR b AND cand expecting left-to-right evaluation.ANDbinds beforeOR. - Writing
= NULLor<> NULL. UseIS NULLandIS NOT NULL. - Using
+to join strings on PostgreSQL, or||to join strings on MySQL. - Forgetting that arithmetic with
NULLreturnsNULL, so a single missing value can blank out a computed column.
Exercise
A query uses WHERE region = 'EU' OR region = 'US' AND revenue > 1000. Which rows does it return? Rewrite it so that the revenue test applies to both regions.
Show answer
Because AND binds tighter than OR, the condition means region = 'EU' OR (region = 'US' AND revenue > 1000). It returns every EU row regardless of revenue, plus the US rows with revenue above 1000. To apply the revenue test to both regions, write WHERE (region = 'EU' OR region = 'US') AND revenue > 1000.
Exercise
On PostgreSQL, the column itemsperbox is an integer and boxes is an integer. The expression boxes / itemsperbox returns 0 when boxes is 3 and itemsperbox is 4. Write an expression that returns 0.75 for those values, and give two ways to do it.
Show answer
Make one operand a decimal. For example, boxes / (itemsperbox * 1.0), or CAST(boxes AS DECIMAL(10, 2)) / itemsperbox. Either one forces decimal division, so 3 / 4 becomes 0.75. (A divisor of 0 would still raise an error, which a later chapter handles with NULLIF.)
Exercise
Why does SELECT firstname || ' ' || lastname AS full_name return a surprising result on MySQL with default settings, and what portable choice is there?
Show answer
In default MySQL mode, || is the logical OR operator, so the three values are treated as conditions and the result is a number such as 0, not joined text. CONCAT(firstname, ' ', lastname) works on MySQL, and also on PostgreSQL and SQL Server.