SQL Language Operators
SQL operators are symbols or keywords that are used to perform operations on one or more values. These values can be columns, variables, or literals. Operators are fundamental to building complex queries and performing calculations, comparisons, and logical operations within your SQL statements.
Arithmetic Operators
Used to perform mathematical calculations.
+
Adds two values.
-
Subtracts one value from another.
*
Multiplies two values.
/
Divides one value by another.
%
Returns the remainder of a division.
Comparison Operators
Used to compare two values. These operators return TRUE, FALSE, or UNKNOWN.
=
Checks if two values are equal.
<> or !=
Checks if two values are not equal.
>
Checks if the left value is greater than the right value.
<
Checks if the left value is less than the right value.
>=
Checks if the left value is greater than or equal to the right value.
<=
Checks if the left value is less than or equal to the right value.
Logical Operators
Used to combine conditional statements or test for true.
AND
Returns TRUE if both conditions are true.
OR
Returns TRUE if at least one condition is true.
NOT
Reverses the logical state of its operand.
Bitwise Operators
Used to perform bitwise operations on integer values.
&
Performs a bitwise AND operation.
|
Performs a bitwise OR operation.
^
Performs a bitwise exclusive OR operation.
~
Performs a bitwise NOT operation.
<<
Shifts bits to the left.
>>
Shifts bits to the right.
Other Operators
Includes operators for pattern matching, set operations, and more.
LIKE
Searches for a specified pattern in a column.
IN
Allows you to specify multiple values in a WHERE clause.
BETWEEN
Selects values within a given range.
IS NULL
Tests for NULL values.
IS NOT NULL
Tests for non-NULL values.
ALL
Combines with a comparison operator to retrieve all rows that satisfy the condition.
ANY
Combines with a comparison operator to retrieve rows where the comparison is true for at least one value in the list.
EXISTS
Tests for the existence of rows in a subquery.
UNION
Combines the result set of two or more SELECT statements.
UNION ALL
Combines the result set of two or more SELECT statements, including duplicates.
INTERSECT
Returns only rows that exist in both result sets.
EXCEPT
Returns rows from the first SELECT statement that are not in the second.
Operator Precedence
Operators are evaluated in a specific order, known as operator precedence. Operators with higher precedence are evaluated before operators with lower precedence. You can use parentheses () to override the default precedence.
-- Example demonstrating operator precedence
SELECT column1, column2
FROM your_table
WHERE (column1 + column2) * column3 > 100;
Understanding SQL operators is crucial for writing effective and efficient database queries. For detailed syntax and specific implementations in different SQL dialects (e.g., SQL Server, MySQL, PostgreSQL), please refer to the relevant documentation for your database system.