SQL Operators: Using WHERE, Comparison, and Logical Operators

SQL operators are essential tools in MySQL for filtering and refining data queries. By using the WHERE clause and various operators, you can efficiently narrow down the data returned by your queries.

1. The WHERE Clause

The WHERE clause is used to filter records based on specific conditions. It is often combined with comparison and logical operators for detailed filtering.

Basic Syntax

SELECT column1, column2, ...
FROM table_name
WHERE condition;

Example

SELECT * FROM employees
WHERE department = 'Sales';

This query retrieves all employees who work in the Sales department.

2. Comparison Operators

Comparison operators are used in SQL to compare values in columns to specified values. Common comparison operators include:

  • = - Equal to
  • > - Greater than
  • < - Less than
  • >= - Greater than or equal to
  • <= - Less than or equal to
  • <> or != - Not equal to

Example

SELECT * FROM employees
WHERE salary > 50000;

This query retrieves all employees whose salary is greater than 50,000.

3. Logical Operators

Logical operators combine multiple conditions in SQL statements. The main logical operators are:

  • AND - Returns true if all conditions are true
  • OR - Returns true if at least one condition is true
  • NOT - Reverses the result of a condition

Example: Using AND

SELECT * FROM employees
WHERE department = 'Sales' AND salary > 50000;

This query retrieves employees in the Sales department who have a salary greater than 50,000.

Example: Using OR

SELECT * FROM employees
WHERE department = 'Sales' OR department = 'Marketing';

This query retrieves employees who work in either Sales or Marketing.

Example: Using NOT

SELECT * FROM employees
WHERE NOT department = 'Sales';

This query retrieves all employees except those in the Sales department.

4. Combining Comparison and Logical Operators

You can use comparison and logical operators together in complex queries.

Example

SELECT * FROM employees
WHERE (department = 'Sales' OR department = 'Marketing')
AND salary >= 60000;

This query retrieves employees in either Sales or Marketing departments with a salary of at least 60,000.

5. Conclusion

Understanding SQL operators enables you to build more flexible and complex queries. Using the WHERE clause with comparison and logical operators helps refine data retrieval, making it more accurate and meaningful.

0 Interaction
883 Views
Views
15 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home