This algorithm aims at unifying and generalizing the algorithm for detecting all types of documented drug interactions such as drug-drug interactions, drug-disease interactions, drug-patient interactions (drug allergy) from patient profile information and drug-laboratory test interactions in real-time prescribing system. Ideally, the system should conform to the following criteria: (1) data independence; (2) software interconnectability; (3) knowledge expandability; (4) flexibility; and (5) computation resource efficiency. We propose a robust Structured Query Language (SQL) algorithm to detect drug interactions and drug allergy according to such criteria. We believe that this is the first public domain algorithm in SQL that could be easily implemented into most open-system prescribing software which support SQL language. The algorithm comprises two major stages: 'expand' and 'extract'. The former expands all information in the prescription with their synonyms, groups, or components. The latter extracts the documented interactions by inner-joining knowledge-base with two independent copies of the expanded prescription list simultaneously. Simulation study for speed performance indicates that this algorithm is well behaved, for the speed of computation does not grow faster than the growth in prescription size.