Db2 SQL Syntax and Syntax Diagrams

IBM documents Db2 SQL with syntax diagrams—visual maps that show which keywords are required, which clauses are optional, and how lists repeat. Learning to read those diagrams is a career skill: the SQL Reference becomes usable instead of intimidating. This page covers SQL syntax basics, how to read Db2 syntax diagrams, and how to write SQL comments safely.

SQL fundamentals
Progress0 of 0 lessons

What “SQL syntax” means

Syntax is the grammar of the language: the legal order of keywords, identifiers, operators, and punctuation. Semantics is what a legal statement means. A statement can be syntactically valid and still wrong for the business (update the wrong rows) or fail at run time (object not found, wrong data type). Beginners should separate “Db2 rejected my grammar” from “Db2 ran it and I dislike the result.”

Db2 SQL statements are built from tokens: keywords (SELECT), identifiers (EMPLOYEE), operators (=, AND), literals ('A01'), special characters (parentheses, commas), and comments. Whitespace generally separates tokens; formatting is for humans. Your team style guide still matters for reviews.

Core syntax habits that prevent errors

  • Match parentheses carefully in expressions and function calls
  • Separate list items with commas where the diagram shows commas
  • End interactive statements according to your tool (often a semicolon in SPUFI)
  • In COBOL, wrap SQL in EXEC SQL ... END-EXEC and watch host-variable colons
  • Do not invent clauses; if the diagram lacks a keyword, Db2 will not accept it
sql
1
2
3
4
SELECT EMP_ID, EMP_NAME FROM EMPLOYEE WHERE DEPT_ID = 'A01' ORDER BY EMP_NAME;

That statement follows a familiar pattern: SELECT list, FROM object, optional WHERE, optional ORDER BY. Syntax diagrams formalize patterns like this for every statement, including ones with many optional branches.

How to read SQL syntax diagrams

IBM’s Db2 manuals use railroad diagrams. You read them left to right, top to bottom, following the path of the line. The following conventions appear throughout the SQL Reference (wording adapted for learners; always check the manual’s “How to read syntax diagrams” section for the edition you use).

Common syntax diagram conventions
Symbol / styleMeaning
►►── / beginning markerStart of the statement or fragment
───► continuationDiagram continues on the next line
►── continuedThis line continues a previous line
───►◄ end markerEnd of the statement or fragment
UPPERCASEKeyword; type as shown (case-insensitive in SQL)
lowercase-nameVariable: replace with your value

Keywords vs variables

Keywords appear in UPPERCASE in diagrams (FROM, WHERE, JOIN). You must spell them as shown; SQL treats them case-insensitively when you type. Variables appear in lowercase italic-style names such as table-name or search-condition. You replace those with real names or with fragments defined in other diagrams.

Required path vs optional branches

The main horizontal line is the required spine of the statement. Optional items usually appear on a branch above or below the main line—you may take the branch or skip it. Alternate choices appear as parallel branches where you pick one path. Repeating items often show a loop arrow so you can return and add another list element (for example more columns in a select list).

text
1
2
3
4
5
6
7
8
Conceptual SELECT fragment (not an official IBM drawing): ►►─ SELECT ─┬─ * ───────────────────┬─ FROM table-name ──►◄ └─ column-list ─────────┘ column-list: ├── column-name ┬───────────────────┤ └─ , column-name ←──┘ (repeat with commas)

Punctuation is real syntax

If the diagram shows parentheses, commas, periods, asterisks, or operators, type them. They are not decoration. Beginners often drop commas between select-list items or forget parentheses around expressions—both are syntax errors.

Fragments point to other rules

Diagrams frequently reference other nonterminals such as expression, search-condition, or fullselect. That means you must also follow the rules for those diagrams. Professional SQL reading is recursive: open the referenced section when you need a clause you have not memorized.

Statement layout in programs and tools

Free-form SQL tools let you break lines between tokens. Embedded SQL in COBOL sits inside EXEC SQL blocks; COBOL margin rules still apply to the surrounding source, and many sites keep SQL verbs aligned for readability. Dynamic SQL strings in host variables must contain complete, legal statement text when prepared.

cobol
1
2
3
4
5
6
EXEC SQL SELECT COUNT(*) INTO :WS-COUNT FROM EMPLOYEE WHERE DEPT_ID = :WS-DEPT END-EXEC.

SQL comments

Comments document intent without changing meaning. Db2 SQL supports common comment forms you will see in scripts and generated SQL.

Simple comments with --

