I agree with Hakon. There are several factors relevant here. First, no lens is perfect. The tricky bit is the edges of the lens, which are less perfect optically than the middle part of the lens. When the lens is "wide open" (i.e. the aperture hole is at its largest size), then there is a bit of distortion caused by the edges of the lens. Pro photographers generally consider f/8 to the the "sweet spot". Closing the aperture down to f/8 eliminates light rays from the edges of the lens elements.
Second, above approximately f/8, the smaller you make the aperture (i.e. the larger the f/number) the more distortion you get from an optical phenomenon called "diffraction".
Third, the smaller you make the aperture, the greater is your depth-of-field. DOF is the range between the nearest object in focus and the furthest object in focus.
Fourth, if you have a zoom lens and use a wide angle setting while getting closer to the subject, you will get MUCH better DOF. Most photos that appear to be sharp for both very close any very far objects are shot with the lens set at a somewhat wide angle setting.
There are a lot of fancy tricks you can use to increase your DOF, such as focus stacking, but these are pretty advanced techniques.
Hope this helps,