Skip to main content
v2026.11,986 entries · CC-BY 4.0

samtools idxstats: Syntax, Output Columns, and Metrics

samtools idxstats extracts chromosome lengths, mapped read counts, and unmapped reads from indexed BAM and CRAM files for rapid genomic quality control.

Written and maintained by CASRAI Editorial Board

Published

On this page

samtools idxstats is a specialized utility in the SAMtools suite that retrieves alignment summary statistics directly from the index file (such as a .bai or .csi file) of a coordinate-sorted BAM, CRAM, or SAM file. By extracting pre-computed index bin counts rather than reading through multi-gigabyte sequence records, samtools idxstats executes almost instantaneously, outputting a four-column tab-delimited table detailing reference sequence names, sequence lengths, mapped read-segment counts, and unmapped read-segment counts for each chromosome or contig. Bioinformaticians rely on this command as an essential quality-control checkpoint to verify chromosome-level read distributions, validate sex chromosome ratios, detect foreign DNA contamination, and confirm library balance across sequencing cohorts prior to running downstream variant calling or expression analysis.

What samtools idxstats is used for in research

High-throughput sequencing workflows generate millions of reads aligned to reference assemblies. Once short or long reads are aligned using tools like Bowtie 2 or BWA-MEM, researchers must confirm that alignments match expected biological parameters before investing compute time in variant calling or transcript quantification. Sequence alignments are stored in compressed formats described in our guide to BAM files and evaluated across formats in our comparison of SAM, BAM, and CRAM. Because complete alignment files routinely exceed tens of gigabytes, streaming through every record to check mapping distributions creates unnecessary computational bottlenecks.

This is where samtools idxstats provides immediate utility. When an alignment file is coordinate-sorted and indexed, as detailed in our guide on BAM index (.bai) files, the index stores metadata summarizing virtual file offsets and record counts for each contig. samtools idxstats queries this compact index structure in milliseconds. In research laboratories and sequencing core facilities, investigators use samtools idxstats for several primary tasks:

  • Sequencing Quality Control: Providing an immediate check to ensure alignments completed properly and reads distributed across expected chromosomes rather than falling into unmapped bins.
  • Sex Determination and Chromosomal Dosage: In mammalian genomics, calculating read count ratios between chromosome X, chromosome Y, and autosomes enables researchers to verify sample sex, detect sample swaps in cohort studies, and flag chromosomal aneuploidies.
  • Contamination and Organellar Screening: Evaluating read counts aligned to mitochondrial DNA (chrM/MT), chloroplast genomes, or spike-in controls (such as PhiX174) quantifies cytoplasmic carryover, library preparation efficiency, and sample purity.
  • Targeted Capture Verification: In exome or targeted panel sequencing, comparing on-target chromosome counts against off-target regions provides fast feedback on hybridization capture efficiency.
  • Automated Pipeline Reporting: Workflow engines like Nextflow and Snakemake run samtools idxstats immediately after alignment, feeding per-chromosome statistics into MultiQC reports without file I/O overhead.

How to install or access samtools idxstats

samtools idxstats is included within the core SAMtools package, developed and maintained by the HTSlib team and Genome Research Limited. Users do not need an independent binary. SAMtools can be installed across Unix-like systems through official channels:

Package Managers (Bioconda and Conda)

In academic bioinformatics, Bioconda is the standard distribution channel. To install SAMtools into an existing conda environment, execute:

conda install -c bioconda -c conda-forge samtools

To create an isolated environment with SAMtools installed, run:

conda create -n bioinfo -c bioconda -c conda-forge samtools
conda activate bioinfo

System Repositories (Debian and Ubuntu)

On Debian, Ubuntu, and related Linux distributions, pre-compiled binaries are available through APT:

sudo apt update
sudo apt install samtools

On Red Hat Enterprise Linux, CentOS, or Rocky Linux, packages are available via EPEL or Fedora repositories using dnf:

sudo dnf install samtools

Compiling from Official Source

For high-performance computing clusters requiring custom compiler optimizations, download the official release tarball from HTSlib and build locally:

wget https://github.com/samtools/samtools/releases/download/1.21/samtools-1.21.tar.bz2
tar -xjf samtools-1.21.tar.bz2
cd samtools-1.21
./configure --prefix=/usr/local
make
sudo make install

