Monday, October 1, 2007

SQL Technique:

Extract ONLY n Rows from a table.

To limit the amount of results that a query may retrieve, the “FETCH FIRST N ROWS ONLY” is a useful technique:

SELECT * FROM TABLE_NAME
FETCH FIRST 10 ROWS ONLY

The last clause ensures that only 10 rows are fetched.

Method to simulate a "right-justify" for character data using SQL
There is no "right-justify" string function built into SQL, but it can still be done: Taking a character string of variable size and right-justifying within a target column
containing a maximum of 12 characters. The example below does a bit more but it illustrates well what can be done, effectively concatenating blanks (up to 12) for a length of 12 - the length of the source column.

INSERT INTO TARGET_TABLE
SITE_CODE_RIGHT_JUSTIFED
SELECT
SUBSTR(' ', 1, 12 -
LENGTH( TRIM( CHAR_COLUMN_NAME)))
|| TRIM( CHAR_COLUMN_NAME )
FROM TABLE
FROM SOURCE_DATA

No comments: