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

Converting BAM to FASTQ: Preserving Read Pairing with samtools and Picard

A practical guide to converting BAM back to FASTQ with samtools fastq and Picard SamToFastq, covering when the conversion is actually needed, the name-sort/collate step that prevents mismatched read pairs, and how to verify paired output afterward.

Written and maintained by CASRAI Editorial Board

Last updated

A BAM file stores aligned sequencing reads, but every read started life as a plain FASTQ record before an aligner ever touched it. Converting a BAM back to FASTQ throws away the alignment and reconstructs those original read sequences and quality strings. The mechanics of samtools fastq and Picard’s SamToFastq are documented separately in each tool’s own docs, but neither one leads with the gotcha that trips up almost every first attempt: pull FASTQ straight out of a coordinate-sorted BAM without collating it by read name first, and the paired-end output can look complete — every read is there, every quality string is real — while the two mate files no longer correspond to each other read for read.

This guide covers when converting BAM back to FASTQ is actually the right move, the exact commands for both tools, why sort order determines whether paired output is trustworthy, and how to verify the result before it goes anywhere near a re-alignment job.

When you actually need to convert BAM back to FASTQ

Raw FASTQ is usually the thing labs are least careful about retaining — it is large, it is “just the input,” and storage budgets get trimmed there first once a BAM exists. That habit is fine until one of a handful of situations forces the conversion back:

  • Re-aligning to a different or updated reference. Moving a legacy dataset from an old BAM built against an older genome build to a current one (for example GRCh37 to GRCh38, or adding a new decoy/masked reference) requires realignment from raw reads — an existing alignment cannot simply be re-projected onto a different reference sequence.
  • Switching alignment or variant-calling pipelines. A new aligner, a different index, or a new pipeline validated on raw FASTQ input needs FASTQ, not another pipeline’s alignment decisions already baked into a BAM.
  • Recovering reads when only the BAM survived. Collaborators, core facilities and data repositories frequently hand over — or only retain — the aligned BAM, and the original FASTQ from the sequencer was never kept or was purged on a retention schedule. If the end goal is actually depositing reads somewhere, check the target repository’s requirements first: NCBI SRA accepts BAM directly for aligned data, so a FASTQ conversion may not even be necessary.
  • Re-running steps that belong upstream of the BAM you have. Adapter trimming, quality filtering, or UMI extraction that should have run before alignment but did not (or ran with settings that now need to change) needs the pre-alignment sequence back.

If none of those apply — if what is actually needed is just a look at the read sequences, not a full re-processing run — indexing and region-querying the BAM directly is usually faster than a full FASTQ export.

Why a coordinate-sorted BAM breaks a naive conversion

Every aligned BAM file stores, for each read, a FLAG field marking whether it is the first or second read of a pair. A naive conversion just walks the file in whatever order it is stored and writes each read to the file its FLAG says it belongs in — first-in-pair reads to one file, second-in-pair reads to another. That works cleanly as long as the BAM is still in the order the sequencer produced it, because mate 1 and mate 2 of the same pair sit next to each other and stream out to their respective files in matching order.

A coordinate-sorted BAM — the standard order after alignment and duplicate-marking, and the order required for indexing — destroys that adjacency. Sorting by leftmost mapping position scatters the two mates of a pair across the file according to where each one happened to align, not according to which pair they belong to: mate 1 might map early on chromosome 3 while mate 2 maps two megabases downstream, or on a different chromosome for a discordant pair. Pull FASTQ straight out of that order into separate -1/-2 files and each output file is individually well-formed, but the pairing between them is scrambled — read N of file 1 and read N of file 2 are, in general, unrelated pairs. Nothing in either file signals the error, since every record still parses, so it fails silently until an aligner produces a suspiciously bad alignment rate or, worse, quietly proceeds with mismatched mates.

samtools’ own documentation states this plainly: if paired reads are to be interleaved or written to separate files in matching order, “the input should be first collated by name.” That is the fix, and it is a mandatory step, not a tuning option.

Step 1: name-sort or collate the BAM before converting

Both tools rely on mates being adjacent again before extraction. The two ways to get there are not interchangeable in cost.

samtools sort -n

Fully sorts every record by query (read) name:

samtools sort -n -o name_sorted.bam in.bam

This is a genuine full sort — expensive on a large BAM, and it produces a BAM that is not useful for anything else afterward, since name order is not what any other downstream tool wants.

