Open In App

Boolean Expressions in SQL

Boolean expressions are that expression that returns boolean datatype as result. In SQL there are three values for boolean datatype, those are:

The boolean data type can not be specified during table creation, unlike other data types. Boolean expressions are mainly used with WHERE clauses to filter the data from a table. It can include comparison operators and other operators like ‘AND’ operator, ‘OR’ operator, etc.



For a demonstration of boolean expressions, follow the below steps:

Step 1: Create a database



we can use the following command to create a database called geeks.

Query:

CREATE DATABASE geeks;

Step 2: Use database

Use the below SQL statement to switch the database context to geeks:

Query:

USE geeks;

Step 3: Table definition

We have the following demo_table in our geek’s database.

Query:

CREATE TABLE demo_table(
NAME VARCHAR(20),
AGE INT,
CITY VARCHAR(20) );

Step 4: Insert data into a table

Query:

INSERT INTO demo_table VALUES
('ROMY', 22, 'NEW DELHI'),
('PUSHKAR',23, 'NEW DELHI'),
('AKANKSHA',22, 'PUNJAB'),
('SUJATA', 30,'PATNA'),
('PREETI', 26,'BANGLORE'),
('PREM',31,'PUNE'),
('RAM', 34,'PUNE'),
('SHEETAL',32, 'RAJASTHAN'),
('SAMITA',25,'HIMACHAL');

Step 5: View data of the table

Query:

SELECT * FROM demo_table;

Output:

Step 6: Boolean expressions

Example 1: Boolean expression including equal to(=) comparison operator 

Query:

SELECT * FROM demo_table
WHERE AGE = 22;                                
{Boolean expression - > (AGE =22)}

This query will return the values from the table where the AGE column has data equal to 22.

Output:

Example 2:  Boolean expression including greater than(>) comparison operator 

Query :

SELECT * FROM demo_table
WHERE AGE > 22;                                      
{Boolean expression - > (AGE > 22)}

Output:

Example 3: Boolean expression including ‘OR’ operator

OR operator return value when any one of the specified conditions is True.

Query:

SELECT * FROM demo_table
WHERE AGE = 22 OR AGE = 23;         
{Boolean expression - > (AGE = 22 OR AGE = 23)}

Output:

Article Tags :
SQL