# Dataset Sort: sort CSV, JSON & dataset rows (`ucchiii/dataset-sort`) Actor

Sorts the rows of an Apify dataset or a CSV / JSON file by one or more columns: ascending or descending, as numbers, text or dates, natural order (item 2 before item 10), empty values first or last. Top-N, dedupe, CSV export. Empty input = free demo.

- **URL**: https://apify.com/ucchiii/dataset-sort.md
- **Developed by:** [Actor Factory](https://apify.com/ucchiii) (community)
- **Categories:** Developer tools, Automation, Integrations
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.14 / 1,000 output rows

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

**Sort the rows of a CSV, JSON file or Apify dataset**

**Puts your rows in the order you need, by one or more columns.** For anyone whose data comes back in whatever order the source felt like: a scraper dataset you want by price, a CSV export you want by country and then by date, a list of files named `item 2`, `item 10` that should count the way a person counts. Name the columns, press Start, and download the sorted rows as CSV, JSON or Excel from the dataset (or as one CSV file). It works from the Console form: no code, no spreadsheet.

**Try it free: leave all inputs empty and press Start** (the demo is not charged and its rows carry `_demo: true`).
**$0.20 per 1,000 output rows**, charged per row ($0.0002 a row). Sorting 5,000 rows costs $1.00. The $5 monthly free credit covers about 25,000 output rows. You pay only for the rows you get back, so a "top 10" costs $0.002. Reading rows is free. Failed runs, runs with no output rows and the demo are free. No scraping, no API keys.

### Sample

Input rows (a dataset or a CSV file), **Sort keys**: `["category", {"field": "price", "direction": "desc", "type": "number"}]`

| category | price |
|---|---|
| tools | 12.50 |
| Garden | 7 |
| garden | 1,200 |
| Tools | 99.9 |

Output:

| category | price |
|---|---|
| garden | 1,200 |
| Garden | 7 |
| Tools | 99.9 |
| tools | 12.50 |

The rows come back exactly as they were, only in a new order: no column is added or changed.

### What it does

- **Sorts by several columns**: the first key is the main order, the next keys break ties. Every key has its own direction (`asc` or `desc`), type, case option, natural-order option and empty-value position.
- **Three kinds of values**: **numbers** (also written as `1,200`, `$5`, `12%` or `1e3`), **text**, and **dates** (`2026-03-04`, `2026-03-04T10:00:00Z`, `2026/03/04`, `4 Mar 2026`, `2026年3月4日`, or `03/04/2026` when you say whether the month or the day comes first). With type `auto` the whole column decides: all numbers = number, all dates = date, otherwise text. Set the type yourself for a column that mixes kinds (ZIP codes, IDs with leading zeros).
- **Natural order**: with **Natural order** on, digits inside text count as numbers, so `item 2` comes before `item 10` and `v1.9` before `v1.10`.
- **Case**: text is compared without regard to case by default (`apple`, `Banana`, `cherry`). Turn **Ignore case** off for a strict character order.
- **Empty values** (missing, null, blank, or not readable as the chosen type) go to the end or the start of the result, whichever you choose, also when you sort descending.
- **Stable**: rows that are equal on every key keep their original order. With several datasets and files, they are read in the order you give and sorted together as one table.
- **Top N and offset**: return only the first N rows of the sorted result (the 10 most expensive, the 5 newest), and skip some rows first to get page 2 or 3. You are charged only for the rows returned.
- **One row per key**: list **Dedupe columns** (for example `email`) and only the first row of each value stays after sorting. Sort the newest date first and you keep the latest row per email; sort the lowest price first and you keep the cheapest offer per product.
- **Two kinds of input**: Apify datasets (resource picker, read permission only) and public CSV / TSV / JSON / NDJSON file URLs, mixed freely. Encoding (UTF-8, Shift JIS, Windows-1252) and delimiter (comma, semicolon, tab, pipe) are detected.
- **Nested fields**: sort by a nested value with dots, for example `owner.name`.
- **CSV copy**: turn on **Also save a CSV file** to get the sorted rows as one file in the key-value store (record `sorted.csv`, UTF-8 with BOM so Excel opens it correctly).

### Input example

```json
{
  "fileUrls": ["https://dummyjson.com/products?limit=100&select=title,category,price,rating"],
  "sortKeys": [{"field": "price", "direction": "desc", "type": "number"}],
  "limit": 10
}
```

A dataset sorted by country and then by newest date, one row per email:
`{"datasetIds": ["<id>"], "sortKeys": ["country", {"field": "date", "direction": "desc"}], "dedupeFields": ["email"]}`.
Short form: a minus in front of a name means descending, so `"sortKeys": ["country", "-price"]` works too.

### Output

- **Dataset**: the sorted rows. Download as CSV, JSON, Excel and more from the Console.
- **`sorted.csv`** (key-value store, only with **Also save a CSV file**).
- **STATS** record (key-value store): `inputRows`, `outputRows`, `chargedRows`, `duplicatesRemoved`, rows read per source in `sources`, and per sort key the type that was used, how many values were empty and how many could not be read as that type.

### Rules worth knowing

- **The order of operations**: sort, then remove duplicates, then skip (**Skip the first rows**), then keep the first N (**Top N rows**).
- **Values keep their type in the output.** A CSV file has no types, so its values stay text exactly as written (`1,200` stays `1,200`) while still being sorted as numbers.
- **Plain text order** compares characters one by one (`item 10` before `item 2`; capitals before lower case when **Ignore case** is off). Accented letters are placed by their character code, not by the dictionary order of any one language.
- **Dates without a time zone** are treated as UTC. Dates with an offset are converted to UTC before comparing.
- **A wrong column name** does not stop the run: nothing can be compared, so the rows stay in their original order, and the run summary and the log tell you that no row has that column. Names are case-sensitive.
- **Values that cannot be read as the type you chose** (for example `n/a` in a number column) are treated as empty and counted in the run summary.
- **Dedupe** compares the same way as the sort: with **Ignore case** on, `A@x.com` and `a@x.com` are the same, `1` and `1.0` are the same number, and two empty values are equal.

### Limits (cannot be raised by input)

- **Up to 1,000,000 rows per run.** A sort needs every row, so all rows are held in memory. If there are more rows than **Max input rows**, the run stops without sorting or charging rather than sorting a partial read, which would give a wrong order.
- **Memory**: a run of 1,000,000 small rows (a few short columns) peaks at roughly 1 GB; wide rows or long text need more, and **Also save a CSV file** adds the size of the output. Set the run memory to 4,096 MB or more for the biggest runs (Run options, Memory). Small sorts of a few thousand rows need nothing special. If memory runs out, the run fails without charging.
- 20 datasets and files per run; 100 MB per file (a JSON array: 50 MB, because it has to be read whole; use NDJSON, one object per line, for bigger files); 10 sort keys.
- Source URLs must be public `http` or `https` links. Addresses on internal networks (localhost, private ranges, cloud metadata) are blocked, also after redirects. Excel files are not read (save them as CSV first).

### Pricing

Pay per event: **$0.20 per 1,000 output rows** (event `row`, $0.0002 per output row). Reading input rows is free. Nothing is charged when the run fails or produces no rows. Set a maximum charge per run: the Actor then writes only the first rows of the sorted result that fit the budget (never past it) and says so in the run summary. If the budget is lower than the price of one row, the run stops at once without charging.
On the Apify Free plan, the $5 of monthly platform credit covers about **25,000 rows** a month.

### Use cases

- Rank scraped products, listings or jobs by price, rating or date, and keep the top 10 or 100
- Order a CSV export by several columns before it goes to a report, a mail merge or an import
- Put numbered names in human order (`Chapter 2` before `Chapter 10`, `IMG_9` before `IMG_10`)
- Keep the newest or cheapest row per customer, product or URL
- Prepare a clean, ordered file for the next Actor in a workflow

### FAQ

**Does it change my source dataset?** No. It only reads it and writes a new dataset.
**Does it change my values?** No. Rows are returned as they were, in a new order.
**Why did `10` come before `9`?** The column was sorted as text. Set the type to `number`, or make sure every value in the column is a number (one `n/a` makes `auto` choose text).
**How do I sort Z to A?** Set `"direction": "desc"` on the key, or put a minus in front of the name: `"-name"`.
**Where do empty values go?** To the end by default; choose the start with **Empty values**.
**Can I sort a file that is bigger than 1,000,000 rows?** Not in one run. Split it first (for example by a column value), or sort each part and combine the results.

If this Actor saved you time, a rating on the Store helps others find it.

### More tools from the same developer

- [Filter CSV, JSON or Dataset Rows by Condition](https://apify.com/ucchiii/filter-rows) — keep only the rows of a CSV, JSON file or dataset that match simple conditions like country = US or price > 100
- [Remove Duplicates](https://apify.com/ucchiii/dataset-dedup-merge) — merge Apify datasets and remove duplicates by the fields you choose
- [Dataset Splitter](https://apify.com/ucchiii/dataset-splitter) — split a dataset or CSV/JSON file into parts by rows, parts, column value or size, or take a random sample
- [CSV to Excel Converter](https://apify.com/ucchiii/csv-xlsx-converter) — convert CSV, TSV, Excel XLSX, JSON and NDJSON files or Apify datasets into each other
- [Dataset Transform](https://apify.com/ucchiii/dataset-transform) — flatten, filter, rename and convert any Apify dataset, export CSV / JSON / JSONL with a link

# Actor input Schema

## `datasetIds` (type: `array`):

Datasets to sort (the 'defaultDatasetId' of a finished run). You can paste a dataset URL from Apify Console too. Several datasets and files are read in the order given and sorted together as one table. Up to 20 in total. Leave this and 'File URLs' empty to run a free demo on a built-in sample (not charged).

## `fileUrls` (type: `array`):

Public http(s) links to CSV, TSV, JSON or NDJSON files (up to 100 MB each; a JSON array up to 50 MB, use NDJSON for bigger files). The encoding (UTF-8, Shift JIS, Windows-1252) and the delimiter are detected. Links to internal networks are blocked.

## `sortKeys` (type: `array`):

The columns to sort by, most important first. Each entry is a column name, or an object with 'field' and any of: 'direction' ('asc' or 'desc'), 'type' ('auto', 'number', 'text', 'date'), 'ignoreCase' (true/false), 'natural' (true/false), 'nulls' ('first' or 'last'). Example: \["country", {"field": "price", "direction": "desc", "type": "number"}]. A name with a leading minus sorts descending ("-price"). Nested fields use dots (owner.name). Options you leave out take the defaults below. Required unless you run the demo.

## `direction` (type: `string`):

Direction for every sort key that does not set its own. Default: ascending.

## `valueType` (type: `string`):

How the values of a column are compared. 'auto' looks at the whole column: all numbers (also '1,200', '$5', '12%') = number; all dates (2026-03-04, 2026-03-04T10:00:00Z, 4 Mar 2026) = date; anything else = text. Set it yourself when a column mixes kinds, for example ZIP codes that should stay text. Values that cannot be read as the chosen type are treated as empty. Default: auto.

## `ignoreCase` (type: `boolean`):

Text sort: 'apple' and 'Banana' are compared without regard to case. Turn off for a strict character order where all capitals come before all lower-case letters. Default: on.

## `naturalSort` (type: `boolean`):

Text sort: digits inside text are compared as numbers, so 'item 2' comes before 'item 10' and 'v1.9' before 'v1.10'. Off = plain character order ('item 10' before 'item 2'). Default: off.

## `nulls` (type: `string`):

Where rows with an empty value (missing, null, blank or not readable as the chosen type) go. This is independent of the direction: 'at the end' means the end of the result even when sorting descending. Default: at the end.

## `dateOrder` (type: `string`):

Dates written with slashes are ambiguous, so they are only read when you say which order you use. Dates like 2026-03-04, 2026/03/04, 04.03.2026 and 4 Mar 2026 are always understood. Default: not read.

## `dedupeFields` (type: `array`):

Column names. After sorting, a row whose values in these columns equal those of an earlier row is dropped, so one row per combination stays: the first in the sorted order. Sort so the row you want comes first (newest date first, lowest price first) and list the columns that identify a group, for example 'email'. Compared the way they are sorted: with 'Ignore case' on, 'A' and 'a' are the same; 1 and 1.0 are the same number; two empty values are equal. Empty list = keep every row.

## `offset` (type: `integer`):

Number of rows to leave out from the start of the sorted (and deduplicated) result. Use it with 'Top N rows' to get page 2, 3 ... Default: 0.

## `limit` (type: `integer`):

Return only this many rows from the sorted result, for example 10 for the ten highest prices. 0 = all rows. You are charged only for the rows returned. Default: 0 (all).

## `outputCsv` (type: `boolean`):

Besides the dataset, save the sorted rows as one CSV file in the key-value store (record 'sorted.csv', UTF-8 with BOM so Excel opens it correctly). The file is built in memory, so it adds to the memory use of big runs. Nested values are written as JSON text. Default: off.

## `maxInputRows` (type: `integer`):

Safety limit on the rows read across all sources. A sort needs every row, so if there are more rows than this the run stops without sorting or charging (it never sorts a partial read). Maximum and default: 1,000,000.

## Actor input object example

```json
{
  "fileUrls": [
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
  ],
  "sortKeys": [
    {
      "field": "species",
      "direction": "asc",
      "type": "text"
    },
    {
      "field": "petal_length",
      "direction": "desc",
      "type": "number"
    }
  ],
  "direction": "asc",
  "valueType": "auto",
  "ignoreCase": true,
  "naturalSort": false,
  "nulls": "last",
  "dateOrder": "auto",
  "offset": 0,
  "limit": 0,
  "outputCsv": false,
  "maxInputRows": 1000000
}
```

# Actor output Schema

## `results` (type: `string`):

The rows in sorted order, unchanged. Download as CSV, JSON, Excel and more.

## `csv` (type: `string`):

The sorted rows as one CSV file (UTF-8 with BOM, opens correctly in Excel). Only exists when 'Also save a CSV file' is on.

## `stats` (type: `string`):

Record STATS: rows read per source, rows written and charged, duplicates removed, and per sort key the type used and how many values were empty or could not be read.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "fileUrls": [
        "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
    ],
    "sortKeys": [
        {
            "field": "species",
            "direction": "asc",
            "type": "text"
        },
        {
            "field": "petal_length",
            "direction": "desc",
            "type": "number"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("ucchiii/dataset-sort").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "fileUrls": ["https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"],
    "sortKeys": [
        {
            "field": "species",
            "direction": "asc",
            "type": "text",
        },
        {
            "field": "petal_length",
            "direction": "desc",
            "type": "number",
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("ucchiii/dataset-sort").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "fileUrls": [
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
  ],
  "sortKeys": [
    {
      "field": "species",
      "direction": "asc",
      "type": "text"
    },
    {
      "field": "petal_length",
      "direction": "desc",
      "type": "number"
    }
  ]
}' |
apify call ucchiii/dataset-sort --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,ucchiii/dataset-sort"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/661qvXE6GenjmpxTR/builds/GwvwzOvBQa4PWMgEm/openapi.json