Prerequisite development libraries include libncurses5-dev, zlib1g-dev, libbz2-dev, and liblzma-dev.

Container Environments

For containerized workflows, verified Docker and Singularity images are hosted on BioContainers. Run SAMtools via Docker with:

docker run --rm -v $(pwd):/data quay.io/biocontainers/samtools:1.21--h50ea8bc_0 samtools --version

How to run samtools idxstats step by step

Running samtools idxstats requires coordinate-sorted and indexed alignments. Follow these five steps to prepare files, execute the command, and process results:

  1. Check Alignment Sort Order:
    Verify that the alignment file is coordinate-sorted by inspecting the header: samtools view -H input.bam | grep '@HD'. The header must display SO:coordinate. If the file is queryname-sorted (SO:queryname) or unsorted, index generation will fail.
  2. Coordinate-Sort the Alignment:
    If the alignment is not yet sorted by coordinate, sort it using multi-threaded compression:

    samtools sort -@ 4 -o sample.sorted.bam sample.bam

    This organizes records into ascending genomic coordinate order according to the sequence dictionary.

  3. Generate the Index File:
    Build the linear coordinate index using samtools index:

    samtools index -@ 2 sample.sorted.bam

    This produces a standard index file named sample.sorted.bam.bai. For genomes containing individual scaffolds longer than 512 megabases (536,870,912 bp), standard BAI bins overflow. In such cases, generate a Coordinate-Sorted Index (CSI) by adding the -c flag:

    samtools index -c -m 14 sample.sorted.bam
  4. Execute samtools idxstats:
    Run samtools idxstats against the indexed BAM file, redirecting output to a tab-delimited text file:

    samtools idxstats sample.sorted.bam > sample.idxstats.tsv

    If the index is located in a separate directory or has a non-default name, specify both paths using the -X option:

    samtools idxstats -X /alignments/sample.sorted.bam /indices/sample.sorted.bam.bai > sample.idxstats.tsv
  5. Filter and Analyze Output Metrics:
    Process the resulting table using standard Unix utilities. To view contigs ordered by mapped read counts in descending order, run:

    sort -k3,3nr sample.idxstats.tsv | head -n 10

    To calculate total mapped read-segments across all reference contigs (excluding unmapped reads), use awk:

    awk '$1 != "*" {mapped += $3} END {print "Total Mapped Segments: " mapped}' sample.idxstats.tsv

    To calculate the proportion of reads mapped to mitochondrial DNA, execute:

    awk '{total += $3 + $4; if ($1 == "chrM" || $1 == "MT") m = $3} END {printf "Mitochondrial Rate: %.4f%%
    ", (m/total)*100}' sample.idxstats.tsv

How to read the output

The output of samtools idxstats is printed to standard output as a four-column tab-delimited table. Each line corresponds to an individual reference contig present in the alignment header, concluding with a final summary row representing unplaced reads:

Column Number Field Name Data Type Description and Interpretation
1 Reference Sequence Name String Identifier of the reference contig (e.g., chr1, chrX, NC_000001.11, or *) matching the @SQ SN: header tag.
2 Sequence Length Integer Length of the reference contig in base pairs, taken from the @SQ LN: header tag (0 for the unmapped * row).
3 Mapped Read-Segments Integer Number of aligned read-segments mapped to this reference sequence.
4 Unmapped Read-Segments Integer Number of unmapped read-segments whose mate mapped to this sequence, or total unplaced reads on the * row.

Below is a representative sample excerpt from a paired-end human sequencing dataset mapped against GRCh38:

chr1    248956422       18420194        14205
chr2    242193529       17904312        13891
chrX    156040895       11420801        9102
chrY    57227415        142011          1540
chrM    16569           854201          212
*       0               0               482910

Read-Segments Versus Physical DNA Fragments

A vital distinction when interpreting Column 3 is that SAMtools counts read-segments rather than physical library fragments. In paired-end sequencing, each DNA fragment yields two reads (Read 1 and Read 2). When both reads map to chr1, Column 3 increments by 2, not 1. Furthermore, if secondary alignments (multi-mapping reads) or supplementary alignments (chimeric reads) are recorded in the index, each alignment record is counted. Consequently, the sum of Column 3 across all contigs can exceed the number of physical sequenced fragments. When converting alignments back to raw sequences, consult our guide on converting BAM to FASTQ to ensure read pairing integrity.

