| by Arround The Web | No comments

SQL AND

“In this article, we guide you into understanding how to use the SQL AND operator, allowing you to add conditions to a given query using the WHERE clause.”

Let us dive in and see how the AND operator plays in our SQL statements.

SQL AND Operator

As you can guess, the AND operator is a logical operator that allows you to combine two or more Boolean expressions and treat them as one. This means that all the conditions must be true for the condition to be applied.

You will find the AND operator used in a WHERE clause in conjunction with other SQL statements such as SELECT, UPDATE, and DELETE.

This allows you to limit the scope of which the action performs. For example, using a DELETE statement, you can use the WHERE clause and the AND keyword to ensure that only the data that satisfy the specified condition is removed.

The syntax of the AND operator can be expressed as shown below:

bool_expr_1 AND bool_expr_2 AND bool_expr_3… AND bool_expr_N;

You can have as many Boolean expressions as you wish. However, remember that all the specified expressions MUST evaluate to be true. If one expression is false, the entire statement is treated as false.

NOTE: NULL values are also treated as false.

Example Usage

Suppose we have sample data as shown in the queries below:

DROP DATABASE IF EXISTS sampledb;
CREATE DATABASE sampledb;
USE sampledb;
CREATE TABLE developers(
    id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50),
    department VARCHAR(50) NOT NULL,
    salary INT
);
INSERT INTO developers(first_name, last_name, department, salary)
VALUES
    ('Rogan', 'Ellison', 'game', 120000),
    ('Anne', 'Neale', 'database', 122000),
    ('Frazer','Kouma', 'frontend', 100000),
    ('Krish','Pollard', 'backend', 115000),
    ('Asa', 'Ford', 'devops', 118000),
    ('Sahil', 'Sierra', 'game', 135000),
    ('Keira', 'Deacon', 'database', 130000),
    ('Inaaya', 'Hanson', 'cloud', 123000),
    ('Bogdan', 'Morley', 'frontend', 108000),
    ('Mariah', 'Goldsmith', 'backend', 120000);

Resulting table:

To find the developers working in the “devops” department and have a salary higher than 110000, we can run a query as shown:

SELECT * FROM developers WHERE department = 'devops' AND salary >= 110000;

The query should find the matching records and return them as shown:

id|first_name|last_name|department|salary|
--+----------+---------+----------+------+
5|Asa       |Ford     |devops    |118000|

In this case, there is only one record, as shown above. You can specify more conditions to filter out your data further using the AND keyword.

Conclusion

In this post, we discussed how to use the AND operator in SQL to combine multiple Boolean expressions in your queries.

Thanks for reading. Check our SQL OR operator tutorial to learn more about the OR operator and how it works compared to the AND operator.

Share Button

Source: linuxhint.com

Leave a Reply