The water table near the ocean

A question for… science/geology types.

Areas of land right near the ocean typically but not always are quite sandy. Frequently the water table is fairly high, close to the surface.

How can it be that you can have a house 200 yards from the surf and have a fresh water table underneath your house, yet if you go 200 yards out, you are in the salt water- and more importantly, you are in salt until you hit a sandy/rocky bottom, at which point you are still in salt.

How does the earth go about making a dividing line underground so that the fresh water table is not sullied by proximity to salt water? Or, am I wrong and is it impossible to drill a well for fresh potable water within a few miles of the ocean? ( This would shock me, since lots of folks on Cape Cod, for example, have fresh water wells and they are wicked close to the ocean. )

How does this work, exactly?

Cartooniverse

Fresh water floats on seawater:

here

Contamination of these fresh water lenses with salt was a big problem after the 2004 tsunami.

When I was on the Midway Islands we drew fresh water from the “lens” under the island. We had to take frequent salinity tests to assure that we didn’t over pump. We utilized what were known as “maui” type wells. I believe they were originally developed on the island of Maui, possibly by the sugar plantation owners.These had a central well casing w/ laterals extenting out from it, like spokes from a hub. The laterals were pourous so as to collect the fresh water and conduct it to the central casing where it was pumped into the system. We had two standpipes (water towers) for storage and system pressurization, plus surface level storage tanks. We also had catchment areas as well as the airfield runways which were used to capture rainwater.
There were three water distribution systems on the island, salt, brackish and fresh. The salt water system was used for flushing and fire hydrants, but it eventually became too expensive to maintain, because of corrosion, and we were gradually eliminating it as it devoped leaks. The brackish system, which was replacing the old salt system, was also supplied from wells, but standard type wells, not the “maui” wells, which were more expensive to construct and maintain. The fresh system was used to distribute potable water and for a limited number of other uses, such as the sprinkler systems in the aircraft hangers.