BAM vs SAM: Key Differences

By Dr. Zubair Khalid, DVM, MS, PhD ·

BAM vs SAM: Key Differences

BAM and SAM hold the same information, because BAM is simply a binary, block-compressed, indexable encoding of the SAM text format. The rule of thumb that covers almost every real decision: keep alignments in BAM for storage, sorting, and any lookup by genomic coordinate, and convert to SAM only when a person or a small script needs to read the records directly.

That single sentence hides a lot of practical detail. The two formats diverge in file size, access patterns, tool support, failure modes, and archival role. Getting the choice wrong rarely produces an error message. It produces a pipeline that runs ten times slower than it should, a file a collaborator cannot open, or an index that silently fails because the header was stripped three steps earlier.

This guide covers what each format actually is, how the records are laid out, where they sit in a sequencing workflow alongside FASTQ and FASTA, and the specific situations where one beats the other.

Side-by-Side Comparison of BAM and SAM

PropertySAMBAM
Full nameSequence Alignment/MapBinary Alignment/Map
EncodingPlain text, one line per alignment recordBinary records in a compressed container
CompressionNone by default, optional gzip as .sam.gzBGZF (blocked gzip) built in
Typical file sizeLarger, often several-fold bigger than the equivalent BAMSmaller, compression ratio depends on read length and quality strings
Random access by coordinateNot possible without conversionYes, via a .bai or .csi index
Human readableYes, with less, head, awkNo, requires samtools view or a library
Sorting requirement for indexingNot indexable as textMust be coordinate sorted before indexing
Header block@HD, @SQ, @RG, @PG, @CO linesSame header, stored at the start of the file
Standard command-line toolsamtools view, awk, cut, grepsamtools view, samtools sort, samtools index
Common downstream consumersCustom scripts, teaching examples, quick inspectionGATK, DeepVariant, featureCounts, IGV, almost every aligner
Archival roleSource text that can be regenerated from BAMCommon working format, often migrated to CRAM for long-term storage

The table answers the surface question. The rest of this article explains why each row looks the way it does, because the reasons drive the edge cases.

What SAM Actually Is

SAM is a text specification for storing read alignments against a reference sequence. Every SAM file has two parts: an optional header block and a body of alignment lines. The format was designed so that a single line of text describes one read and its placement on a reference.

The header block

Header lines begin with @ and appear before any alignment record. The most important is @SQ, which declares each reference sequence and its length.

@HD	VN:1.6	SO:coordinate
@SQ	SN:chr1	LN:248956422
@SQ	SN:chr2	LN:242193529
@RG	ID:lane1	SM:sampleA	PL:ILLUMINA
@PG	ID:bwa	PN:bwa	VN:0.7.17	CL:bwa mem ref.fa R1.fq.gz R2.fq.gz

Each tag carries meaning. SO:coordinate records the sort order. SN and LN give the reference name and length. @RG defines a read group, which is how per-sample and per-library information travels with the reads. @PG records the program, version, and command line that produced the file, which is one of the few provenance mechanisms in genomics that actually survives handoffs between labs.

The @SQ lines are not decorative. Without them, a BAM converted from that SAM has no reference dictionary. Tools like GATK will refuse to run, and samtools index will fail. Stripping headers to save a few kilobytes is one of the most common ways to break a downstream pipeline.

The 11 mandatory alignment fields

Each alignment line has 11 tab-separated mandatory fields followed by optional tags.

#FieldMeaningExample
1QNAMERead nameread_0001
2FLAGBitwise flag describing the read99
3RNAMEReference sequence namechr7
4POS1-based leftmost mapping position55019017
5MAPQMapping quality, Phred scaled60
6CIGARCompact representation of the alignment76M
7RNEXTReference name of the mate or next read=
8PNEXTPosition of the mate or next read55019103
9TLENObserved template length162
10SEQRead sequenceACGTACGT
11QUALBase qualities, Phred+33 encodedIIIIIIII

