A key signature in Western musical notation is a graphic representation at the beginning of each staff, just after the clef but before the time signature, indicating how many sharps or flats are in the piece's main key. The use of a key signature automatically makes the affected notes sharp or flat for the entire piece, unless cancelled out by a natural sign. While it's theoretically possible for any combination of flats and sharps to constitute the key signature, it is usually the case for the key signature to consist either of sharps or flats, but not both. Also unusual are key signatures containing more than six sharps or flats, though one sometimes sees seven in a few extreme cases (more being theoretically impossible). Johann Sebastian Bach uses seven sharps in the third prelude and fugue of Well-Tempered Clavier, and Beethoven uses seven flats in the third movement of his piano sonata Op. 26.
Students learn within the first few years of musical lessons which major or minor key a key signature indicates, which can be ascertained by counting the number of sharps or flats. They correspond as follows:
| No. of Sharps or Flats | Major Key | Minor Key |
|---|---|---|
| 0 | C | a |
| 1♯ | G | e |
| 2♯ | D | b |
| 3♯ | A | f♯ |
| 4♯ | E | c♯ |
| 5♯ | B | g♯ |
| 6♯ | F♯ | d♯ |
| (7♯) | (C♯) | (a♯) |
| 1♭ | F | d |
| 2♭ | B♭ | g |
| 3♭ | E♭ | c |
| 4♭ | A♭ | f |
| 5♭ | D♭ | b♭ |
| 6♭ | G♭ | e♭ |
| (7♭) | (C♭) | (a♭) |
In the case of six sharps or flats, the actual notes are enharmonically identical, which means that on keyboard instruments this represents exactly the same scale, though notated differently. J.S. Bach also used this enharmonic equivalence to prove a point in Book 1 of the Well-Tempered Clavier, in which he wrote the eighth prelude in e♭ minor, and its accompanying fugue in d♯ minor.
It is also possible, albeit rare, for a key signature to denote a mode other than major or minor. In 17th and early 18th century music, g minor is sometimes written with one flat, which is a holdover from the modal thinking of Renaissance music.