Page Content

Tutorials

What Are The Operators in PostgreSQL With Code Example

Operators in PostgreSQL

Operators in PostgreSQL are symbolic components that are used in SQL expressions to manipulate one or two arguments and return a single value. Each operator maps to a function that performs the actual work, making them effectively syntactic sugar for underlying functions. Numerous built-in operators are supported by PostgreSQL for a variety of data types, including numeric, text, and date/time. These operators include arithmetic (+, -, *, /), logical (AND, OR, NOT), and comparison (<, >, =, <=, >=, <>,!=).

In addition to these standard types, PostgreSQL offers specialised operators for range types (e.g., && for overlap detection), arrays, JSON/JSONB data (e.g., ->, ->> for key/value extraction, and JSONPath operators for complex queries), network addresses, text search (e.g., pattern matching with LIKE, ILIKE, and POSIX regular expressions, or full-text search operators like @@), and geometric data (e.g., for scaling, translation, and identifying intersections).

A symbolic alias for an underlying function that does the actual work is what an operator is. In contrast to functions, which usually accept arguments wrapped in parenthesis, operators typically accept one unary argument or two binary arguments that appear to the left and/or right of the operator symbol. To return their total, the operator +, for instance, takes one argument on its left and one on its right. A large number of operators are pre-defined in PostgreSQL, and users can additionally define their own.

Operators in PostgreSQL
Operators in PostgreSQL

Types of Operators

In terms of data types and functions, PostgreSQL offers a wide range of operators. Among the significant categories are:

Arithmetic Operators: Arithmetic operators operate according to normal precedence principles and carry out mathematical operations including addition (+), subtraction (-), multiplication (*), division (/), modulo (%), and exponentiation (^).Other math operations include cube root (||/) and square root.

Comparison Operators: Examples of comparison operators include <=, >=, <, not equal (<> or!=), and equal (=). All comparison operators are Boolean and binary.

Logical Operators: Logical operators (AND, OR, and NOT) are essential components of PostgreSQL that are used to combine or alter Boolean statements in order to yield a Boolean value. These operators are essential for creating intricate conditions in SQL queries, especially in JOIN, CASE, and WHERE clauses.

String Operators: A wide range of string operators and associated functions are available in PostgreSQL for working with and comparing different kinds of textual and binary data. The most popular operator for concatenation for basic character string types like text, varchar, and char is ||, which can also implicitly convert non-string values to text for joining.

Pattern Matching Operators: Regular expressions are one of the most effective ways that PostgreSQL provides pattern matching. Case-sensitive regular expression matching is done using the ~ operator, and case-insensitive matching is done with ~*.

Bit String Operators: & (AND), | (OR), # (XOR), ~ (NOT), << (shift left), and >> (shift right) are examples of bitwise operations that can be performed on integral or bit string data types.

Date/Time Operators: When performing calculations involving dates and times, such as adding or subtracting intervals from timestamps, date/time operators are utilised.

Geometric Operators: To carry out scaling, translation, rotation, and the determination of intersections or distances, a wide range of operators are provided for geometric types (such as points, boxes, and circles).

Network Address Operators: Comparison, containment (<<, >>), and bitwise operations are examples of network address operators for inet and cidr types.

Text Search Operators: Full-text search capabilities depend on the @@ operator, which determines whether a tsvector matches a tsquery.

Array Operators: In order to compare arrays, operators like <@ (is contained by), @> (contains), and && (overlaps) are utilised.

Range Operators: Range operators offer specific operations for certain range types, such as containment (@>), overlap (&&), and determining whether a range is left or right (&<, &>).

Code Example:

CREATE TABLE products (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    price DECIMAL(10, 2),
    stock_quantity INT,
    product_details JSONB
);
INSERT INTO products (name, price, stock_quantity, product_details) VALUES
('Laptop', 1200.00, 50, '{"brand": "TechCo", "weight": 2.5}'),
('Mouse', 25.00, 200, '{"brand": "Logi", "wireless": true}'),
('Keyboard', 75.00, 150, '{"brand": "MechKey", "wireless": false}');
UPDATE products
SET price = price * 1.05
WHERE name = 'Laptop';
SELECT name, price, stock_quantity
FROM products
WHERE price > 100 AND stock_quantity < 100;
SELECT product_details ->> 'brand' AS brand_name
FROM products
WHERE name = 'Keyboard';

Output:

CREATE TABLE
INSERT 0 3
UPDATE 1
  name  |  price  | stock_quantity 
--------+---------+----------------
 Laptop | 1260.00 |             50
(1 row)
 brand_name 
 MechKey
(1 row)

Operator Precedence and Syntax

SQL expressions employ symbolic operators in PostgreSQL to operate on one or two arguments and return a single value. They are “syntactic sugar” for underlying functions, so each operator calls a function that does the task. PostgreSQL has many built-in operators, such as arithmetic (+, -, *, /, % for modulo, ^ for exponentiation), logical (AND, OR, NOT), and comparison (<, >, =, <=, >=, <>,!=). The!= operator is a synonym for <>. Prefix, infix, and postfix operators are named using characters from a defined list, such as + – * / < > = ~! @ # % ^ & |?. Operator name restrictions include the absence of — and/*, and multi-character names ending in+ or- unless they contain special characters. Operators with non-SQL names need spaces between them to avoid misinterpretation.

