In MySQL, conditional logic plays a crucial role when querying data. The ability to use logical operators such as AND, OR, and NOT empowers developers to build powerful, complex filters for selecting or modifying rows in a database.
This tutorial covers the practical usage, syntax, and real-world examples of these operators. You will learn how to combine them, avoid logical mistakes, and improve query precision while querying or manipulating your data.
Logical operators are used in the WHERE clause to combine one or more conditions. The common logical operators supported by MySQL include:
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2;
SELECT * FROM employees
WHERE department = 'Sales' AND salary > 40000;
This query returns all employees from the Sales department whose salary is greater than 40,000.
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2;
SELECT * FROM employees
WHERE department = 'Sales' OR department = 'Marketing';
This query returns employees who belong to either the Sales or Marketing department.
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
SELECT * FROM employees
WHERE NOT department = 'IT';
This query retrieves all employees who are not in the IT department.
These operators can be combined to form more complex conditions. Use parentheses () to group conditions and control precedence.
SELECT * FROM employees
WHERE department = 'Sales' AND (salary > 50000 OR experience_years > 5);
This query fetches employees from the Sales department who either earn more than 50,000 or have more than 5 years of experience.
MySQL evaluates conditions in the following order unless overridden by parentheses:
SELECT * FROM employees
WHERE NOT department = 'Finance' AND salary > 50000 OR experience_years > 10;
Due to operator precedence, this condition is interpreted as:
(NOT department = 'Finance') AND (salary > 50000) OR (experience_years > 10);
To change this logic, you should use parentheses explicitly.
SELECT * FROM employees
WHERE NOT (department = 'Finance' AND salary > 50000) OR experience_years > 10;
SELECT * FROM customers
WHERE city = 'New York' AND (age >= 30 OR membership = 'Premium');
Returns customers from New York who are either 30+ years old or have a premium membership.
SELECT * FROM orders
WHERE NOT status = 'Cancelled' AND (total_amount > 500 OR priority = 'High');
Returns orders that are not cancelled and either have a high priority or total above 500.
DELETE FROM users
WHERE is_active = 0 AND (created_at < NOW() - INTERVAL 1 YEAR);
Deletes users who are inactive and were created more than a year ago.
UPDATE products
SET discount = 20
WHERE category = 'Electronics' OR price > 1000;
Applies a 20% discount to all electronics or products priced above 1000.
SELECT * FROM employees
WHERE department IN ('IT', 'Finance') AND status = 'active';
SELECT * FROM products
WHERE price BETWEEN 500 AND 1000 OR category = 'Luxury';
SELECT * FROM customers
WHERE NOT email LIKE '%@example.com';
Returns customers who do not have an email with @example.com domain.
Use multiple levels of parentheses to build deeply nested logical queries.
SELECT * FROM employees
WHERE (department = 'HR' AND salary > 30000)
OR (department = 'IT' AND (experience_years > 5 OR certification = 'Yes'));
SELECT * FROM products
WHERE price IS NULL OR quantity <= 0;
This query identifies products that either have no price or are out of stock.
Logical operators can also be used in HAVING to filter group results.
SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
HAVING total > 10 AND department != 'Intern';
DELIMITER //
CREATE PROCEDURE GetQualifiedEmployees()
BEGIN
SELECT * FROM employees
WHERE (department = 'Sales' AND salary > 50000)
OR (department = 'IT' AND experience_years > 5);
END //
DELIMITER ;
EXPLAIN SELECT * FROM employees
WHERE department = 'Sales' AND salary > 50000;
You want to select employees eligible for a bonus. Criteria:
SELECT * FROM employees
WHERE (department = 'Sales' OR department = 'Support')
AND experience_years > 3
AND salary < 70000;
If your query returns unexpected results, test each logical component separately:
SELECT * FROM employees WHERE department = 'Sales';
SELECT * FROM employees WHERE experience_years > 3;
SELECT * FROM employees WHERE salary < 70000;
Then combine them once verified individually.
MySQL's logical operators AND, OR, and NOT are fundamental tools for building complex and precise queries. They provide developers with flexibility in defining custom logic for filtering data. By mastering these operators, you can write more expressive queries, maintain clean and optimized SQL code, and avoid common logic pitfalls. Proper use of parentheses and understanding operator precedence ensures that your logic yields correct and expected results.
Use the command: CREATE INDEX index_name ON table_name (column_name); to create an index on a MySQL table.
To install MySQL on Windows, download the installer from the official MySQL website, run the setup, and follow the installation wizard to configure the server and set up user accounts.
MySQL is an open-source relational database management system (RDBMS) that uses SQL (Structured Query Language) for managing and manipulating databases. It is widely used in web applications for its speed and reliability.
Use the command: INSERT INTO table_name (column1, column2) VALUES (value1, value2); to add records to a MySQL table.
Use the command: mysql -u username -p database_name < data.sql; to import data from a SQL file into a MySQL database.
DELETE removes records based on a condition and can be rolled back, while TRUNCATE removes all records from a table and cannot be rolled back.
A trigger is a set of SQL statements that automatically execute in response to certain events on a MySQL table, such as INSERT, UPDATE, or DELETE.
The default MySQL port is 3306, and the root password is set during installation. If not set, you may need to configure it manually.
Replication in MySQL allows data from one MySQL server (master) to be copied to one or more servers (slaves), providing data redundancy and load balancing.
A primary key is a unique identifier for a record in a MySQL table, ensuring that no two records have the same key value.
Use the command: SELECT column1, column2 FROM table_name; to fetch data from a MySQL table.
Use the command: CREATE DATABASE database_name; to create a new MySQL database.
Use the command: CREATE PROCEDURE procedure_name() BEGIN SQL_statements; END; to define a stored procedure in MySQL.
Indexing in MySQL improves query performance by allowing the database to find rows more quickly. Common index types include PRIMARY KEY, UNIQUE, and FULLTEXT.
Use the command: UPDATE table_name SET column1 = value1 WHERE condition; to modify existing records in a MySQL table.
CHAR is a fixed-length string data type, while VARCHAR is variable-length. CHAR is faster for fixed-size data, whereas VARCHAR saves space for variable-length data.
MyISAM is a storage engine that offers fast read operations but lacks support for transactions, while InnoDB supports transactions and foreign keys, providing better data integrity.
A stored procedure is a set of SQL statements that can be stored and executed on the MySQL server, allowing for modular programming and code reuse.
Use the command: mysqldump -u username -p database_name > backup.sql; to create a backup of a MySQL database.
Use the command: DELETE FROM table_name WHERE condition; to remove records from a MySQL table.
A foreign key is a column or set of columns in one MySQL table that references the primary key in another, establishing a relationship between the two tables.
Use the command: CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN SQL_statements; END; to create a trigger in MySQL.
Normalization in MySQL is the process of organizing data to reduce redundancy and improve data integrity by dividing large tables into smaller ones.
JOIN is used to combine rows from two or more MySQL tables based on a related column, allowing for complex queries and data retrieval.
Use the command: mysqldump -u username -p database_name > backup.sql; to export a MySQL database to a SQL file.
Copyrights © 2024 letsupdateskills All rights reserved