Depends on the ship/structure. Generally goes by rank, but on a ship, the ship's captain, regardless of rank, outranks all other officers at all times as Starfleet Command is based on the U.S. Navy command structure
Usually it goes: Captain, First Officer, Second Officer (if one is present), Chief Engineer. This will vary of course based on many variables. It's probably easier to state the chain of command on the different series.
TOS: Kirk, Spock, Scotty, Sulu
TNG: Picard, Riker, Data, Geordi.
DS9: Sisko, Kira, Dax (I could be wrong here)
VOY: Janeway, Chakotay, Tuvok
ENT: Archer, T'Pol, Tucker
In TNG "The Arsenal of Freedom" it's worth noting that Geordi, a Lt. j.g. at the time, was over Lieutenant Logan, the Chief Engineer of the Week. Perhaps Logan had not undergone starship command training or something.
(bridge officers are generally given command preferentially over other officers, regardless of rank)