<!-- https://learnsql.cpetoday.com/functions/m/table-firstn -->
# Table.FirstN

Language: Power Query M
Category: Table: rows
Syntax: Table.FirstN(table as table, countOrCondition as any) as table
Summary: Keeps the first rows, either a set number or while a condition holds.
Returns: A table with the first rows.
Level: Beginner
Related: Table.LastN, Table.Skip, Table.Sort, Table.SelectRows

## What it does
Table.FirstN keeps the top rows of a table. Used on its own it gives you a sample to check the layout. Used after a sort, it gives you a top list, such as the ten largest customers by credit limit. The sort is what gives the rows meaning, because the database does not promise any order unless you ask for one.

## Syntax and arguments
- **table**: the table to read from. Required.
- **countOrCondition**: a number of rows to keep, or a function. With a function, rows are kept from the top while the function returns true, and the first row that fails stops the list. Required.

## Example
A credit committee wants the ten customers with the highest credit limits in the sample database.

```powerquery
let
    Source = Sql.Database("learnsql.cpetoday.com,1433", "classicmodels"),
    Customers = Source{[Schema = "classicmodels", Item = "customers"]}[Data],
    Ranked = Table.Sort(Customers, {{"creditLimit", Order.Descending}}),
    Top10 = Table.FirstN(Ranked, 10)
in
    Top10
```

The table is sorted from the highest limit down, and the first ten rows are kept. Both steps are simple enough that Power Query can send them to the database as one query.

## Example: a second, different use
A transaction list is sorted by date. The first run of rows that share a clean date is kept, and the list stops at the first blank date.

```powerquery
let
    Source = Excel.CurrentWorkbook(){[Name = "Bank"]}[Content],
    Clean = Table.FirstN(Source, each [Date] <> null)
in
    Clean
```

## Things to watch
- Sort before you take the top rows. Without a sort, the first rows are whatever the source returns first.
- Ties at the cut-off can leave out equal values. If the tenth and eleventh customers have the same limit, only one is kept.
- Query folding: a row count after a sort usually folds into TOP and ORDER BY. The condition form usually does not. Check View Native Query.
- Use FirstN for a preview while you build a query, and remove it before the final load if you need every row.

## In business terms
Top-ten lists for credit reviews, largest vendors for a spend review and the first lines of an export to check the layout are typical uses in finance work.