The FLAG field packs many booleans into one integer. The value 99 decodes as 1 (paired) plus 2 (proper pair) plus 32 (mate is reverse strand) plus 64 (first read in pair). Other bits mark unmapped reads (4), reverse-strand reads (16), secondary alignments (256), PCR or optical duplicates (1024), and supplementary alignments such as the split pieces of a chimeric read (2048). A single integer therefore answers questions that would otherwise need several columns.

The MAPQ field deserves its own warning. A value of 255 means the mapping quality is unavailable, not that the read mapped perfectly. Multi-mapping reads often carry MAPQ 0. Filtering with $5 < 20 in awk treats 255 as high quality, which is the opposite of what many people intend.

CIGAR strings use a small alphabet: M for alignment match, I for insertion to the reference, D for deletion from the reference, N for skipped region such as an intron, S for soft clipping, H for hard clipping, P for padding, and = or X for explicit match or mismatch. A CIGAR of 50M100N50M describes a read split across an intron, which is exactly what a spliced RNA-seq aligner emits.

Optional fields and tags

Anything after the 11 mandatory columns is a tag of the form TAG:TYPE:VALUE. Common examples include NM:i:2 for edit distance, AS:i:74 for alignment score, RG:Z:lane1 for read group assignment, and MD:Z:... for a mismatch string used by variant callers and by some visualization tools.

These tags are where much of the practical value of an alignment file lives. Variant callers, duplicate markers, and quantification tools all read them. A SAM file that has been through an aggressive cut -f1-11 will still parse, and will still lose information that mattered.

Why text still matters

Text has one property that binary formats cannot match: a human can read it. When an alignment looks wrong in a genome browser, the fastest diagnostic is often samtools view -h sample.bam | head -40 and a careful look at the flags, the CIGAR string, and the header. A pipeline that produced 4 percent mapped reads can usually be explained by inspecting a handful of SAM lines, not by rerunning anything.

Text also makes SAM the format of choice for teaching, for bug reports, and for tools that accept a stream of alignments on standard input.

What BAM Is Under the Hood

BAM carries the same records and the same header as SAM, but writes them in a binary layout inside a compressed container.

BGZF blocks

The compression layer is BGZF, short for blocked GNU zip format. A BAM file is a series of independently compressed gzip blocks, each holding up to about 64 KB of uncompressed data. Each block carries its own checksum and end-of-file marker. The final file is a valid gzip stream, so a standard gunzip can decompress it, but only BGZF-aware tools can jump from block to block without streaming through everything before the target.

That block structure is what makes random access possible. An index stores virtual file offsets, each combining a block position and a position within that block. A tool asked for reads at chr7:55,000,000 seeks directly to the right block instead of scanning the file from the start.

The same idea appears elsewhere in genomics. A benchmark of two nanopore signal formats found that the binary BLOW5 container beat POD5 on sequential and random-access reads across most tested systems, with no tested case where POD5 reading was significantly faster [1]. Container design, not merely the binary versus text distinction, determines how fast a file can be read.

Binary record layout

Inside the decompressed stream, each alignment record starts with a fixed-size block: a length field, the reference ID, the 0-based position, the read name length, mapping quality, bin, CIGAR operation count, flag, sequence length, mate reference ID, mate position, and template length. Variable-length fields follow: the read name, the packed CIGAR, the sequence, the qualities, and the tags.

The sequence is packed four bases per byte using a small lookup table (A=1, C=2, G=4, T=8, N=15), which halves the space compared with plain text. Qualities are stored as raw bytes rather than ASCII characters offset by 33, which saves one byte per base and removes the printable-character ceiling that SAM imposes.