samtools collate

Groups reads so mates end up adjacent without fully sorting the whole file — cheaper, and the right default when the only reason to touch sort order is extracting FASTQ:

samtools collate -o collated.bam in.bam

Or skip writing the intermediate BAM to disk entirely and pipe it straight into samtools fastq:

samtools collate -u -O in.bam | samtools fastq -1 paired_1.fastq -2 paired_2.fastq -0 /dev/null -s /dev/null -n -

Converting with samtools fastq

Basic syntax (see the samtools fastq/fasta manual page for the complete option list):

samtools fastq [options] in.bam

The output-routing options do the real work:

Option What it writes
-1 FILE Reads flagged as read 1 of a pair (and not read 2)
-2 FILE Reads flagged as read 2 of a pair (and not read 1)
-0 FILE Reads with both or neither of the read1/read2 flags set
-s FILE Singletons — reads whose mate did not survive filtering
-o FILE Shorthand equivalent to -1 FILE -2 FILE
-n / -N Suppress (-n) or force (-N) a /1, /2 suffix on read names

A complete paired-end extraction from an already name-collated BAM, discarding singletons and anything without a mate:

samtools fastq -1 paired_1.fastq -2 paired_2.fastq -0 /dev/null -s /dev/null -n collated.bam

By default, samtools fastq filters out secondary and supplementary alignments (FLAG bits 0x100 and 0x800, combined filter 0x900) so a read that aligned to multiple places does not get written to the FASTQ more than once. -f, -F, and --rf let you set a different FLAG filter, but loosening it is rarely useful for a re-alignment workflow — it reintroduces exactly the duplicate-read problem the default filter exists to prevent.

Converting with Picard SamToFastq

Picard’s tool takes the same input and produces the same kind of output, with KEY=VALUE syntax instead of short options:

java -jar picard.jar SamToFastq 
    I=in.bam 
    FASTQ=paired_1.fastq 
    SECOND_END_FASTQ=paired_2.fastq 
    UNPAIRED_FASTQ=singletons.fastq

A few behaviors are worth knowing before relying on it:

  • It tolerates either sort order, but not equally well. Picard’s own documentation for SamToFastq notes that it works with both coordinate-sorted and name-sorted (or name-collated) input. From a name-sorted BAM, the FASTQ comes out in the same read order the sequencer originally produced. From a coordinate-sorted BAM, SamToFastq still matches mates correctly internally — it does not desync pairs the way a naive line-by-line write would — but read order comes out scrambled relative to the sequencer output, which the documentation flags as something that can affect non-deterministic mappers. Name-sorting or collating first is still the safer, more reproducible default.
  • RE_REVERSE (default true) restores original read orientation. A BAM always stores a read’s SEQ field in reference-forward orientation, so a read that aligned to the reverse strand is stored reverse-complemented relative to what the sequencer actually produced. With RE_REVERSE=true, SamToFastq reverse-complements those reads back before writing them to FASTQ, so the exported sequence matches the original sequencer read rather than the alignment orientation. samtools fastq performs the same reversal automatically; neither tool gives a normal reason to turn it off in a re-processing workflow.
  • INCLUDE_NON_PF_READS (default false) controls quality-failed reads. Reads the sequencer itself flagged as failing its own platform/vendor quality check are excluded from the FASTQ by default; set this to true only if a downstream step specifically needs them.

samtools fastq vs. Picard SamToFastq

  samtools fastq Picard SamToFastq
Speed on large BAMs Generally faster; native C implementation, streams well with collate Slower; JVM startup and per-read object overhead add up on whole-genome BAMs
Pairing safety on coordinate-sorted input Requires name-sort/collate first, or output pairing is wrong Matches mates correctly either way, but read order is only reproducible from name-sorted input
Typical pipeline fit Shell-scripted, Unix-pipeline-native workflows GATK-centric pipelines that already stage other Picard/GATK steps
Reverse-strand handling Automatic Automatic (RE_REVERSE=true by default)

Where these formats sit relative to each other and to CRAM is covered in more depth in SAM vs. BAM vs. CRAM.

Verifying the output is correctly paired

