SQL Programming Language

SQL Tutorial

SQL Operators - SQL Tutorials

SQL Operators

In the realm of relational database management systems (RDBMS), SQL (Structured Query Language) reigns supreme as the standard language for managing and manipulating data. SQL operators play a crucial role in this process, providing a set of powerful tools for filtering, combining, and transforming data within a database.

Take a look at all the topics that are discussed in this article:

What is SQL Operator?

SQL operators are special keywords or symbols used in SQL queries to perform specific operations on data stored in databases. They allow you to manipulate, filter, sort, and combine data based on conditions and criteria specified in the query.

Types of Operator in SQL

The main types of operators in SQL are:

  1. Arithmetic Operators
  2. Comparison Operators
  3. Logical Operators
  4. String Operators
  5. Range Operators
  6. Set Operators
  7. Membership Operators
  8. Join Operators

Let’s discuss each operator with their types.

SQL Arithmetic Operators

SQL (Structured Query Language) provides a set of arithmetic operators that allow you to perform mathematical calculations within your queries. These operators are essential for manipulating numerical data and deriving new values based on existing data.

1. Addition (+)

The addition operator is used to sum two or more values. It can be applied to numerical data types such as integers, decimal numbers, and floating-point numbers.

Example:

				
					SELECT product_name, price, price + 10 AS price_with_markup
FROM products;

				
			

2. Subtraction (-)

The subtraction operator is used to find the difference between two values.

Example:

				
					SELECT order_id, order_date, DATE_SUB(CURRENT_DATE(), order_date) AS days_since_order
FROM orders;

				
			

3. Multiplication (*)

The multiplication operator is used to multiply two or more values.

Example:

				
					SELECT product_name, quantity, price, quantity * price AS total_cost
FROM order_items;

				
			

4. Division (/)

The division operator is used to divide one value by another.

Example:

				
					SELECT employee_name, salary, salary / 12 AS monthly_salary
FROM employees;

				
			

5. Modulus (%)

The modulus operator returns the remainder of a division operation.

Example:

				
					SELECT product_id, price, price % 10 AS price_remainder
FROM products;

				
			

6. Exponentiation (** or POWER())

While SQL doesn’t have a dedicated exponentiation operator, some database systems support the double-asterisk (**) for exponentiation. Alternatively, you can use the POWER() function to achieve the same result:

				
					-- Using **
SELECT POWER(base, exponent) AS result
FROM calculations;

-- Using POWER()
SELECT POWER(2, 3) AS result;

				
			

SQL Comparison Operators

In SQL Comparison operators play a crucial role in filtering and manipulating data based on specific conditions. These operators enable you to compare values and make informed decisions about which data to retrieve or update.

1. Equal (=)

The equal operator is used to check if two values are identical.

Example:

				
					SELECT customer_name, city
FROM customers
WHERE city = 'New York';

				
			

2. Not Equal (<>)

The not equal operator is used to check if two values are not identical.

Example:

				
					SELECT product_name, price
FROM products
WHERE price <> 0;

				
			

3. Greater Than (>)

The greater than operator is used to check if one value is strictly greater than another.

Example:

				
					SELECT employee_name, salary
FROM employees
WHERE salary > 50000;

				
			

4. Less Than (<)

The less than operator is used to check if one value is strictly less than another.

Example:

				
					SELECT order_id, order_date
FROM orders
WHERE order_date < '2023-01-01';

				
			

5. Greater Than or Equal To (>=)

The greater than or equal to operator is used to check if one value is greater than or equal to another.

Example:

				
					SELECT product_name, stock_quantity
FROM products
WHERE stock_quantity >= 100;

				
			

6. Less Than or Equal To (<=)

The less than or equal to operator is used to check if one value is less than or equal to another.

Example:

				
					SELECT customer_name, age
FROM customers
WHERE age <= 30;

				
			

SQL Logical Operators

In SQL, logical operators play a vital role in combining conditions and creating complex filters for data retrieval and manipulation. These operators allow you to combine multiple conditions, enabling you to extract precisely the data you need from your database.

1. AND Operator

The AND operator is used to combine two or more conditions, and all conditions must be true for the overall statement to be true.

Example:

				
					SELECT product_name, price, category
FROM products
WHERE price > 50 AND category = 'Electronics';

				
			

2. OR Operator