Two consecutive hyphens start a simple comment. The comment runs to the end of the line. Use them to label predicates, note ticket numbers, or temporarily disable a clause while testing in a scratch pad (prefer version control over commenting out production logic long term).

sql
1
2
3
4
SELECT EMP_ID, EMP_NAME -- directory fields only FROM EMPLOYEE WHERE DEPT_ID = 'A01'; -- active department filter -- AND STATUS = 'ACTIVE' -- temporarily ignored in this test

Bracketed comments with /* */

Bracketed comments begin with /* and end with */. They can span multiple lines. Nested bracketed comments are not something to rely on; keep comments simple. Avoid placing comment delimiters inside string literals accidentally—your string may end early and the rest looks like broken SQL.

sql
1
2
3
4
5
6
7
8
SELECT EMP_ID, EMP_NAME FROM EMPLOYEE /* Multi-line note: Used by HR roster report. */ WHERE HIRE_DATE >= DATE('2020-01-01');

Comments vs host-language comments

Inside the SQL statement text, use SQL comment syntax. Outside EXEC SQL in COBOL, use COBOL comments (for example * in the indicator area). Mixing them up is a frequent beginner mistake: a COBOL * does not comment out SQL keywords inside the EXEC SQL block the way newcomers expect.

Worked mini-example: turning a diagram into SQL

Suppose a simplified diagram says: keyword DELETE, keyword FROM, variable table-name, optional branch with keyword WHERE plus search-condition. Valid statements include deleting all rows from a table (dangerous) or deleting with a predicate (usual).

sql
1
2
3
4
5
6
-- Optional WHERE taken DELETE FROM TEMP_STAGE WHERE LOAD_DATE < CURRENT DATE - 7 DAYS; -- WHERE branch skipped means "all rows" — confirm intentionally! -- DELETE FROM TEMP_STAGE;

The diagram teaches the option. Professional judgment decides whether skipping WHERE is acceptable. Syntax skill plus operational caution belong together.

Common syntax mistakes

  • Misspelled keywords (FORM instead of FROM)
  • Missing commas in SELECT lists or VALUES lists
  • Unbalanced parentheses in complex predicates
  • Using a host-language comment style inside SQL text
  • Assuming a clause exists because another DBMS supports it
  • Forgetting that ordered clauses still must follow legal diagram order

When Db2 returns a syntax error, read the message token pointing near the failure, then open the statement’s syntax diagram and compare clause order. That workflow scales to unfamiliar statements better than guessing.

Explain It Like I'm Five

A syntax diagram is like a treasure map for a sentence. The thick path shows words you must say, like “please” and “thank you.” Side paths show extra words you may add, like “with whipped cream.” Loopy arrows mean you can name more toppings, comma after comma. Uppercase words are fixed magic words. Lowercase blanks are spaces where you pencil in your own names. Comments are sticky notes on the map that the cook ignores when making the food.

Exercises

  1. Open any SELECT diagram in IBM’s SQL Reference (or a training extract) and list three optional clauses you see.
  2. Rewrite a one-line SELECT into a multi-line, readable form and add a -- comment above the WHERE clause.
  3. Mark each token in SELECT A, B FROM T WHERE C = 1 as keyword, identifier, operator, or literal.
  4. Explain why /* comment */ inside a quoted string can break a statement if misplaced.
  5. Given a diagram with an optional WHERE branch, write one DELETE that uses WHERE and describe what happens if you omit it.

Quiz

Test Your Knowledge

1. In IBM SQL syntax diagrams, what do uppercase words usually represent?

  • User-supplied variable values
  • Keywords that must appear as shown
  • Optional comments only
  • JCL parameters

2. What do lowercase names like column-name usually mean in a syntax diagram?

  • They are optional keywords you must type in lowercase
  • They are placeholders for user-supplied names or values
  • They are always null
  • They disable the optimizer

3. Which comment form starts with two hyphens?

  • /* block comment */
  • -- simple comment to end of line
  • Only # comments
  • Only COBOL * in column 7

4. What do brackets or optional branches in syntax diagrams generally indicate?

  • That the statement is illegal
  • That a fragment is optional or that you choose among paths
  • That IRLM must stop
  • That you must repeat the fragment forever

5. Must punctuation shown in a syntax diagram (parentheses, commas) be typed?

  • No, punctuation is only decorative
  • Yes, enter punctuation and operators exactly as shown when they appear on the main path
  • Only commas matter; parentheses never do
  • Only in COBOL, never in SPUFI