Module 4: DB2 Data Types and SQL Basics
SELECT
The SELECT statement reads rows from one or more tables or views. It never changes data, so it is the safest SQL to practice with.
SELECT syntax
- Basic shape: SELECT columns FROM table WHERE condition.
- SELECT * reads all columns. In programs, name the columns instead - it is faster and safer.
- Columns can come from the table, from host variables, from constants, or from calculations like SALARY + BONUS.
- Use AS to name a calculated column, for example SELECT SALARY + BONUS AS INCOME.
INTO and FROM clauses
- INTO puts the result into COBOL host variables. The number and types must match the select list.
- A single-row SELECT ... INTO needs exactly one matching row. Zero rows gives +100, more than one gives -811.
- FROM names the table or view. A typical name has two parts: creator.table, for example MM01.CUSTOMER.
WHERE clause
- WHERE keeps only the rows that satisfy the condition. Without WHERE, every row is returned.
- Comparison operators: = < > <> <= >=.
- Values can be literals ('CA'), host variables (:STATE), or expressions.
Example
- Reading one customer row into host variables:-
EXEC SQL
SELECT FNAME, LNAME, STATE
INTO :WS-FNAME, :WS-LNAME, :WS-STATE
FROM MM01.CUSTOMER
WHERE CUSTNO = :WS-CUSTNO
END-EXEC.
IF SQLCODE = 0
DISPLAY 'FOUND: ' WS-FNAME ' ' WS-LNAME
ELSE IF SQLCODE = 100
DISPLAY 'CUSTOMER NOT FOUND'
END-IF.
