How to sort records using the ORDER BY statement in SQL - Support

How to sort records using the ORDER BY statement in SQL

From Support

Jump to: navigation, search

When there is a need to sort records using SQL, the ORDER BY SQL clause should be used in an SQL statement.

The following is a hard coded SQL sample line to illustrate the use of ORDER BY:

SELECT * FROM NameAddress ORDER BY Last

The following is a hard coded SQL sample line to illustrate the use of ORDER BY to sort by 2 keyfields named Last and First:

SELECT * FROM NameAddress ORDER BY Last, First


The following RPG statement is creating a soft-coded SQL statement with an ORDER BY statement added to the end of the SQL string. If you want to test this code, replace the SQL listed below into the SQTEST23R program in RJSRPGSQL to see how it works:

C                   Eval      SQLStmt = 'SELECT * FROM NameAddress ' +  
C                             'WHERE Last LIKE ' + QUOT + '%' +         
C                             %trimr(ILAST) + '%' + QUOT + ' AND ' +    
C                             'First LIKE ' + QUOT + '%' +              
C                             %trimr(IFIRST) + '%' + QUOT +             
C                             ' ORDER BY Last '
Personal tools