Interpreting Column 4: Unmapped Read-Segments per Contig

Researchers often wonder why specific chromosomes report unmapped read counts in Column 4. Under the SAM specification, when one read of a pair maps to a chromosome (such as chr1) but its mate fails to map, the aligner marks the mate as unmapped (FLAG bit 0x4) but records the mate’s reference name (RNAME) and coordinate (POS) matching the mapped partner. The index records these unmapped mates under that chromosome’s coordinate bin. Column 4 therefore quantifies unmapped read-segments whose mates mapped to that specific chromosome.

The Asterisk (*) Summary Row

The terminating line with an asterisk (*) represents completely unplaced reads. These are records where neither the read nor its mate mapped to any reference contig, or records without assigned coordinates (RNAME *, POS 0). For this line, Column 2 and Column 3 are always 0, and Column 4 reports the global count of completely unplaced reads. For deeper analysis of bitwise alignment states, see our practical guide on decoding SAM/BAM FLAG values.

Troubleshooting samtools idxstats

When incorporating samtools idxstats into bioinformatics pipelines, common errors typically involve index availability, sort order, or coordinate ranges:

Missing Index File

Symptom: The command fails with [E::hts_idx_load3] Could not load index file for 'sample.bam'.

Cause: SAMtools expects sample.bam.bai or sample.bam.csi in the same folder. If the index was omitted or renamed, the tool cannot locate it.

Resolution: Generate the index using samtools index sample.bam. If stored elsewhere, specify the index explicitly using the -X parameter: samtools idxstats -X /data/sample.bam /indices/sample.bam.bai.

Unsorted or Name-Sorted BAM Input

Symptom: The command prints a warning that the file is not coordinate-sorted, or it executes very slowly while scanning the full file.

Cause: On unindexed or name-sorted files, samtools idxstats falls back to a linear full-file scan. While it eventually prints correct counts, execution time increases from seconds to minutes.

Resolution: Sort the file by coordinate using samtools sort -@ 4 -o sample.sorted.bam sample.bam, index it with samtools index sample.sorted.bam, and re-run idxstats.

Index File Older Than Alignment File

Symptom: Terminal logs report [W::hts_idx_load3] the index file is older than the data file.

Cause: The modification timestamp on the .bai file is older than the BAM file timestamp. This occurs when BAM files are touched or moved after indexing.

Resolution: If the BAM contents did not change, synchronize timestamps using touch sample.bam.bai. If the BAM was modified, re-index with samtools index -f sample.bam.

Coordinate Overflow on Large Contigs

Symptom: samtools index fails with an error indicating a sequence coordinate exceeds the maximum limit for BAI format (512 Mbp).

Cause: Standard BAI format uses a hierarchical binning scheme capped at 536.87 Mbp (229 – 1 bp). Large plant or amphibian chromosomes exceed this limit.

Resolution: Build a Coordinate-Sorted Index (CSI) using samtools index -c -m 14 sample.bam. samtools idxstats reads CSI indices transparently.

Discrepancy with samtools flagstat Counts

Symptom: Summing Column 3 in idxstats does not equal the mapped read tally reported by samtools flagstat.

Cause: idxstats counts all alignment entries in the index, including secondary and supplementary alignments. samtools flagstat differentiates primary from secondary alignments.

Resolution: To count primary alignments only, filter alignments prior to inspection using samtools view -b -F 0x904 sample.bam | samtools idxstats -.

Free alternatives to samtools idxstats

While samtools idxstats is the standard for rapid index-based chromosome statistics, several open-source tools provide alternative or expanded alignment summaries:

Tool Name Developer / Project Requires Index Execution Speed Primary Focus Output Scope
samtools idxstats HTSlib / Samtools Team Yes (.bai / .csi) Near-instantaneous (O(1)) Per-contig mapped and unmapped read-segment counts Contig summary table
samtools flagstat HTSlib / Samtools Team No Moderate (stream scan) Bitwise flag proportions (duplicates, proper pairs) Library summary report
samtools coverage HTSlib / Samtools Team Yes (.bai / .csi) Moderate (indexed scan) Breadth of coverage, mean depth, base and map qualities Contig depth table
samtools stats HTSlib / Samtools Team No Thorough (record scan) Insert size distributions, error rates, GC profiles Multi-section report
bamtools stats Barnett et al. (Marth Lab) No Moderate (stream scan) General alignment tallies, single/paired read metrics Terminal text output
Picard CollectAlignmentSummaryMetrics Broad Institute Yes (.bai) Moderate (Java JVM) Read-group metrics, mismatch rates, adapter content Tabular metric file
Mosdepth Brent Pedersen / Quinlan Lab Yes (.bai / .csi) Fast (parallel C/Nim) Base-level depth, windowed coverage distributions BED and summary files

