CHAMPION KAY TUTORIAL

SQL TOP Clause


The TOP Clause

The TOP clause is used to specify the number of records to return.
The TOP clause can be very useful on large tables with thousands of records. Returning a large number of records can impact on performance.
Note: Not all database systems support the TOP clause.

SQL Server Syntax

SELECT TOP number|percent column_name(s)
FROM table_name

SQL SELECT TOP Equivalent in MySQL and Oracle

MySQL Syntax

SELECT column_name(s)
FROM table_name
LIMIT number

Example


SELECT *
FROM Persons
LIMIT 5

Oracle Syntax

SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number

EXAMPLE:

SELECT *
FROM Persons
WHERE ROWNUM <=5

SQL TOP Example

The "Persons" table:

1ADNANADTimoteivn 10Sandnes
2UMAIRUMIBorgvn 23Sandnes
3ASADASDStorgt 20Stavanger
4ALIPAPIVingvn 23Stavanger


Now we want to select only the two first records in the table above.
We use the following SELECT statement:

SELECT TOP 2 * FROM Persons

The result-set will look like this:

1HansenOlaTimoteivn 10Sandnes
2SvendsonToveBorgvn 23Sandnes


SQL TOP PERCENT Example

The "Persons" table:

1HansenOlaTimoteivn 10Sandnes
2SvendsonToveBorgvn 23Sandnes
3PettersenKariStorgt 20Stavanger
4NilsenTomVingvn 23Stavanger


Now we want to select only 50% of the records in the table above.
We use the following SELECT statement:

1UMAIRUMITimoteivn 10Sandnes
2ALIpApiBorgvn 23Sandnes


0 comments:

Post a Comment