Use this file to discover all available pages before exploring further.
In this article, learn how to simplify SQL queries by using the IN operator in place of multiple OR conditions, ensuring cleaner syntax and easier maintenance.
If you need to filter products based on specific IDs—such as 1, 2, and 3—the OR approach can be verbose:
SELECT * FROM products WHERE id = 1 OR id = 2 OR id = 3;
Instead, using the IN operator streamlines the query considerably:
SELECT * FROM products WHERE id IN (1, 2, 3);
The output for this query may be as follows:
Data Output| name | character varying | price | integer | id | [PK] integer | is_sale | boolean | inventory | integer | created_at | timestamp with time zone ||---------------|-------------------|-------|---------|----|---------------|---------|---------|-----------|---------|-------------|--------------------------|| TV | | 200 | 1 | false | 0 | 2021-08-20 00:49:58.021274-04 || DVD Players | | 80 | 2 | false | 0 | 2021-08-20 00:49:58.021274-04 || remote | | 10 | 3 | false | 0 | 2021-08-20 00:49:58.021274-04 |
Using the IN operator not only reduces the repetition of SQL keywords but also improves readability, especially when filtering based on multiple values.
Both methods—chaining multiple OR conditions and using the IN operator—yield the same result. However, the IN operator provides a more robust and clear solution to filter data across multiple values. Here is the concise version once again:
SELECT * FROM products WHERE id IN (1, 2, 3);
This approach is especially beneficial when dealing with larger sets of filtering criteria, making your queries easier to write and understand.