PostgreSQL Expressions
An expression is composed of one or more values, operators, and PostgreSQL functions.
PostgreSQL expressions are similar to formulas. They can be applied in query statements to retrieve a result set that meets specified conditions.
Syntax
The syntax for the SELECT statement is as follows:
SELECT column1, column2, columnN
FROM table_name
WHERE [CONDITION | EXPRESSION];
PostgreSQL expressions can be of different types, which we will discuss next.
Boolean Expression
A Boolean expression retrieves data based on a specified condition:
SELECT column1, column2, columnN
FROM table_name
WHERE SINGLE VALUE MATCHING EXPRESSION;
Create a COMPANY table (download COMPANY SQL file), with the following data content:
tutorialprodb# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
The following uses a Boolean expression (SALARY=10000) to query data:
tutorialprodb=# SELECT * FROM COMPANY WHERE SALARY = 10000;
id | name | age | address | salary
----+-------+-----+----------+--------
7 | James | 24 | Houston | 10000
(1 row)
Numeric Expression
Numeric expressions are commonly used for mathematical operations in query statements:
SELECT numerical_expression as OPERATION_NAME
[FROM table_name WHERE CONDITION];
numerical_expression is a mathematical operation expression, with an example as follows:
tutorialprodb=# SELECT (17 + 6) AS ADDITION;
addition
----------
23
(1 row)
Additionally, PostgreSQL includes some built-in mathematical functions such as:
- avg(): Returns the average value of an expression
- sum(): Returns the total sum of a numeric field
- count(): Returns the total number of records in the query
The following example queries the total number of records in the COMPANY table:
tutorialprodb=# SELECT COUNT(*) AS "RECORDS" FROM COMPANY;
RECORDS
---------
7
(1 row)
Date Expression
Date expressions return the current system date and time and can be used for various data manipulations. The following example queries the current time:
tutorialprodb=# SELECT CURRENT_TIMESTAMP;
current_timestamp
-------------------------------
2019-06-13 10:49:06.419243+08
(1 row)