Leetcode SQL 50 -- 1527. Patients With a Condition

  1. Question
    1. Table name: Patients
  2. Explaination
    1. SQL LIKE Operator
    2. Valid outputs
  3. Solution

Question

Table name: Patients

Column Name Type
patient_id int
patient_name varchar
conditions varchar

conditions contains zero or more code separated by spaces.
This table contains information of the patients in the hospital.

Write a solution to find the patient_id, patient_name, and conditions of the patients who have Type I Diabetes.
Type I Diabetes always starts with DIAB1 prefix. Return the result table in any order.

Explaination

SQL LIKE Operator

In SQL, to extract data that contain certain specified pattern, we can use LIKE in the WHERE clause.
For example, we can use

SELECT * FROM Patients WHERE conditions LIKE 'DIAB1%'

In here, % is a wildcard, refers to any number of characters can exist after the string DIAB1.
DIAB1, DIAB1234, DIAB1eg are valid outputs.

There is another wildcard _, refers to exactly one single character.
aDIAB12, 2DIAB1 are valid outputs of _DIAB1

Valid outputs

In this question, conditions which contain valid DIAB1 are either:

  • DIAB1 is after some conditions, for exmaple ACNE DIAB100, or
  • the list of conditions begins with DIAB1, for example DIAB100 MYOP.

Therefore, we have to include both cases with two separate LIKE operator.

Solution

SELECT * FROM Patients
WHERE conditions LIKE '% DIAB1%' OR conditions LIKE 'DIAB1%'

More SQL 50 questions: here


Please cite the source for reprints, feel free to verify the sources cited in the article, and point out any errors or lack of clarity of expression. You can comment in the comments section below or email to GreenMeeple@yahoo.com
This Repo