These choices explain most of the size difference. A SAM line for a 150 bp read spends roughly 150 bytes on sequence, 150 on qualities, and another 150 on the CIGAR and the rest of the fields, assuming typical tag content. The same record in BAM spends about 38 bytes on packed sequence, 150 on qualities, and a few dozen on the remaining binary fields, then compresses the whole stream. The exact ratio varies with read length, quality-string entropy, and how repetitive the alignments are, which is why quoting a single compression figure for all data is a mistake.

Sorting and the BAI index

BAM files intended for coordinate queries must be sorted by reference and position. samtools sort produces that order, and samtools index builds the .bai file. The classic BAI has coordinate limits that some very large or highly scaffolded assemblies exceed, which is why the CSI index format exists as an alternative for large references.

Two consequences follow. First, an unsorted BAM can be created and read, but it cannot be indexed for random access. Second, sorting is not free. It rewrites the entire file and needs disk space for temporary chunks. A pipeline that sorts three times because nobody checked the sort order wastes hours on large data.

What BAM does not change

BAM does not add information. The FLAG semantics, the CIGAR alphabet, the tag vocabulary, and the header conventions are identical. BAM does not store the reference sequence either, which is why CRAM exists as a reference-based alternative that compresses far better for some data and requires the matching reference to decode.

Where SAM and BAM Sit in a Workflow

Alignment files are the middle of a sequencing pipeline, not the start and not the end.

FASTQ versus FASTA, the formats before alignment

Raw reads come out of a sequencer as FASTQ. Each record has four lines: an @ header, the nucleotide sequence, a + separator, and a quality string of the same length as the sequence, encoded with Phred+33 so that a quality of 30 appears as the character ?. FASTQ is the format that carries per-base confidence, which is the entire reason quality trimming tools such as FastQC and Trimmomatic have something to work with.

FASTA has only two lines per record: a > header and the sequence. No qualities. FASTA is where reference genomes, transcriptomes, protein sets, and individual gene sequences live. When you align reads to a reference, the reference is FASTA and the reads are FASTQ. Newer work has extended FASTA headers to carry structured annotation, such as the FASTS format that embeds SMILES chemical structure strings alongside peptide sequences [2], but the core two-line structure is unchanged.

The distinction matters for SAM and BAM because neither carries the original per-cycle quality information beyond the trimmed base qualities that survive into the QUAL field. If you deleted the FASTQ, you cannot recover the raw reads from the BAM. The BAM contains the sequence as the aligner saw it, after any trimming and clipping decisions.

FormatContentQuality scoresTypical role
FASTASequence onlyNoReference genomes, transcripts, proteins
FASTQSequence plus per-base qualityYesRaw sequencing reads
SAMAligned reads as textYes, Phred+33Inspection, interchange, teaching
BAMAligned reads as compressed binaryYes, raw bytesStorage, sorting, coordinate queries

The alignment step itself

A typical short-read pipeline runs the aligner and pipes its SAM output straight into a sorter, which writes BAM.

bwa mem -t 8 ref.fa R1.fq.gz R2.fq.gz \
  | samtools sort -@ 4 -o sample.bam -
samtools index sample.bam
samtools flagstat sample.bam

The SAM that bwa mem writes to standard output never touches disk. It exists as a stream between two processes. This is the dominant pattern in production pipelines, and it explains why SAM remains important even in workflows that store nothing but BAM. Start-to-finish protocols for bulk RNA-seq follow the same logic, using FastQC for read quality, Trimmomatic for trimming, BWA or HISAT2 for alignment, and Samtools for the format conversion and sorting steps [3].

A closely related workflow exists for data reuse. The European Genome-Phenome Archive runs a QC portal over submitted FASTQ, SAM/BAM/CRAM, and VCF files, and has published reports covering 1,694,442 files, letting users assess quality before requesting access [4]. That kind of programmatic quality assessment is only practical when files are in an indexable binary form.

The Criteria That Decide the Choice

Four criteria decide most real choices: storage, random access, tool support, and human review.

Storage and transfer

