SQL (Structured Query Language) is a powerful tool for managing and manipulating data stored in relational databases. Understanding SQL operators is crucial for writing efficient, effective queries that retrieve the desired information from your database. In this section, we will explore various types of SQL operators, including arithmetic, comparison, logical, and string operators, along with their real-world applications and best practices.
Arithmetic operators are used to perform mathematical operations on numeric data in SQL. These operators include addition, subtraction, multiplication, division, and modulus.
SELECT
product_id,
price,
quantity,
(price * quantity) AS total_cost,
(price * quantity) / 100 AS discount_10_percent,
(price * quantity) % 5 AS remainder_division_by_5
FROM
products;
In this example, we calculate the total_cost by multiplying price and quantity. We also demonstrate how to apply a 10% discount and find the remainder when dividing the total cost by 5.
Comparison operators are used to compare two values in SQL. These operators return a Boolean result (TRUE or FALSE) based on the comparison. Common comparison operators include:
=): Checks if two values are equal.<> or !=): Checks if two values are not equal.>): Checks if one value is greater than another.<): Checks if one value is less than another.>=): Checks if one value is greater than or equal to another.<=): Checks if one value is less than or equal to another.SELECT
product_id,
product_name,
price
FROM
products
WHERE
price > 100 AND price <= 200;
This query retrieves all products with a price greater than $100 and less than or equal to $200.
Logical operators are used to combine multiple conditions in SQL queries. These operators include:
SELECT
customer_id,
first_name,
last_name,
email
FROM
customers
WHERE
country = 'USA' AND (age > 30 OR age < 18);
This query selects all customers who are either under 18 or over 30 years old and reside in the USA.
String operators are used to manipulate string data in SQL. These operators include:
SELECT
product_id,
product_name,
category
FROM
products
WHERE
category LIKE 'Electronics%' AND price BETWEEN 500 AND 1000;
This query retrieves all electronic products priced between $500 and $1000.
SQL operators are fundamental tools for querying and manipulating data in relational databases. By understanding and effectively using arithmetic, comparison, logical, and string operators, you can write powerful SQL queries that meet your business needs. Always consider best practices to ensure your queries are optimized for performance and accuracy.