SQL operators are symbols or keywords used to perform operations on data in SQL queries. They are essential for filtering, sorting, or manipulating data within the database. Here's a breakdown of the main SQL operators:
1. Arithmetic Operators
These operators perform mathematical operations on numeric values.
+(Addition)-(Subtraction)*(Multiplication)/(Division)%(Modulo or Remainder)
Example:
SELECT salary + 1000 AS updated_salary FROM employees;
2. Comparison Operators
These operators are used to compare values.
=(Equal to)!=or<>(Not equal to)<(Less than)>(Greater than)<=(Less than or equal to)>=(Greater than or equal to)BETWEEN(Within a range)IN(Matches any value in a list)LIKE(Pattern matching)IS NULL(Checks for NULL values)IS NOT NULL(Checks for non-NULL values)
Example:
SELECT * FROM employees WHERE salary > 50000;
3. Logical Operators
These operators are used to combine multiple conditions in a query.
AND(True if both conditions are true)OR(True if at least one condition is true)NOT(Reverses the condition)
Example:
SELECT * FROM employees WHERE salary > 50000 AND department = 'HR';
4. Set Operators
These operators are used to combine results from multiple queries.
UNION(Combines results from multiple queries, removing duplicates)UNION ALL(Combines results from multiple queries, including duplicates)INTERSECT(Returns common records between queries)EXCEPTorMINUS(Returns records from the first query that aren't in the second query)
Example:
SELECT name FROM employees
UNION
SELECT name FROM contractors;
5. String Operators
These are used for string manipulation.
CONCAT()(Concatenates two or more strings)||(Concatenates strings in some SQL dialects like PostgreSQL)
Example:
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
6. Bitwise Operators
These operators perform bit-level operations.
&(Bitwise AND)|(Bitwise OR)^(Bitwise XOR)<<(Bitwise left shift)>>(Bitwise right shift)
Example:
SELECT 5 & 3; -- Result is 1 (binary: 101 & 011)
7. NULL Operators
Used to handle NULL values in SQL queries.
IS NULL(Check if a value is NULL)IS NOT NULL(Check if a value is not NULL)
Example:
SELECT * FROM employees WHERE department IS NULL;
These operators help you to filter, compare, and combine data in various ways when writing SQL queries.
No comments:
Post a Comment