How to Use Logical Operators in SQL Query

Here is an example that shows usage of logical operators (AND and OR) in SQL query in WHERE clause.

SQL WHERE the AND and OR

Why do we need AND condition in the WHERE clause? To give more than one condition and both to satisfy. The other condition is OR. Why do we need OR in WHERE? To get rows that have any one condition satisfied.

So limiting rows in SQL [asktom.oracle.com/] output can do it using the where clause with AND and OR. The AND and OR conditions examples here show you how to achieve it.

AND condition in WHERE

In the below query, you will get rows, from the INVOICES table, where the invoice date is > 12th JAN 2022 and the Total is less than $5[developer.salesforce.com]

Invoices table

Invoices table
InvoicesTable
SELECT
    InvoiceDate,
    BillingAddress,
    BillingCity,
    Total
FROM
    invoices
WHERE
    DATE(InvoiceDate) > '2022-01-12' AND Total < 5
ORDER BY
    Total
32 Complex SQL Queries

OR condition in WHERE

The OR operator in the WHERE allows you to get rows that match any criteria. The below query pulls the rows BillingCity’s first letter of ‘p’ or ‘d.’

SELECT
    InvoiceDate,
    BillingAddress,
    BillingCity,
    Total
FROM
    invoices
WHERE
    BillingCity LIKE 'p%' OR BillingCity LIKE 'd%'
ORDER BY
    Total

AND and OR conditions in the WHERE clause

This query shows you to use both AND and OR. So that you can limit the rows in the output.

SELECT
    InvoiceDate,
    BillingAddress,
    BillingCity,
    Total
FROM
    invoices
WHERE
    Total > 1.98 AND BillingCity LIKE 'p%' OR
    BillingCity LIKE 'd%'
ORDER BY
    Total

Related

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.