How does PostgreSQL decide which query to cancel during deadlock cleanup I know that PostgreSQL will detect and clear deadlock once it happen by cancelling one of the queries. How does PostgreSQL decide which one to cancel? Is this deterministic or there is some randomness in this? Will it cancel the same query always when situation is the same?
According to the documentation located at http://www.postgresql.org/docs/9.4/static/explicit-locking.html#LOCKING-DEADLOCKS (emphasis mine):


  PostgreSQL automatically detects deadlock situations and resolves them
  by aborting one of the transactions involved, allowing the other(s) to
  complete. (Exactly which transaction will be aborted is difficult to
  predict and should not be relied upon.)