Say you are going to compose a piece of music in the key of D. You know, by the circle of fifths, that there are two sharps in the key of D = F# and C#. When writing the key signature on the staff you must write the F# first and then the C#. Why? Because, on the circle of fifths, G is a fifth up from C and has one sharp in it, which is F#. It is the first sharp in the circle of fifths.
WS WS HS WS WS WS HS
Begin on G on the keyboard and follow this pattern and you will find that F is the only sharped note in G major scale.
If we follow our circle of fifths the sharps are in this order: F#, C#, G#, D#, A#, E#, B#. Another way to think of it is in fifths. Notice that each sharp is a fifth up from the latter.
This is what the order of sharps looks like on the staff:
Now let's look at the order of flats. The same rule applies. We find which notes are flatted by using our major scale pattern. Then when writing the key signature we place the flats in the proper order that they are in on the circle of fifths: Bb, Eb, Ab, Db, Gb, Cb, Fb. Another way to think of the order of flats is to think in fifths. Each flat is a fifth DOWN from the latter.
Here is what the order of flats looks like on the staff:
If you were writing the key signature for Eb it would be as follows: Bb, Eb, Ab
Hope this is helpful. Feel free to leave any comments or questions.