Q1 of 40 · Git

Explain the difference between git merge and git rebase.

GitJuniorgitmergerebasebranchingworkflow

Short answer

Short answer: git merge joins two branches by creating a merge commit with two parents, preserving full branching history. git rebase re-applies your commits on top of another branch tip, producing a linear history as if you'd started from there. Merge is safer for shared branches; rebase is cleaner for private feature branches before a PR.

Detail

Both commands integrate changes from one branch into another, but they rewrite history differently.

git merge: if the target branch is ahead and there's no divergence, Git fast-forwards (no extra commit). Otherwise it creates a three-way merge commit with two parents. The commit graph shows the actual branching shape — when the feature diverged, when it merged back. This is honest and reversible (git revert on a merge commit works). On a busy repo the graph fills with merge commits that make git log noisy.

git rebase: takes your commits, temporarily removes them, updates your branch pointer to the tip of the target, then replays your commits on top — creating new commits with new hashes. The result looks like you wrote your feature starting from the latest main. Linear, clean, easy to git bisect. The downside: it rewrites history. If others have already based work on your original commits, the rewrite breaks their branches.

The rule in practice:

  • Public/shared branches (main, develop, release branches) → merge only. Never rebase shared history.
  • Private feature branches → rebase onto main to stay current before opening a PR, then merge (or fast-forward) to main. This gives you linear history on main without the force-push danger of rebasing shared branches.

// EXAMPLE

# Merge approach — preserves branching history
git checkout main
git merge feature/login
# Creates a merge commit if histories diverged

# Rebase approach — keep your feature branch current with main
git checkout feature/login
git rebase main            # replay feature commits on top of current main tip
# If conflicts arise:
git add .
git rebase --continue      # or: git rebase --abort to cancel

# After clean rebase, integrate to main without a merge commit
git checkout main
git merge feature/login    # fast-forward — perfectly linear history

# Visualise the difference
git log --oneline --graph --decorate

// WHAT INTERVIEWERS LOOK FOR

Understanding that merge preserves history and rebase rewrites it (new commit hashes), the golden rule of never rebasing public branches, and the practical workflow: rebase private branches to stay current, merge into shared branches. Knowing what 'two parent commits' means for merge is a nice bonus.

// COMMON PITFALL

Saying 'rebase is always better because it's cleaner.' Rebase on a shared branch causes the team to deal with divergent histories and force-push situations. The right answer is always context-dependent.