Published on

SQL Operators Unleashed! πŸ› οΈ

Authors
  • avatar
    Name
    Edward Villarin
    Twitter

SQL Operators Unleashed! πŸ› οΈ

SQL operators are the superpowers behind your database queries, letting you slice, dice, and manipulate data with ease! πŸͺ„ These symbols and keywords are essential for building queries that filter, compare, and transform data. Whether you're doing math, comparing values, or combining results, operators are your go-to tools. Here’s the breakdown of the main types:

  • Arithmetic Operators βž•βž–βœ–οΈβž—: Perform calculations like addition (+), subtraction (-), multiplication (*), and division (/).
  • Comparison Operators βš–οΈ: Compare values with = (equal), != or <> (not equal), < (less than), > (greater than), <=, and >=.
  • Logical Operators 🀝: Combine conditions using AND (both true), OR (at least one true), and NOT (inverts a condition).
  • Set Operators 🧩: Merge query results with UNION (all rows), INTERSECT (common rows), or EXCEPT (rows in one but not another).

These operators give you laser-like precision in retrieving and modifying data, making your queries both powerful and flexible! 🌟

Sample Code: SQL Operators in Action! πŸ’»

Here’s a sample SQL query using an employees table (columns: employee_id, name, salary, department, hire_date) to show operators at work:

-- Create a sample employees table
CREATE TABLE employees (
    employee_id INT,
    name VARCHAR(50),
    salary DECIMAL(10, 2),
    department VARCHAR(30),
    hire_date DATE
);

-- Insert sample data
INSERT INTO employees VALUES
(1, 'Alice', 75000.00, 'IT', '2023-01-15'),
(2, 'Bob', 60000.00, 'HR', '2022-06-20'),
(3, 'Charlie', 80000.00, 'IT', '2021-09-10'),
(4, 'Diana', 65000.00, 'HR', '2023-03-05');

-- Query using multiple operators
SELECT name, salary, department
FROM employees
WHERE department = 'IT' AND salary > 70000  -- Comparison and Logical operators
ORDER BY salary * 1.1 DESC;  -- Arithmetic operator for a 10% raise projection

-- Combine results using a set operator
SELECT name, department
FROM employees
WHERE salary >= 70000
UNION
SELECT name, department
FROM employees
WHERE hire_date < '2023-01-01';