Musicians often say that a particular composition is written in a particular key. In fact, the key of a composition is often communicated in its title, for instance: Bach’s Prelude No. 5 in D major from Well-Tempered Clavier, book I. However, any longer composition usually has passages that are written in different keys. The question is then, how musicians determine the key of a composition as a whole?
Most often, a composition begins and ends with the same key. In this case, the key of the composition is equal to the key in which the composition begins and ends. For instance, we can look at the beginning and ending of Bach’s Prelude No. 5 in D major, from Well-Tempered Clavier, book I, shown in the next figure. As understood from its title, we should expect that this composition begins and ends with passages written in the D major key. Indeed, we see in the figure that all the notes are diatonic tones of the D major key. Also, we see that the D major/B minor key signature is used.
Figure: The beginning and ending of Bach's Prelude No. 5 in D major, from Well-Tempered Clavier, book I
However, there exist compositions that do not begin and end with the same key. Especially, if the key changes a lot in them, it is a matter of convention what key is associated with them: it may be the key at the beginning, the one at the end or the one that occurs the most often.
The key of a composition is often called its home key.