YogeshChauhan.com
PostgreSQL BETWEEN
November 1, 2020

BETWEEN operator/construct = useful to match a value against a range of values.

The syntax is quite like this:


value_of_rows BETWEEN x AND y;

x and y are just end points and they are inclusive.

You can rewrite the same syntax from above without using BETWEEN as well:


value_of_rows >= x AND value_of_rows <= y;

Let’s take a look at the examples of both:

I am using the database available on my Github public repo

Example with BETWEEN:


SELECT product_name, unit_price 
FROM products 
WHERE unit_price 
BETWEEN 40 AND 50;

//Output
product_name.         unit_price 
"Northwoods Cranberry Sauce"	40
"Schoggi Schokolade"	43.9
"Rössle Sauerkraut"	45.6
...
...

Example without BETWEEN


SELECT product_name, unit_price 
FROM products 
WHERE unit_price >= 40 AND unit_price <= 50;

//Output
product_name.         unit_price 
"Northwoods Cranberry Sauce"    40
"Schoggi Schokolade"    43.9
"Rössle Sauerkraut"    45.6
...
...

To get the values out of that range, all we need to do is add NOT.

Example with NOT BETWEEN:


SELECT product_name, unit_price 
FROM products 
WHERE unit_price 
NOT BETWEEN 40 AND 50;

//Output
product_name.  unit_price 
"Chai"	18
"Chang"	19
"Aniseed Syrup"	10
...
...

You can achieve same results without using NOT BETWEEN as well:

Example without NOT BETWEEN:


SELECT product_name, unit_price 
FROM products 
WHERE unit_price < 40 OR unit_price > 50;

//Output
product_name.  unit_price 
"Chai"	18
"Chang"	19
"Aniseed Syrup"	10
...
...

Pay attention to the fact that, we needed to use OR to do so.

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

How to refresh a page using PHP at regularly occurring intervals?PHPHow to catch .keypress() on body using jQuery?jQueryIntroduction to Angular modules Part 1: NgModule metadataAngularHow to change CSS with jQuery?CSSHow to merge arrays in JavaScript?JavaScriptUPDATE and DELETE Statements in PostgresPostgres