BAM is smaller than uncompressed SAM, usually by a wide margin. It is not always smaller than a gzipped SAM, because both end up roughly compressed. A .sam.gz file loses indexing but keeps readability after decompression, which makes it a reasonable compromise for small datasets shared with someone who wants to read the text.

For very large studies, specialized formats beat both. A methylation haplotype format reduced BAM file size by 40 to 140 fold while keeping read-level CpG information [5]. An epiread format achieved over 100-fold compression from an input BAM for whole-genome bisulfite data [6]. A CH3 format cut methylation file sizes by more than 95 percent and paired with a database backend for analysis [7]. These are not replacements for BAM in general. They are evidence that BAM stores more than many analyses need.

The same pattern holds for genotype data. A simple uncompressed binary format, IGD, was reported as more than 100 times faster and 3.5 times smaller than vcf.gz on biobank-scale whole-genome sequence data [8]. Binary design decisions compound at scale.

Random access

This is the clearest dividing line. SAM cannot be queried by region without reading the whole file. BAM with a BAI or CSI index can jump straight to chr7:55,000,000 and return the overlapping reads in milliseconds.

The practical consequence is that any tool that displays a genomic region, such as IGV, any tool that walks the genome in windows, such as variant callers and coverage calculators, and any tool that needs to fetch a specific locus for review all depend on indexed BAM. Structured query layers have been built on top of SAM/BAM specifically to make complex filtering easier, with one SQL-like tool designed to replace long chains of Bash one-liners and to scale without reorganizing existing file infrastructure [9].

Tool support

Almost every aligner emits SAM. Almost every downstream consumer prefers BAM. The tools that read BAM include GATK, DeepVariant, Picard, featureCounts, HTSeq, IGV, samtools, and the htslib ecosystem that underlies most of them. Tools that read SAM are fewer, though many accept it on standard input because the two formats share a specification.

Ambiguity is rare in practice. If you are unsure whether a tool takes SAM or BAM, checking the documentation is faster than guessing, but the safe default is BAM.

Human review

Text wins here, and it is the only criterion where SAM has a clear advantage. Grepping for a read name, checking whether a read group tag exists, counting how many records have a specific flag, or reading the first 20 lines of a suspicious file are all one-liners in SAM and require samtools view in BAM.

The cost is small. samtools view -h file.bam | head -40 gives the same view at the cost of one extra command.

Archiving

Neither format is ideal for permanent archival. BAM is the common working format and is widely accepted by repositories, but CRAM compresses better for many datasets because it stores alignments as differences from the reference. The tradeoff is that CRAM decoding requires the matching reference sequence, and a CRAM paired with the wrong reference build fails or produces wrong sequences. That dependency is fine for a well-managed archive and risky for a file passed between labs without documentation.

When to Use BAM

Use BAM when any of the following is true.

  • The file will be queried by genomic region, now or later.
  • The file will be visualized in a genome browser.
  • The file feeds a variant caller, a quantification tool, or a peak caller.
  • The file needs to be sorted, merged, or deduplicated with standard tools.
  • The file will be shared with a collaborator who expects a standard alignment format.
  • The dataset is large enough that storage and transfer cost matter.
  • The file will be submitted to a repository that accepts alignment data.

In practice, this covers nearly every alignment file that survives past the alignment step. The default assumption in a production pipeline is BAM unless there is a specific reason to use something else.

When to Use SAM

Use SAM when the file is meant for reading rather than computing.

  • Debugging an aligner or a pipeline, especially when flags, CIGAR strings, or header lines look wrong.
  • Teaching the format or reviewing a method section with someone who has not seen alignments before.
  • Writing or testing a small parser where a text line is easier to handle than a binary record.
  • Sharing a handful of records in a bug report or a methods appendix.
  • Inspecting the header of an existing file with samtools view -H file.bam.
  • Interfacing with a tool that only accepts SAM or that accepts it on standard input.

The unifying theme is human bandwidth. SAM is the format you use when a person is the consumer.

Worked Scenarios