Do not treat a clean exit code as proof the conversion worked. Check the actual pairing before handing the FASTQ to an aligner:

  1. Compare read counts against the source BAM. Run samtools flagstat on the original BAM and note the “read1” and “read2” counts. The number of records in each output FASTQ — line count divided by 4 — should match the corresponding count exactly.
  2. Confirm the two files have identical read counts. A correctly paired export always produces the same number of reads in file 1 and file 2. A mismatch means something — usually a filtering flag or a missed collate step — dropped reads asymmetrically.
  3. Spot-check that read names line up. Pull every fourth line (the header line) from each file, strip any trailing /1 or /2, and diff the two name lists. They should be identical, position for position. Any mismatch confirms the desync described above, and the conversion needs to be redone from a properly collated BAM rather than patched after the fact.
  4. Re-align a subsample and check the properly-paired rate. The most direct end-to-end check: align a subset of the exported FASTQ pair back to the same reference and compare the “properly paired” percentage in samtools flagstat against what the original BAM reported. This is also a good moment to sanity-check coverage against the original alignment. A properly collated conversion reproduces roughly the same properly-paired rate; a desynced one collapses it, often dramatically, because the aligner is now trying to place unrelated reads as mates.

Common pitfalls

  • Skipping collation because the BAM “looks fine.” A coordinate-sorted BAM converts to FASTQ without a single error or warning even when the pairing comes out wrong — there is no failure signal to catch this after the fact except the checks above.
  • Loosening the default FLAG filter without a reason. Overriding samtools fastq‘s default 0x900 exclusion, or not filtering secondary/supplementary alignments in a custom script, writes a read to FASTQ once per alignment record instead of once per read, inflating downstream read counts.
  • Assuming FASTQ round-trips a BAM exactly. If the BAM already had adapter-trimmed or hard-clipped sequence data, the exported FASTQ reflects that modified sequence, not the sequencer’s raw output — a problem if the point of the exercise is re-running trimming from scratch.
  • Forgetting singleton handling. Without -s (samtools) or UNPAIRED_FASTQ (Picard), reads whose mate did not make it through a prior filtering step get folded into the paired output anyway, or dropped, depending on the tool and version — always route singletons explicitly and check whether that file has any content.

Frequently asked questions

Does converting BAM to FASTQ lose any information?

Yes, deliberately: alignment position, CIGAR string, mapping quality, and any BAM-specific tags are discarded. Only the read name, sequence, and quality string survive the conversion, along with which mate each read is — exactly what a re-alignment step needs and nothing more.

Can I convert directly from a CRAM file instead of BAM?

Yes — both samtools fastq and Picard’s tool accept CRAM input directly, as long as the reference FASTA the CRAM was compressed against is available and correctly referenced. The name-sort-or-collate requirement applies identically to CRAM.

Do I need to name-sort, or is collate enough?

samtools collate is enough, and is the better default for this specific job. It groups mates adjacent to each other without performing a full alphanumeric sort, which is faster and produces the same correctly-paired FASTQ output that a full sort -n would.

Why do my read names have a /1 or /2 suffix, and should I remove it?

Older FASTQ conventions appended /1 and /2 to mate read names to disambiguate them when both mates lived in a single interleaved file. Most current aligners expect bare, unsuffixed names and infer mate identity from which file (or which position in an interleaved file) a read appears in — use -n in samtools fastq to suppress the suffix unless a specific downstream tool documents that it needs it.

Will the re-exported FASTQ be identical to the original sequencer output?

Close, but not guaranteed byte-identical. Reverse-strand reads are correctly reverse-complemented back to sequencer orientation, but any trimming or sequence modification already applied before the BAM was created will carry through rather than being undone. For most re-alignment purposes this is not a problem — the sequence and quality data needed for realignment are intact and correctly paired.

Follow CASRAI

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

Ask CASRAI · included with Regulatory Radar

Ask about Converting BAM to FASTQ: Preserving Read Pairing with samtools and Picard

Ask CASRAI answers research-administration questions and cites the passages behind every claim — and says so when the corpus does not cover something, instead of guessing. It comes with a Regulatory Radar subscription at $29 a month, alongside the daily digest of regulatory changes and the dashboard of what changed.

150 questions a day, on this site, over the API, or inside your own tools through the CASRAI MCP server.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free 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 →

Regulatory Radar

Stop finding out after the fact

$29/month, cancel anytime. Daily digest updates from our analysis, a dashboard holding the same items, and a cited assistant for everything they raise.

  • Federal Register, Federal Register+, Grants.gov, Regulations.gov, NSF News, UKRI, plus CASRAI’s own published content.
  • 72,264 indexed passages, and every answer cites the ones it drew on.