In SQL, operators play a crucial role in performing operations on data, whether it's for filtering, sorting, or transforming the results of a query. SQL operators are the building blocks of complex queries, and mastering them is essential for efficient database manipulation.
SQL operators are symbols or keywords used to perform operations on data. They can manipulate values, compare values, or perform logical operations within SQL queries. Operators allow users to filter and modify data to get precise results.
SQL operators fall into the following categories:
Arithmetic operators in SQL are used to perform basic mathematical operations on numeric values. These operators work just like they do in other programming languages.
SELECT 10 + 5 AS result; -- Returns 15
SELECT 10 - 5 AS result; -- Returns 5
SELECT 10 * 5 AS result; -- Returns 50
SELECT 10 / 5 AS result; -- Returns 2
SELECT 10 % 3 AS result; -- Returns 1
Comparison operators are used to compare two values. They are often used in the WHERE
clause to filter query results based on specific conditions.
SELECT * FROM employees
WHERE department = 'Sales';
SELECT * FROM employees
WHERE department != 'Sales';
SELECT * FROM employees
WHERE salary > 50000;
SELECT * FROM employees
WHERE salary < 50000;
SELECT * FROM employees
WHERE salary >= 50000;
SELECT * FROM employees
WHERE salary <= 50000;
SELECT * FROM employees
WHERE salary BETWEEN 40000 AND 60000;
SELECT * FROM employees
WHERE department IN ('Sales', 'Marketing');
SELECT * FROM employees
WHERE name LIKE 'J%'; -- Matches names starting with "J"
NULL
(no value).
SELECT * FROM employees
WHERE department IS NULL;
NULL
.
SELECT * FROM employees
WHERE department IS NOT NULL;
Logical operators are used to combine multiple conditions in a WHERE
clause. They help to refine queries with complex filtering requirements.
SELECT * FROM employees
WHERE department = 'Sales' AND salary > 50000;
SELECT * FROM employees
WHERE department = 'Sales' OR department = 'Marketing';
SELECT * FROM employees
WHERE NOT department = 'Sales';
There are other operators in SQL that perform specialized operations:
SELECT * FROM employees e
WHERE EXISTS (SELECT * FROM departments d WHERE e.department_id = d.department_id);
SELECT * FROM employees
WHERE salary > ALL (SELECT salary FROM employees WHERE department = 'Sales');
SELECT CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;