Scenario 1: Bulk RNA-seq from FASTQ to counts

A typical RNA-seq run starts with FASTQ, trims adapters, aligns with a splice-aware aligner such as HISAT2, and ends with a count matrix. The aligner emits SAM, which is piped into samtools sort to produce BAM. The BAM is indexed so that quantification tools and visualization tools can access it by region. The final count step reads the BAM, not the SAM. Choosing SAM for storage here would multiply disk usage and break region-based tools. Published start-to-finish protocols for this workflow use exactly this chain of FastQC, Trimmomatic, HISAT2 or BWA, and Samtools [3].

Scenario 2: A sample maps at 3 percent and nobody knows why

The first step is to look at the data, not to rerun the aligner. samtools view -h sample.bam | head -40 shows the header, the reference names, and the first few alignment records. Common findings include a @SQ header naming a different reference build than the one used downstream, read names that carry a barcode that should have been trimmed, or CIGAR strings with heavy soft clipping at one end, which usually means residual adapter. Quality control tools designed for this task report sequence composition, base quality composition, and mapping error profiles split by mapping quality, which is exactly the view needed to distinguish a trimming problem from a sequencing problem [10]. The diagnosis happens in the text view, and the fix happens upstream.

Scenario 3: Submitting alignments to a repository

Repositories accept SAM, BAM, and CRAM, and run quality checks on what arrives [4]. The practical choice is BAM for consistency, or CRAM if storage is tight and the reference can be reliably documented. Submitting SAM is possible but uncommon for anything beyond small examples, because the files are larger and the receiving system may convert them anyway.

Scenario 4: Pulling one read by its identifier

Coordinate queries on BAM are fast because of the BAI. Queries by read name are slow because the BAI has no name index. A tool built for this specific problem creates a one-time read identifier index in the same BGZF format as the BAM and retrieves reads by name, with retrieval appearing near instantaneous after the index exists [11]. The lesson is not that BAM is bad at name queries. It is that the index determines which access pattern is fast, and BAM ships with a coordinate index by default.

Scenario 5: Methylation data and other specialized assays

Bisulfite sequencing alignments carry methylation calls in the read sequence itself, which makes BAM awkward and bulky for downstream work. Specialized formats convert BAM into a representation that preserves read-level CpG information at 40 to 140 fold smaller size [5], or over 100-fold compression in an epiread representation [6]. If the analysis is methylation-specific, the BAM is an intermediate, not the destination.

Scenario 6: Hi-C and metagenomics

Hi-C pipelines use SAM/BAM as an intermediate representation before converting to matrix formats such as .hic or .mcool that store multi-resolution contact data for visualization [12]. Metagenomics pipelines similarly move through several format layers, and modular systems built in Snakemake emphasize standardized module outputs to keep those transitions reproducible [13]. In both cases BAM is the working format at the alignment stage and is replaced by something more specialized afterward.

Common Mistakes and Limitations

Forgetting that BAM is not a gzip file you can edit in place. BGZF is a valid gzip stream, but appending to it, editing a block, or splitting it with generic tools corrupts the offset structure. Use samtools or bgzip for anything beyond decompression.

Stripping the header. A SAM file without @SQ lines converts to a BAM without a reference dictionary. samtools index fails, GATK refuses to run, and the error message rarely points at the header. Check with samtools view -H file.bam before blaming the aligner.

Sorting after indexing. The index must be built on a coordinate-sorted BAM. If a file is re-sorted later, the old index is stale and samtools index will overwrite it, but only if you remember to run it.

Confusing name-sorted and coordinate-sorted files. samtools sort -n produces a name-sorted BAM. That file cannot be indexed for coordinate queries without re-sorting. Marking duplicates often wants name order, and variant calling wants coordinate order, so a pipeline may legitimately need both, and the file names should say which is which.