The data table below compares alignment inspection and metrics utilities across the HTSlib software suite. Choose the tool that matches your analytical scope: use samtools idxstats for instantaneous chromosome-level QC and sex validation; use samtools flagstat to monitor library-level duplicate and mapping percentages; and use samtools coverage or Mosdepth when evaluating base-pair depth and physical coverage breadth.

Frequently asked questions

How is samtools idxstats different from samtools flagstat or samtools stats?

samtools idxstats queries pre-computed index files directly without reading individual sequence records, producing an instant per-chromosome breakdown of mapped and unmapped reads. In contrast, samtools flagstat performs a full linear stream scan to calculate library-wide flag proportions, such as duplicate rates and proper pair percentages. samtools stats carries out an exhaustive record-by-record analysis to compute insert size distributions, cycle-by-cycle error rates, and GC content, requiring substantially more compute time.

Why does samtools idxstats count reads multiple times?

samtools idxstats tallies alignment records (read-segments) rather than physical DNA fragments. In paired-end sequencing, both reads of a mapped pair are counted individually, incrementing the mapped count by two. In addition, when aligners output secondary alignments for multi-mapping reads or supplementary alignments for split reads, each alignment record indexed in the BAM file contributes to its contig count.

What does the asterisk row mean in samtools idxstats output?

The asterisk (*) row at the bottom of the samtools idxstats output represents completely unplaced and unmapped reads. These records correspond to reads where neither the read nor its mate mapped to any reference contig, or records without assigned coordinates. For this row, sequence length (Column 2) and mapped count (Column 3) are 0, while Column 4 reports the total count of unplaced reads.

Can samtools idxstats run on a name-sorted BAM file?

samtools idxstats cannot perform instant index lookups on a name-sorted BAM file because linear index files require coordinate sorting. While samtools idxstats will attempt to process an unindexed or name-sorted file by scanning every record linearly, this fallback is much slower and eliminates the primary advantage of the command. Alignment files should always be coordinate-sorted with samtools sort and indexed with samtools index first.

What are unmapped read-segments in column 4 of samtools idxstats?

Unmapped read-segments in Column 4 of a chromosome row represent reads that failed to align, but whose paired mate aligned successfully to that chromosome. Under the SAM specification, an unmapped read with a mapped mate is assigned the reference name and coordinate position of its mapped partner. Consequently, the index records these unmapped mates under that chromosome’s bin, allowing researchers to evaluate discordant read pairs directly.

Sources

Data: HTSlib Alignment Inspection and Metrics Utility Matrix

A comparative technical matrix evaluating sequence alignment inspection and summary tools within the HTSlib samtools software ecosystem, detailing required index structures, computational complexity, stream compatibility, and output metric resolution across genomic analysis pipelines.

Period covered: 2026. Coverage: Global.

HTSlib Alignment Inspection and Metrics Utility Matrix
Tool UtilityPrimary Metrics ReportedRequires Coordinate Index (Boolean)Computational ComplexityOutput GranularityStream Piped Input (Boolean)
samtools idxstatsPer-contig mapped and unmapped read-segment counts and reference lengths1O(1) index parsePer-chromosome tabular breakdown
samtools flagstatTotal reads, secondary alignments, supplementary, duplicates, and paired read flagsO(N) single-pass scanWhole-file library flag summary1
samtools statsExhaustive metrics including insert size distribution, mismatch rates, GC content, and read lengthsO(N) deep record scanMulti-section detailed report1
samtools coveragePer-chromosome coverage percentage, mean depth, base quality, and mapping quality1O(N) indexed scanPer-chromosome tabular metrics
samtools depthSingle-base position depth across specified genomic coordinates1O(N) coordinate streamPer-base coordinate positions1
samtools bedcovTotal read count and base count overlapping specified BED intervals1O(N) regional index lookupPer-interval summary counts

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about samtools idxstats: Syntax, Output Columns, and Metrics

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →