Which repository will Ubuntu choose to download a package from if the same package is available in more than one repos? Suppose a package A was initially installed from repository X and later I added repo Y which also has package A. Which repo will be chosen to update the package? Also if I completely remove this package and try to reinstall then which repo would be preferred by Ubuntu to install the package?
By default, the package with the highest version number is installed, regardless of which repository it comes from, unless its version number is lower than the currently installed version of the package (this can happen, for example, if you downloaded a higher version as a
.deb package and installed it manually). In the very unlikely case that several repositories have the same (highest) version of a package, the package is installed from the one which appears first in the
You can change this, however, by assigning a different priority to some packages based on various criteria. The previous paragraph is true with the default settings because by default all packages have priority 500. If different versions of the package have different priorities, however, the version with the highest priority will be installed, and version numbers will only be used as tie-breakers if several versions have the same (highest) priority. Also, if the highest-priority package has priority at least 1000, it will be installed even if its version is lower than the version currently installed.
Priorities are managed in
/etc/apt/preferences and documented in
man apt_preferences. See my answer here for an example of how they can be used.