Skip to main content
Practice Problems

What is the difference between git merge and git rebase?

Two ways to integrate changes from one branch to another.

git merge

Creates a new "merge commit" that ties together histories.

```bash git checkout main git merge feature

```

Result: ``` main: A---B---C-------M \ / feature: D---E ```

Pros:

  • Preserves complete history
  • Safe for shared branches
  • Shows when features were merged
  • Non-destructive

Cons:

  • Creates extra merge commits
  • History can become cluttered
  • "Spaghetti" history in large teams

git rebase

Moves commits to new base, creating linear history.

```bash git checkout feature git rebase main

```

Result: ``` Before: main: A---B---C
feature: D---E

After: main: A---B---C
feature: D'---E' (new commits!) ```

Pros:

  • Clean, linear history
  • Easier to follow
  • No merge commits
  • Better for code review

Cons:

  • Rewrites commit history (dangerous!)
  • Can't see when feature was merged
  • Complex conflicts
  • Never use on public branches!

When to Use What?

Use Merge when:

  • Working on public/shared branches
  • Want to preserve full history
  • Multiple people work on branch
  • Safe default choice

Use Rebase when:

  • Cleaning up local commits before push
  • Feature branch not yet pushed
  • Want linear history
  • Solo development

Common Workflow

```bash

git checkout feature git rebase main # Clean up feature commits

git checkout main git merge feature --no-ff # Keep feature context ```

Golden Rules

  1. Never rebase public history
  2. Rebase local, merge public
  3. Use rebase for cleanup before sharing
  4. Use merge for integrating work

Interactive Rebase

Clean up commits before merging:

```bash git rebase -i HEAD~3

```

Interview Q&A

Q: Can you undo a merge? A: Yes, use `git reset --hard HEAD~1` (before push) or `git revert -m 1 ` (after push).

Q: What happens if you rebase a public branch? A: Others get conflicts, duplicate commits, and history chaos. Team must `git reset --hard` to fix.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems