Expressions
KSQL supports expressions in SELECT, WHERE, ORDER BY, GROUP BY, and HAVING. Anywhere you can put a column name, you can put an expression.
Arithmetic expressions
Standard math works in any clause.
SELECT price * quantity AS total FROM Products
SELECT Revenue - Costs AS profit FROM Deals
SELECT (price * quantity) * (1 - discount / 100) AS net FROM LineItems
Use parentheses to control evaluation order.
String concatenation
Use || or CONCAT() to join strings.
SELECT first_name || ' ' || last_name AS full_name FROM Employees
SELECT Name || ' (' || Status || ')' AS display FROM Customers
SELECT CONCAT(City, ', ', State) AS location FROM Offices
|| and CONCAT() are equivalent for two strings; CONCAT() accepts an arbitrary number of arguments.
CASE WHEN
Conditional logic within a query.
SELECT Name,
CASE
WHEN Revenue > 100000 THEN 'Enterprise'
WHEN Revenue > 50000 THEN 'Mid-Market'
WHEN Revenue > 10000 THEN 'SMB'
ELSE 'Starter'
END AS tier
FROM Customers
Multiple WHEN branches are supported. ELSE is optional (defaults to NULL when omitted).
CASE in WHERE
WHERE CASE
WHEN Type = 'premium' THEN Priority > 3
ELSE Priority > 7
END
CASE in ORDER BY
Useful for custom sort orders:
ORDER BY CASE
WHEN Status = 'urgent' THEN 1
WHEN Status = 'high' THEN 2
WHEN Status = 'medium' THEN 3
ELSE 4
END ASC
Combining expressions
Expressions nest freely:
-- Profit margin percentage, rounded
SELECT Name,
ROUND((Revenue - Costs) * 100.0 / Revenue, 1) AS margin_pct
FROM Deals
WHERE Revenue > 0
-- First initial + last name
SELECT UPPER(LEFT(FirstName, 1)) || '. ' || LastName AS short_name
FROM Employees
-- Conditional with date math
SELECT Name,
IF(DueDate < NOW(), 'OVERDUE', 'On track') AS status,
DATEDIFF(DueDate, NOW()) AS days_remaining
FROM Tasks
WHERE Status != 'done'
Next
- Functions → — full function reference
- Operators → — comparison, logical, arithmetic