The OR operator is used to combine two or more conditions, and if any one of the conditions is true, the overall statement is considered true.

Example:

				
					SELECT customer_name, city, country
FROM customers
WHERE city = 'New York' OR country = 'Canada';

				
			

3. NOT Operator

The NOT operator is used to negate a condition or reverse its logic.

Example:

				
					SELECT employee_name, department
FROM employees
WHERE department NOT IN ('Sales', 'Marketing');

				
			

4. IN Operator

The IN operator is used to specify multiple values in a WHERE clause. It simplifies queries that involve multiple OR conditions.

Example:

				
					SELECT * FROM orders
WHERE customer_id IN (1, 5, 8, 10);

				
			

5. BETWEEN Operator

The BETWEEN operator is used to filter results within a specific range. It is inclusive, meaning that the values specified are included in the result set.

Example:

				
					SELECT * FROM products
WHERE price BETWEEN 100 AND 500;

				
			

Logical operators can be combined and with comparison operators to create complex filtering conditions. This allows you to extract precise subsets of data based on multiple criteria, enabling more advanced data analysis and decision-making.

Example:

				
					SELECT order_id, order_date, total_amount
FROM orders
WHERE total_amount > 1000 AND (order_date >= '2023-01-01' AND order_date <= '2023-03-31');

				
			

SQL String Operators

In SQL, string operators play a crucial role in manipulating and analyzing text-based data. These operators allow you to perform various operations on character strings, enabling you to extract, concatenate, and transform data in powerful ways.

1. Concatenation Operator (||)

The concatenation operator is used to combine two or more strings into a single string.

Example:

				
					SELECT first_name || ' ' || last_name AS full_name
FROM employees;

				
			

2. LIKE Operator

The LIKE operator is used to search for a pattern within a string. It supports the use of wildcard characters (% and _) to match partial strings.

Example:

				
					SELECT product_name, description
FROM products
WHERE product_name LIKE 'Apple%';

				
			

3. UPPER() and LOWER() Functions

The UPPER() function converts a string to uppercase letters, while the LOWER() function converts a string to lowercase letters.

Example:

				
					SELECT UPPER(customer_name) AS uppercase_name, LOWER(city) AS lowercase_city
FROM customers;

				
			

4. SUBSTRING() Function

The SUBSTRING() function extracts a portion of a string based on the specified starting position and length.

Example:

				
					SELECT order_id, SUBSTRING(order_date, 1, 4) AS order_year
FROM orders;

				
			

5. TRIM() Function

The TRIM() function removes leading and trailing spaces from a string.

Example:

				
					SELECT TRIM(product_description) AS trimmed_description
FROM products;

				
			

SQL Range Operators

In SQL (Structured Query Language), range operators provide a powerful way to filter data based on specified value ranges. These operators allow you to retrieve records that fall within or outside a particular range, enabling precise data selection and analysis.

1. BETWEEN Operator

The BETWEEN operator is used to select values that fall within a specified range, including the boundary values.

Example:

				
					SELECT product_name, price
FROM products
WHERE price BETWEEN 50 AND 100;

				
			

2. NOT BETWEEN Operator

The NOT BETWEEN operator is used to select values that fall outside a specified range.

Example:

				
					SELECT employee_name, salary
FROM employees
WHERE salary NOT BETWEEN 40000 AND 60000;

				
			

3. IN Operator

The IN operator is used to select values that match any value in a specified list or subquery.

Example:

				
					SELECT customer_name, city
FROM customers
WHERE city IN ('New York', 'London', 'Paris');

				
			

4. NOT IN Operator

The NOT IN operator is used to select values that do not match any value in a specified list or subquery.

Example:

				
					SELECT product_name, category
FROM products
WHERE category NOT IN ('Electronics', 'Clothing');

				
			

SQL Set Operators

In SQL, set operators provide a powerful way to combine and manipulate result sets from multiple queries. These operators allow you to perform various set operations, such as unions, intersections, and differences, enabling you to extract and analyze data in more complex ways.

1. UNION Operator

The UNION operator is used to combine the result sets of two or more SELECT statements, removing any duplicate rows.

Example:

				
					SELECT product_name, category
FROM products
UNION
SELECT product_name, category
FROM discontinued_products;

				
			

2. UNION ALL Operator

The UNION ALL operator is similar to the UNION operator, but it includes duplicate rows in the result set.

