Legend says that in 832 AD, an army of Scots was facing a Northumbrian army. The Scottish king prayed to St Andrew for help, and saw the saltire of St Andrew (the saint had been martyred on a diagonal cross) in the heavens against a clear blue sky. On seeing the cross in the sky, he swore that if the Scots beat the English in the battle that was about to be joined, then St Andrew would forever be the patron saint of Scotland
The Scots did in fact win the battle, and from that day on the saltire has been the national flag of Scotland.
You may see another Scottish flag, below
This is the Royal Flag of Scotland, and strictly speaking should only be used by the king or queen of the United Kingdom, in their capacity as monarch of Scotland.
However it is used fairly universally now as a second flag of Scotland. It has even been hijacked by politicians, flying over the offices of the Secretary of State for Scotland (who is the representative of the U.K. government in Scotland) in both London and in Edinburgh.
In one of those peculiarly British edicts on etiquette, the Lord Lyon, the herald responsible for Scottish heraldry, takes the official stance that the Rampant Lion Flag can be waved (as at football matches) but that it cannot be flown from a flagpole without his permission. Indeed he once threatened the town councillors of Cumbernauld with a parliamentary Act of 1679 which prescribed the death penalty for misuse of the royal arms.