What does the CSV Column Sorter do?
The CSV Column Sorter sorts delimited tabular CSV data and spreadsheets by any chosen column in ascending or descending order. It supports automatic data type inference for numeric values, alphabetical strings, and ISO dates, while preserving header rows and RFC 4180 quotation escaping.
Core Concepts
- Multi-Type Sorting: Differentiates between alphanumeric sorting (
1, 2, 10) and lexical sorting (1, 10, 2). - RFC 4180 Quoting: Properly handles multiline records, embedded commas, and escaped double quotes (
""). - Header Isolation: Ensures the header row stays pinned at line 1 while reordering all subsequent records.
How to use the tool?
- Input CSV Data: Paste raw CSV rows into the input textarea or click Load Sample.
- Select Column: Choose the column index or name from the dropdown.
- Configure Options:
- Direction: Toggle between Ascending (
A → Z,0 → 9) and Descending (Z → A,9 → 0). - Data Type: Select Auto-Detect, Numeric, Alphabetical, or Date.
- Header Toggle: Check if row 1 contains column names.
- Direction: Toggle between Ascending (
- Sort & Export: Click Sort CSV Data to view results, then click Copy or Download.
Related Developer Utilities
- CSV to JSON Converter: Convert tabular CSV records into structured JSON documents.
- CSV Formatter & Beautifier: Align and format CSV columns into readable ASCII tables.
- JSON to CSV Converter: Export nested JSON objects into CSV format.
REST API Integration
blueutils.com provides a free REST API endpoint (POST https://blueutils.com/api/csv/csv-column-sorter) for programmatic integration.
API Request Parameters
| Name | Type | Description | Example |
|---|---|---|---|
payload |
String or Array | The raw CSV text payload OR a native JavaScript array-of-arrays to sort. Aliases: rawText, text, input, csv. |
"id,name\n2,Bob\n1,Alice" |
options |
Object | Optional sorting configurations. | { "columnIndex": 0, "direction": "asc" } |
options.columnIndex |
Number | Zero-based index of the target column to sort. | 0 |
options.direction |
String | Sort direction: "asc" or "desc". |
"asc" |
options.sortType |
String | Data type: "auto", "numeric", "text", "date". |
"auto" |
options.hasHeader |
Boolean | Whether the first row represents headers. | true |
API Request Payload Examples
cURL (String Payload)
curl -X POST https://blueutils.com/api/csv/csv-column-sorter \
-H "Content-Type: application/json" \
-d '{
"payload": "id,name,salary\n102,Bob,72000\n101,Alice,95000",
"options": {
"columnIndex": 0,
"direction": "asc",
"sortType": "numeric",
"hasHeader": true
}
}'Python (Array Payload)
import requests
url = "https://blueutils.com/api/csv/csv-column-sorter"
payload = {
"payload": [["id", "name", "salary"], ["102", "Bob", "72000"], ["101", "Alice", "95000"]],
"options": {
"columnIndex": 0,
"direction": "asc",
"sortType": "numeric"
}
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
String jsonPayload = "{\"payload\": \"id,name\\n2,Bob\\n1,Alice\", \"options\": {\"columnIndex\": 0, \"direction\": \"asc\"}}";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://blueutils.com/api/csv/csv-column-sorter"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}API Response Parameters
| Name | Type | Description | Example |
|---|---|---|---|
isValid |
Boolean | Indicates whether the sorting succeeded. | true |
result |
String | Sorted CSV text output. | "id,name\n1,Alice\n2,Bob" |
data |
Array | Native array-of-arrays representation of the sorted CSV. | [["id", "name"], ["1", "Alice"], ["2", "Bob"]] |
originalSize |
Number | Byte size of the original unformatted data. | 37 |
resultSize |
Number | Byte size of the formatted string output. | 27 |
rowCount |
Number | Number of sorted data rows. | 2 |
sortedColumnName |
String | Name or index of sorted column. | "id" |
API Response Payload Examples
Success Response (HTTP 200 OK)
{
"isValid": true,
"result": "id,name,salary\n101,Alice,95000\n102,Bob,72000",
"data": [
["id", "name", "salary"],
["101", "Alice", "95000"],
["102", "Bob", "72000"]
],
"originalSize": 46,
"resultSize": 46,
"headers": ["id", "name", "salary"],
"sortedColumnIndex": 0,
"sortedColumnName": "id",
"rowCount": 2,
"columnCount": 3,
"direction": "asc",
"sortType": "numeric"
}Error Response (HTTP 400 Bad Request)
{
"isValid": false,
"error": "CSV input cannot be empty."
}Rate Limit Exceeded Response (HTTP 429 Too Many Requests)
{
"error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}Why use an API to sort CSV columns?
Integrating the CSV Column Sorter API into CI/CD pipelines, automated extract-transform-load (ETL) scripts, or autonomous agent workflows provides several practical advantages:
- Rapid Script Validation: Enables developers and data engineers to quickly test and programmatically verify sorting and data normalization across multiple environments.
- Optimized Token Efficiency for AI Agents: Offloading parsing, numeric conversions, and deterministic table sorting to an external API significantly cuts prompt and completion token consumption for autonomous agents.
- Deterministic Accuracy Without Hallucinations: Language models can occasionally miscalculate or hallucinate sorted ordering in large CSV files. Delegating processing to a deterministic API guarantees 100% computational accuracy every time without token overhead.
Native Usage
How to achieve the same task locally without external dependencies using native operating system utilities and scripting languages:
Windows (CMD / PowerShell)
Using native PowerShell Import-Csv and Sort-Object:
# Sort CSV by numeric salary column in descending order
Import-Csv -Path "input.csv" | Sort-Object -Property @{Expression={[int]$_.salary}; Descending=$true} | Export-Csv -Path "output.csv" -NoTypeInformationLinux / Unix (Bash / Shell)
Using standard Linux sort and head (preserving header on line 1):
# Sort CSV by 4th column numerically in descending order
(head -n 1 input.csv && tail -n +2 input.csv | sort -t',' -k4,4nr) > output.csvPython
Using the Python standard library csv module:
import csv
with open("input.csv", mode="r", encoding="utf-8") as infile:
reader = csv.reader(infile)
header = next(reader)
# Sort data rows by column index 3 (salary) numerically descending
sorted_rows = sorted(reader, key=lambda row: float(row[3]), reverse=True)
with open("output.csv", mode="w", newline="", encoding="utf-8") as outfile:
writer = csv.writer(outfile)
writer.writerow(header)
writer.writerows(sorted_rows)
print("CSV sorted successfully.")Java
Using standard Java java.nio.file.Files and a custom comparator:
import java.nio.file.*;
import java.util.*;
public class SortCsvExample {
public static void main(String[] args) throws Exception {
List<String> lines = Files.readAllLines(Paths.get("input.csv"));
if (lines.isEmpty()) return;
String header = lines.get(0);
List<String> dataRows = new ArrayList<>(lines.subList(1, lines.size()));
// Sort rows by 1st column (index 0) numerically ascending
dataRows.sort(Comparator.comparingDouble(row -> Double.parseDouble(row.split(",")[0].trim())));
List<String> result = new ArrayList<>();
result.add(header);
result.addAll(dataRows);
Files.write(Paths.get("output.csv"), result);
System.out.println("CSV sorted successfully.");
}
}