Editing SAM text with awk or cut. These tools are fine for reading and counting. They are dangerous for writing, because a misplaced tab or a truncated QUAL field produces a file that parses and is wrong. If the goal is to filter records, use samtools view with flags and region arguments.

Assuming a high MAPQ means a good alignment. MAPQ 255 means unavailable, and MAPQ 0 means a multi-mapping read. Filter with awareness of both conventions.

Assuming BAM is always smaller. For very small files, the BGZF block overhead can make BAM larger than the SAM it came from. The advantage appears at scale.

Treating BAM as self-contained. BAM does not include the reference sequence. Variant calling needs the reference FASTA, and CRAM needs it plus a correct checksum match.

Losing read groups during merging. Merging BAMs without preserving @RG lines makes per-sample demultiplexing impossible later. The reads are still there, but the sample labels are gone.

Using CRAM without the reference. A CRAM decoded against the wrong reference assembly produces plausible-looking but wrong sequence. Keep the reference build documented alongside the file.

Expecting SAM to support region queries. It does not. If a downstream tool needs a region, convert to BAM and index it, or use a purpose-built text query tool [9].

Assuming all aligners populate the same tags. NM, MD, AS, and RG are common but not universal. A pipeline that depends on MD:Z will fail on data from an aligner that does not emit it.

Ignoring the specialized format question. BAM is a general-purpose container, not an optimal one. For methylation, genotype, or contact data, formats built for the assay can reduce size by one or two orders of magnitude [6][8][5][7]. That is a real limitation of BAM, not a bug.

Frequently Asked Questions

Is BAM better than SAM?

BAM is better for storage and computation, and SAM is better for reading. They hold the same records, so neither is more accurate or more complete. The choice depends on whether the next consumer is a program or a person.

Can I convert BAM back to SAM without losing information?

Yes, for all practical purposes. samtools view -h file.bam > file.sam reconstructs the SAM text, and converting back with samtools view -b file.sam > file.bam produces a functionally equivalent file. Field ordering and tag ordering are preserved by samtools.

What is the difference between BAM and CRAM?

CRAM stores alignments as differences from a reference sequence, which usually makes it smaller than BAM. The cost is that decoding requires the exact matching reference, so a CRAM without its reference is not portable.

Do I have to sort a BAM before indexing it?

Yes. samtools index requires a coordinate-sorted BAM, and it will fail on a name-sorted or unsorted file. Run samtools sort -o sorted.bam input.bam first, then index.

Is BAM the same as FASTQ?

No. FASTQ holds raw reads with per-base quality scores before alignment. BAM holds reads that have been aligned to a reference, with coordinates, CIGAR strings, flags, and tags added. Converting BAM back to FASTQ loses the alignment information.

Which is smaller, a SAM file or a BAM file?

BAM is usually smaller, because the sequence is packed four bases per byte and the whole stream is compressed. A gzipped SAM can be close to the same size, but it loses random access and must be fully decompressed to be read.

Sources

  1. The enduring advantages of the SLOW5 file format for raw nanopore sequencing data.
  2. DRAMP 5.0: an update integrating sequence and structure in a novel FASTS format for AI-driven design of antimicrobial peptides.
  3. Streamline Protocol for Bulk-RNA Sequencing: From Data Extraction to Expression Analysis.
  4. A quality control portal for sequencing data deposited at the European genome-phenome archive.
  5. The DNA methylation haplotype (mHap) format and mHapTools.
  6. wgbstools: a computational suite for DNA methylation sequencing data analysis.
  7. ModSeqR: an R package for efficient analysis of modified nucleotide data.
  8. IGD: a simple, efficient genotype data format.
  9. SamQL: a structured query language and filtering tool for the SAM/BAM file format.
  10. SAMStat 2: quality control for next generation sequencing data.
  11. Atlantool: a command line tool to retrieve DNA and RNA sequencing reads from BAM files by the read identifier.
  12. Hi-C Data Formats.
  13. CAMP: a modular metagenomics analysis system for integrated multistep data exploration.