Example:

				
					SELECT customer_name, city
FROM customers
UNION ALL
SELECT supplier_name, city
FROM suppliers;

				
			

3. INTERSECT Operator

The INTERSECT operator is used to return only the rows that are common to the result sets of two or more SELECT statements.

Example:

				
					SELECT employee_id
FROM employees
INTERSECT
SELECT employee_id
FROM managers;

				
			

4. EXCEPT (or MINUS) Operator

The EXCEPT (or MINUS) operator is used to return the rows from the first SELECT statement that are not present in the second SELECT statement.

Example:

				
					SELECT product_id
FROM products
EXCEPT
SELECT product_id
FROM discontinued_products;

				
			

SQL Membership Operators

In SQL, membership operators provide a powerful way to filter data based on whether a value belongs to a specified set or meets certain criteria. These operators allow you to test the membership of a value against a list, subquery, or range, enabling precise data selection and analysis.

1. IN Operator

The IN operator is used to check if a value matches any value in a specified list or subquery.

Example:

				
					SELECT product_name, category
FROM products
WHERE category IN ('Electronics', 'Clothing', 'Books');

				
			

2. NOT IN Operator

The NOT IN operator is used to check if a value does not match any value in a specified list or subquery.

Example:

				
					SELECT employee_name, department
FROM employees
WHERE department NOT IN (SELECT department_id FROM departments WHERE location = 'New York');

				
			

3. EXISTS Operator

The EXISTS operator is used to check if a subquery returns any rows.

Example:

				
					SELECT customer_name, city
FROM customers c
WHERE EXISTS (
  SELECT 1
  FROM orders o
  WHERE o.customer_id = c.customer_id
);

				
			

4. ANY and SOME Operators

The ANY and SOME operators are used to compare a value with a set of values returned by a subquery.

Example:

				
					SELECT product_name, price
FROM products
WHERE price > ANY (
  SELECT AVG(price)
  FROM products
  GROUP BY category
);

				
			

5. ALL Operator

The ALL operator is used to compare a value with every value returned by a subquery.

Example:

				
					SELECT employee_name, salary
FROM employees
WHERE salary > ALL (
  SELECT salary
  FROM employees
  WHERE department = 'Sales'
);

				
			

SQL Join Operators

In SQL, join operators play a crucial role in combining data from multiple tables based on related columns. These operators allow you to retrieve and analyze data from different sources, enabling you to gain comprehensive insights and make informed decisions.

1. INNER JOIN

The INNER JOIN operator returns rows from both tables where the join condition is met, resulting in the intersection of the two tables.

Example:

				
					SELECT customers.customer_name, orders.order_date, orders.total_amount
FROM customers
INNER JOIN orders ON customers.customer_id = orders.customer_id;

				
			

2. LEFT JOIN (or LEFT OUTER JOIN)

The LEFT JOIN operator returns all rows from the left table (the first table in the join) and the matching rows from the right table (the second table in the join). If there is no match in the right table, the result will contain NULL values for those columns.

Example:

				
					SELECT products.product_name, categories.category_name, sales.quantity
FROM products
LEFT JOIN categories ON products.category_id = categories.category_id
LEFT JOIN sales ON products.product_id = sales.product_id;

				
			

3. RIGHT JOIN (or RIGHT OUTER JOIN)

The RIGHT JOIN operator is the opposite of the LEFT JOIN. It returns all rows from the right table (the second table in the join) and the matching rows from the left table (the first table in the join). If there is no match in the left table, the result will contain NULL values for those columns.

4. FULL OUTER JOIN

The FULL OUTER JOIN operator returns all rows from both tables, regardless of whether there is a match or not. If there is no match, the result will contain NULL values for the columns from the other table.

5. CROSS JOIN

The CROSS JOIN operator returns the Cartesian product of rows from two or more tables. It combines each row from the first table with every row from the second table, resulting in a multiplication of rows.

Example:

				
					SELECT products.product_name, suppliers.supplier_name
FROM products
CROSS JOIN suppliers;

				
			

SQL operators are the backbone of data manipulation within relational databases. They empower users to perform a wide range of operations, from simple data filtering and sorting to complex calculations and data transformations.

By mastering the use of these operators, database professionals can unlock the full potential of SQL, enabling them to extract valuable insights, make informed decisions, and drive business success through effective data management.

Categories