TSO-ISPF JCL COBOL VSAM DB2 CICS Tools Articles Job Portal Forum Quiz Interview Q&A

DB2 - SQL Where Clause


The WHERE clause is used to filter records.

Retrieving just the data you want, involves specifying search criteria, also known as a filter condition. Within a SELECT statement, data is filtered by specifying search criteria in the WHERE clause.

Syntax:

SELECT column1, column2, ...
  FROM table_name
 WHERE condition;

WHERE clause is not only used in SELECT statement, it is also used in UPDATE, DELETE statement.

DB2 Database:

Below is a selection from the "Product" table in the DB2 database.

ProductIDProductDescCategorySRPQtyOnHandTotalValue
7001MouseAccessories75.00
7002Harddrive65.00201,300
7003KeyboardAccessories36.00331,118.00
7004RAMComponents23.5016376.00
7005HondaBikes1,200
7006PEN7.451074.50
7007CddriveAccessories75.00
7008SpeakerAccessories75.00

Example:

The below SQL statement retrieves two columns from the "Product" table, but instead of returning all rows, only rows with a SRP value of 75.00 are returned.

SELECT ProductID, ProductDesc
  FROM Product
 WHERE SRP = 75.00;
Result:
ProductIDProductDesc
7001Mouse
7007Cddrive
7008Speaker

Numeric Fields vs Text Fields

SQL requires single quotes around text values (most database systems will also allow double quotes).. However, numeric fields should not be enclosed in quotes.

SELECT ProductID, ProductDesc, SRP
  FROM Product
 WHERE Category = 'Accessories';
Result:
ProductIDProductDescSRP
7001Mouse75.00
7003Keyboard36.00
7007Cddrive75.00
7008Speaker75.00

WHERE Clause Operators:

SQL supports a whole range of conditional operators in the WHERE clause as listed.

OperatorDescription
=Equality
<>Non-equality
!=Non-equality
<Less than
<=Less than or equal to
!<Not less than
>Greater than
>=Greater than or equal to
!>Not greater than
BETWEENBetween two specified values including the specified start and end value
IS NULLIs a NULL value


Example 1:

To List all products that cost less than $10

SELECT ProductID, ProductDesc
  FROM Product
 WHERE SRP < 10;
Result:
ProductIDProductDesc
7006PEN

Example 2:

To List all Category products other than 'Accessories'

SELECT ProductID, ProductDesc, SRP
  FROM Product
  WHERE Category <> 'Accessories';
Result:
ProductIDProductDescSRP
7002Harddrive65.00
7004RAM23.50
7005Honda1,200
7006PEN7.45

Example 3:

To retrieve all products with a price between $5 and $10, including the specified start and end values.

SELECT ProductID, ProductDesc
  FROM Product
  WHERE SRP BETWEEN 5 AND 25;
Result:
ProductIDProductDesc
7004RAM
7006RAM

Example 4:

To return a list of all products that have no Category(i.e. null value)

SELECT ProductID, ProductDesc, SRP
  FROM Product
 WHERE Category IS NULL;
Result:
ProductIDProductDescSRP
7002Harddrive65.00
7006PEN7.45


If you have any doubts or queries related to this chapter, get them clarified from our Mainframe experts on ibmmainframer Community!

Are you looking for Job Change? Job Portal