Petroleum was formed by the decomposition of the remains of plants and animals buried under the sea millions of years ago.
The plants and animals which lived in the sea, died and their bodies settled at the bottom of the sea. The dead remains got covered with mud, sand and clay. Due to high temperature, high pressure and the absence of air, these were slowly converted into petroleum and natural gas as shown in figure.

The layer containing petroleum oil and gas is found above than water. It is because oil and gas are lighter than water and do not mix with it.
Petroleum is extracted by drilling holes (oil wells) in the Earth's crust. In the drilling process, natural gas comes out first with a great pressure and for a time, the crude petroleum oil comes out by itself due to gas pressure.