Expressions execute operators in order according to operator precedence rules. For instance, exponentiation (^) precedes multiplication (*), division (/), and modulo (%), which precede addition (+) and subtraction (-). Usually, operators with the same precedence are evaluated left to right. Logical operators (NOT, AND, OR) usually take precedence after other operators, with NOT binding most firmly. Parentheses can alter default precedence rules and control evaluation order. Short-circuit evaluation for logical expressions in PostgreSQL may not evaluate parts if the outcome can be determined from other parts, which might cause complications if not accounted for.

User-Defined and Custom Operators

PostgreSQL’s extensibility lets users construct operators for custom data types. This procedure involves several steps:

Create an underlying function: Every operator in PostgreSQL is simply syntactic sugar for a call to one of the underlying functions, which are the core code that each operator calls to carry out its actual task. Therefore, the matching underlying function must be declared before an operator may be generated. The CREATE FUNCTION command, which enables users to register functions inside the database, is used to accomplish this.

Declare the operator: The operator can be defined by using the CREATE OPERATOR command, which also allows you to specify the argument types (LEFTARG, RIGHTARG), the procedure (underlying function), and optional optimisation information. When one of the LEFTARG or RIGHTARG clauses is omitted, unary operators are defined.

Operator Optimization Information

Beyond their syntactic ease, operators give the query planner optimisation information that helps it create effective execution plans. Incorporating appropriate optimisation clauses can greatly accelerate queries. Important sentences consist of:

COMMUTATOR: Indicates which operator and the current one are commutative (e.g., A + B = B + A). So, the optimiser can rewrite expressions.

NEGATOR: When constructing a new operator in PostgreSQL, the NEGATOR clause is used to provide another operator that logically negates its result. If both operators return Boolean values and the phrase (x A y) is equal to NOT (x B y) for all possible inputs x and y, then operator A is the negator of operator B.

RESTRICT: Restricted selectivity estimation function for Boolean binary operators. The optimiser can use this to determine how many rows fulfil a WHERE clause condition like the column OP constant.

JOIN: Indicates a function for estimating join selectivity for binary operators that return Boolean. This aids the optimiser in estimating how many rows from a join condition, such as table1.column1 OP, will be produced. table2.column 2.

HASHES / MERGES: HASHES and MERGES are essential clauses in PostgreSQL that are used when defining new operators using the CREATE OPERATOR command. Their main purpose is to give the query planner optimisation information, particularly for join operations. By serving as hints, these flags may help PostgreSQL choose more effective query execution techniques.

SORT1 / SORT2: The CREATE OPERATOR command in PostgreSQL employs the SORT1 and SORT2 clauses to give the query planner optimisation hints for the merge join procedure. The SORT1 clause specifies the operator that sorts the new operator’s left-hand data type, whereas SORT2 defines the right-hand data type. For binary operators that return a Boolean value and constitute an equality test, these clauses help the query optimiser effectively sort the two operand classes for a merge join. SORT1 and SORT2 should use “less-than” operators for their data types.

Operator Classes and Operator Families

When it comes to PostgreSQL indexing, operator classes (opclass) are essential. They classify acceptable data types and comparable comparison operators for a certain index method (e.g., B-tree, GiST, GIN). The collection of operators and support functions that an index will employ for a specific column’s data type is determined by its opclass, which permits various indexing behaviours (e.g., ranking complex numbers by absolute value vs. real portion). An example of an opclass for B-tree indexes on text, varchar, and char is text pattern ops, which is helpful for LIKE or POSIX regular expressions because it compares values only character by character.

An operator family (opfamily) is a more comprehensive grouping that includes one or more opclasses and “loose” indexable operators that may be applicable to many data types. This structure helps the planner optimise searches, particularly when it comes to operations involving different data types.

Discovering and Explaining Operators

Finding Operators the \do command in psql, the PostgreSQL interactive terminal, allows users to list available operators. All operators and their parameters can be listed with this command. The \do command also takes an extra name parameter, which can be a regular expression (e.g., \do / or \do ^) for more focused searches. Additionally, \h offers assistance with SQL command syntax, and \? in psql can display information about possible operations. The pg operator system catalogue contains metadata about operators, including built-in and user-defined metadata.

Understanding how operators are employed in queries can also be aided by tools like as DBeaver. Some questions can be explained by its “Explain Query using AI” capability, which would obliquely include analysing operators and their effects.

Conclusion

To sum up, PostgreSQL operators offer a strong, expandable system for carrying out a wide range of tasks, from simple arithmetic and logical comparisons to complex operations on arrays, JSON, ranges, and custom data types. They make query writing easier and provide the query planner with useful optimisation data for quicker execution by serving as syntactic sugar over underlying functions. PostgreSQL enables developers to customise database behaviour for specific applications and indexing strategies by supporting user-defined operators, operator classes, and operator families. Because of its versatility and strong built-in operators, PostgreSQL is a great option for managing intricate data manipulation, improving modern database systems’ efficiency and maintainability.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index