System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )

[User] How many patients have provided both a phone_number and emergency_contact_phone?

[Assistant] SELECT COUNT(*) FROM healthcare.patients WHERE phone_number IS NOT NULL AND emergency_contact_phone IS NOT NULL;

[User] Find pairs of patients who share the same last name. Show the patient IDs, full names, and the shared last name.

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name AS patient1_first_name, p1.last_name AS patient1_last_name, p2.patient_id AS patient2_id, p2.first_name AS patient2_first_name, p2.last_name AS patient2_last_name, p1.last_name AS shared_last_name FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.last_name = p2.last_name AND p1.patient_id < p2.patient_id;

[User] Now, only include pairs where they also share the same date of birth.

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name AS patient1_first_name, p1.last_name AS patient1_last_name, p2.patient_id AS patient2_id, p2.first_name AS patient2_first_name, p2.last_name AS patient2_last_name, p1.last_name AS shared_last_name, p1.date_of_birth AS shared_date_of_birth FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.last_name = p2.last_name AND p1.date_of_birth = p2.date_of_birth AND p1.patient_id < p2.patient_id;

[User] Could you also restrict the results to only include pairs where at least one patient has a non-null phone number?

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name AS patient1_first_name, p1.last_name AS patient1_last_name, p2.patient_id AS patient2_id, p2.first_name AS patient2_first_name, p2.last_name AS patient2_last_name, p1.last_name AS shared_last_name, p1.date_of_birth AS shared_date_of_birth FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.last_name = p2.last_name AND p1.date_of_birth = p2.date_of_birth AND p1.patient_id < p2.patient_id WHERE p1.phone_number IS NOT NULL OR p2.phone_number IS NOT NULL;

[User] Finally, sort the results by shared last name, then date of birth, ascending.

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name AS patient1_first_name, p1.last_name AS patient1_last_name, p2.patient_id AS patient2_id, p2.first_name AS patient2_first_name, p2.last_name AS patient2_last_name, p1.last_name AS shared_last_name, p1.date_of_birth AS shared_date_of_birth FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.last_name = p2.last_name AND p1.date_of_birth = p2.date_of_birth AND p1.patient_id < p2.patient_id WHERE p1.phone_number IS NOT NULL OR p2.phone_number IS NOT NULL ORDER BY shared_last_name ASC, shared_date_of_birth ASC;

[User] List the patient_id, first_name, last_name, and phone_number for all patients whose gender is 'Female', and whose emergency_contact_name is not null. Also, only include patients who have an email address.

[Assistant] SELECT patient_id, first_name, last_name, phone_number FROM healthcare.patients WHERE gender = 'Female' AND emergency_contact_name IS NOT NULL AND email IS NOT NULL;

[User] Can you only include those patients whose phone_number begins with '+1'?

[Assistant] SELECT patient_id, first_name, last_name, phone_number FROM healthcare.patients WHERE gender = 'Female' AND emergency_contact_name IS NOT NULL AND email IS NOT NULL AND phone_number LIKE '+1%';

[User] I got more results than I expected. Can you add a filter to only include patients born after January 1, 1990?

[Assistant] SELECT patient_id, first_name, last_name, phone_number FROM healthcare.patients WHERE gender = 'Female' AND emergency_contact_name IS NOT NULL AND email IS NOT NULL AND phone_number LIKE '+1%' AND date_of_birth > '1990-01-01';

[User] Find pairs of patients where patient A's emergency contact phone matches patient B's phone number, and patient B's emergency contact phone matches patient A's phone number. Include both patient IDs, their full names, patient A's phone, and patient B's phone.

[Assistant] SELECT p1.patient_id AS patient_a_id, p1.first_name AS patient_a_first_name, p1.last_name AS patient_a_last_name, p2.patient_id AS patient_b_id, p2.first_name AS patient_b_first_name, p2.last_name AS patient_b_last_name, p1.phone_number AS patient_a_phone, p2.phone_number AS patient_b_phone FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.emergency_contact_phone = p2.phone_number AND p2.emergency_contact_phone = p1.phone_number AND p1.patient_id != p2.patient_id;

[User] Show all pairs of patients who share the same email domain. Return patient1_id, patient2_id, and the shared domain, but do not pair a patient with themselves.

[Assistant] SELECT p1.patient_id AS patient1_id, p2.patient_id AS patient2_id, SUBSTRING(p1.email FROM POSITION('@' IN p1.email) + 1) AS shared_domain FROM healthcare.patients p1 JOIN healthcare.patients p2 ON SUBSTRING(p1.email FROM POSITION('@' IN p1.email) + 1) = SUBSTRING(p2.email FROM POSITION('@' IN p2.email) + 1) AND p1.patient_id <> p2.patient_id WHERE p1.email IS NOT NULL AND p2.email IS NOT NULL;

[User] Get a list of all patients and all medications they could potentially take. Include patient_id, full name, medication_id, and medication_name.

[Assistant]
SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, m.medication_id, m.medication_name
FROM healthcare.patients p
CROSS JOIN healthcare.medications m;

[User] Only include patients whose email ends with '@gmail.com'.

[Assistant]
SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, m.medication_id, m.medication_name
FROM healthcare.patients p
CROSS JOIN healthcare.medications m
WHERE p.email LIKE '%@gmail.com';

[User] Also include the medication's generic_name in the results.

[Assistant]
SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, m.medication_id, m.medication_name, m.generic_name
FROM healthcare.patients p
CROSS JOIN healthcare.medications m
WHERE p.email LIKE '%@gmail.com';

[User] Finally, filter the medications to only those manufactured by 'Pfizer'.

[Assistant]
SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, m.medication_id, m.medication_name, m.generic_name
FROM healthcare.patients p
CROSS JOIN healthcare.medications m
WHERE p.email LIKE '%@gmail.com'
  AND m.manufacturer = 'Pfizer';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Find the average settlement_amount of closed claims for each claim handler. Return claim_handler_id and avg_settlement_amount.

[Assistant]
SELECT c.claim_handler_id, AVG(c.settlement_amount) AS avg_settlement_amount
FROM insurance.claims c
WHERE c.status = 'Closed'
  AND c.settlement_amount IS NOT NULL
GROUP BY c.claim_handler_id;

[User] Retrieve the number of open claims each customer has filed. Return customer_id, first_name, last_name, and open_claim_count.

[Assistant]
SELECT cu.customer_id, cu.first_name, cu.last_name, COUNT(cl.claim_id) AS open_claim_count
FROM insurance.customers cu
LEFT JOIN insurance.claims cl ON cu.customer_id = cl.customer_id AND cl.status = 'Open'
GROUP BY cu.customer_id, cu.first_name, cu.last_name;

[User] Now include only customers who have at least 3 open claims and order the results by open_claim_count descending.

[Assistant]
SELECT cu.customer_id, cu.first_name, cu.last_name, COUNT(cl.claim_id) AS open_claim_count
FROM insurance.customers cu
JOIN insurance.claims cl ON cu.customer_id = cl.customer_id
WHERE cl.status = 'Open'
GROUP BY cu.customer_id, cu.first_name, cu.last_name
HAVING COUNT(cl.claim_id) >= 3
ORDER BY open_claim_count DESC;

[User] List all policies where the premium_amount exceeds the base_premium of its insurance product. Display the policy_number, premium_amount, product_name, and base_premium. Sort the results by premium_amount descending.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
ORDER BY p.premium_amount DESC;

[User] Actually, I only want policies that are active and whose insurance products are also active.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'active'
  AND ip.is_active = TRUE
ORDER BY p.premium_amount DESC;

[User] Also, limit the output to policies with a coverage_limit greater than 1000000.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'active'
  AND ip.is_active = TRUE
  AND p.coverage_limit > 1000000
ORDER BY p.premium_amount DESC;

[User] What is the average commission rate for active agents?

[Assistant] SELECT AVG(commission_rate) FROM insurance.agents WHERE status = 'Active';

[User] For each claim, show the claim ID, incident date, the customer's first and last name, and the policy number under which it was filed.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id;

[User] Filter these results to only include claims reported in the year 2024.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01';

[User] Now, only show claims where the status is 'Settled' or 'Approved', and include the settlement amount.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number, cl.settlement_amount FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01' AND cl.status IN ('Settled', 'Approved');

[User] For *these* settled or approved claims reported in 2024, find the count of associated claim documents and the total size of those documents. Show the claim ID, customer full name, and the document count and total size.

[Assistant] SELECT cl.claim_id, c.first_name AS customer_first_name, c.last_name AS customer_last_name, COUNT(cd.document_id) AS document_count, SUM(cd.file_size_bytes) AS total_document_size_bytes FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id LEFT JOIN insurance.claim_documents AS cd ON cl.claim_id = cd.claim_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01' AND cl.status IN ('Settled', 'Approved') GROUP BY cl.claim_id, c.first_name, c.last_name ORDER BY cl.claim_id;

[User] List policies issued by active agents to customers in the 'CA' state, including policy number, customer's first and last name, agent's first and last name, and the agent's license state.

[Assistant] SELECT p.policy_number, c.first_name AS customer_first_name, c.last_name AS customer_last_name, a.first_name AS agent_first_name, a.last_name AS agent_last_name, a.license_state FROM insurance.policies AS p JOIN insurance.agents AS a ON p.agent_id = a.agent_id JOIN insurance.customers AS c ON p.customer_id = c.customer_id WHERE a.status = 'Active' AND c.state = 'CA';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )

[User] For each prescription, find the next prescription for the same patient. Return current prescription_id, next_prescription_id, patient_id, and days between start dates.

[Assistant]
SELECT p1.patient_id,
       p1.prescription_id AS current_id,
       p2.prescription_id AS next_id,
       (p2.start_date - p1.start_date) AS days_between
FROM healthcare.prescriptions p1
JOIN healthcare.prescriptions p2
  ON p1.patient_id = p2.patient_id
 AND p2.start_date = (
       SELECT MIN(start_date)
       FROM healthcare.prescriptions p3
       WHERE p3.patient_id = p1.patient_id
         AND p3.start_date > p1.start_date
   );

[User] Only include pairs where days_between is less than 30 days.

[Assistant]
SELECT p1.patient_id,
       p1.prescription_id AS current_id,
       p2.prescription_id AS next_id,
       (p2.start_date - p1.start_date) AS days_between
FROM healthcare.prescriptions p1
JOIN healthcare.prescriptions p2
  ON p1.patient_id = p2.patient_id
 AND p2.start_date = (
       SELECT MIN(start_date)
       FROM healthcare.prescriptions p3
       WHERE p3.patient_id = p1.patient_id
         AND p3.start_date > p1.start_date
   )
WHERE (p2.start_date - p1.start_date) < 30;

[User] Find pairs of prescriptions for the same patient with overlapping periods. Show p1.prescription_id, p2.prescription_id, patient_id, and the overlap duration in days where the overlap is greater than 15 days.

[Assistant]
SELECT p1.prescription_id AS prescription_id_1,
       p2.prescription_id AS prescription_id_2,
       p1.patient_id,
       (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days
FROM healthcare.prescriptions p1
JOIN healthcare.prescriptions p2
  ON p1.patient_id = p2.patient_id
 AND p1.prescription_id < p2.prescription_id
WHERE LEAST(p1.end_date, p2.end_date) >= GREATEST(p1.start_date, p2.start_date)
  AND (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) > 15;

[User] Actually, only consider pairs where both prescriptions allow refills.

[Assistant]
SELECT p1.prescription_id AS prescription_id_1,
       p2.prescription_id AS prescription_id_2,
       p1.patient_id,
       (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days
FROM healthcare.prescriptions p1
JOIN healthcare.prescriptions p2
  ON p1.patient_id = p2.patient_id
 AND p1.prescription_id < p2.prescription_id
WHERE LEAST(p1.end_date, p2.end_date) >= GREATEST(p1.start_date, p2.start_date)
  AND (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) > 15
  AND p1.refills_allowed > 0
  AND p2.refills_allowed > 0;

[User] Also, limit the results to overlaps that start in 2024 and order by overlap_days descending.

[Assistant]
SELECT p1.prescription_id AS prescription_id_1,
       p2.prescription_id AS prescription_id_2,
       p1.patient_id,
       (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days
FROM healthcare.prescriptions p1
JOIN healthcare.prescriptions p2
  ON p1.patient_id = p2.patient_id
 AND p1.prescription_id < p2.prescription_id
WHERE LEAST(p1.end_date, p2.end_date) >= GREATEST(p1.start_date, p2.start_date)
  AND (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) > 15
  AND p1.refills_allowed > 0
  AND p2.refills_allowed > 0
  AND GREATEST(p1.start_date, p2.start_date) >= '2024-01-01'
ORDER BY overlap_days DESC;

[User] What is the average quantity_dispensed per route for prescriptions with start_date in 2024? Return route and avg_quantity.

[Assistant]
SELECT route,
       AVG(quantity_dispensed) AS avg_quantity
FROM healthcare.prescriptions
WHERE start_date >= '2024-01-01'
GROUP BY route;

[User] Refine to only include routes with more than 20 prescriptions and round avg_quantity to two decimal places.

[Assistant]
SELECT route,
       ROUND(AVG(quantity_dispensed), 2) AS avg_quantity
FROM healthcare.prescriptions
WHERE start_date >= '2024-01-01'
GROUP BY route
HAVING COUNT(*) > 20;

[User] Show prescription ID, patient ID, and medication ID for prescriptions that have a start date before their end date.

[Assistant] SELECT prescription_id, patient_id, medication_id FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date;

[User] Only include those where the refills allowed is zero.

[Assistant] SELECT prescription_id, patient_id, medication_id FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date AND refills_allowed = 0;

[User] Further narrow down to prescriptions with a 'daily' frequency.

[Assistant] SELECT prescription_id, patient_id, medication_id FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date AND refills_allowed = 0 AND frequency = 'daily';

[User] Count how many such prescriptions were issued by each doctor.

[Assistant] SELECT doctor_id, COUNT(*) FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date AND refills_allowed = 0 AND frequency = 'daily' GROUP BY doctor_id;

[User] Find pairs of prescriptions issued to the same patient but for different medications, issued on the same date. Show the patient ID, the prescription IDs of the two prescriptions, and their medication IDs and prescription dates.

[Assistant] SELECT p1.patient_id, p1.prescription_id AS prescription1_id, p1.medication_id AS medication1_id, p2.prescription_id AS prescription2_id, p2.medication_id AS medication2_id, p1.prescription_date FROM healthcare.prescriptions p1 JOIN healthcare.prescriptions p2 ON p1.patient_id = p2.patient_id AND p1.prescription_date = p2.prescription_date AND p1.medication_id <> p2.medication_id AND p1.prescription_id < p2.prescription_id;

[User] List all distinct medication IDs that have been prescribed with more than 5 refills allowed.

[Assistant] SELECT DISTINCT medication_id FROM healthcare.prescriptions WHERE refills_allowed > 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )

[User] Find all patients who have never received any diagnoses. Show patient ID, first_name, and last_name.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name
FROM healthcare.patients p
LEFT JOIN healthcare.diagnoses d
  ON p.patient_id = d.patient_id
WHERE d.diagnosis_id IS NULL;

[User] Only include those who have had at least one appointment.

[Assistant]
SELECT DISTINCT p.patient_id,
                p.first_name,
                p.last_name
FROM healthcare.patients p
JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
LEFT JOIN healthcare.diagnoses d
  ON p.patient_id = d.patient_id
WHERE d.diagnosis_id IS NULL;

[User] How many patients are there in each gender category?

[Assistant]
SELECT gender,
       COUNT(*) AS patient_count
FROM healthcare.patients
GROUP BY gender;

[User] Limit this to categories with more than 50 patients.

[Assistant]
SELECT gender,
       COUNT(*) AS patient_count
FROM healthcare.patients
GROUP BY gender
HAVING COUNT(*) > 50;

[User] I need to get a list of all patients who had an appointment in the last 30 days, including patient ID, first and last name, appointment_time, and any associated diagnosis description.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       a.appointment_time,
       d.description
FROM healthcare.appointments a
JOIN healthcare.patients p
  ON a.patient_id = p.patient_id
LEFT JOIN healthcare.medical_records mr
  ON a.appointment_id = mr.appointment_id
LEFT JOIN healthcare.diagnoses d
  ON mr.record_id = d.record_id
WHERE a.appointment_time >= current_timestamp - INTERVAL '30 days';

[User] Exclude any appointments with status 'Cancelled'.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       a.appointment_time,
       d.description
FROM healthcare.appointments a
JOIN healthcare.patients p
  ON a.patient_id = p.patient_id
LEFT JOIN healthcare.medical_records mr
  ON a.appointment_id = mr.appointment_id
LEFT JOIN healthcare.diagnoses d
  ON mr.record_id = d.record_id
WHERE a.appointment_time >= current_timestamp - INTERVAL '30 days'
  AND a.status <> 'Cancelled';

[User] Also, sort the results by appointment_time descending.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       a.appointment_time,
       d.description
FROM healthcare.appointments a
JOIN healthcare.patients p
  ON a.patient_id = p.patient_id
LEFT JOIN healthcare.medical_records mr
  ON a.appointment_id = mr.appointment_id
LEFT JOIN healthcare.diagnoses d
  ON mr.record_id = d.record_id
WHERE a.appointment_time >= current_timestamp - INTERVAL '30 days'
  AND a.status <> 'Cancelled'
ORDER BY a.appointment_time DESC;

[User] Show me the full names of all patients who have received a diagnosis for 'hypertension', along with the appointment time and the doctor's full name for each related appointment.

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, d2.first_name AS doctor_first_name, d2.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.patients d2 ON diag.doctor_id = d2.patient_id
WHERE diag.diagnosis_code = 'hypertension';

[User] Actually, can you update the query to only include those appointments that are currently marked as 'scheduled'?

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, d2.first_name AS doctor_first_name, d2.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.patients d2 ON diag.doctor_id = d2.patient_id
WHERE diag.diagnosis_code = 'hypertension' AND a.status = 'scheduled';

[User] I got an error: doctor information seems to be incorrect, since doctors shouldn’t be retrieved from the patients table. Can you fix the join so the doctor information comes from the correct table?

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, doc.first_name AS doctor_first_name, doc.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.doctors doc ON diag.doctor_id = doc.doctor_id
WHERE diag.diagnosis_code = 'hypertension' AND a.status = 'scheduled';

[User] Find all patients along with the number of unique diagnoses each has received. Only include patients who have at least two diagnoses.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, COUNT(DISTINCT d.diagnosis_id) AS num_diagnoses
FROM healthcare.patients p
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
GROUP BY p.patient_id, p.first_name, p.last_name
HAVING COUNT(DISTINCT d.diagnosis_id) >= 2;

[User] List all medications whose manufacturer field is not null.

[Assistant]
SELECT medication_id, medication_name, generic_name, manufacturer, ndc_code, description
FROM healthcare.medications
WHERE manufacturer IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )

[User] Count the number of events for each hour of the day based on the emitted_at timestamp.

[Assistant] SELECT EXTRACT(HOUR FROM emitted_at) AS event_hour, COUNT(*) AS event_count FROM web3.events GROUP BY event_hour ORDER BY event_hour;

[User] Actually, only show hours with more than 100 events.

[Assistant] SELECT EXTRACT(HOUR FROM emitted_at) AS event_hour, COUNT(*) AS event_count FROM web3.events GROUP BY event_hour HAVING COUNT(*) > 100 ORDER BY event_hour;

[User] For each contract, can you show the number of different types of events it has emitted along with the contract ID?

[Assistant] SELECT contract_id, COUNT(DISTINCT event_name) AS distinct_event_types FROM web3.events GROUP BY contract_id;

[User] For each event, display its event_id, the event_id of the previous event in the same transaction (if any), and the log_index of both events.

[Assistant]
SELECT curr.event_id   AS current_event_id,
       prev.event_id   AS previous_event_id,
       curr.log_index  AS current_log_index,
       prev.log_index  AS previous_log_index,
       curr.transaction_id
FROM web3.events curr
LEFT JOIN web3.events prev
  ON curr.transaction_id = prev.transaction_id
 AND curr.log_index = prev.log_index + 1;

[User] List the transaction IDs which have had more than one unique event emitted inside them.

[Assistant] SELECT transaction_id FROM web3.events GROUP BY transaction_id HAVING COUNT(DISTINCT event_name) > 1;

[User] Actually, can you also list the names of these unique events for each transaction ID?

[Assistant] SELECT transaction_id, STRING_AGG(DISTINCT event_name, ', ') AS unique_event_names FROM web3.events GROUP BY transaction_id HAVING COUNT(DISTINCT event_name) > 1;

[User] Can you find the contract that has emitted the most events, and show its contract ID along with the total number of events emitted?

[Assistant] SELECT contract_id, COUNT(*) AS total_events FROM web3.events GROUP BY contract_id ORDER BY total_events DESC LIMIT 1;

[User] Find all pairs of events that occurred in the same transaction but at different log indices, showing both event_ids, their event_names, the transaction_id, and each log_index.

[Assistant]
SELECT a.event_id AS event_id1,
       a.event_name AS event_name1,
       b.event_id AS event_id2,
       b.event_name AS event_name2,
       a.transaction_id,
       a.log_index AS log_index1,
       b.log_index AS log_index2
FROM web3.events a
JOIN web3.events b
  ON a.transaction_id = b.transaction_id
 AND a.log_index < b.log_index;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )

[User] Show me reviews from 'Expedia' that have an overall rating of 1 or 2.

[Assistant] SELECT review_id, property_id, guest_id, rating_overall, review_date, comment FROM hospitality_technology.reviews WHERE review_source = 'Expedia' AND rating_overall <= 2;

[User] Actually, only include those submitted in the second half of 2023.

[Assistant] SELECT review_id, property_id, guest_id, rating_overall, review_date, comment FROM hospitality_technology.reviews WHERE review_source = 'Expedia' AND rating_overall <= 2 AND review_date >= '2023-07-01' AND review_date < '2024-01-01';

[User] List public reviews whose comment contains the word 'slow'.

[Assistant] SELECT review_id, comment, review_date, rating_overall, property_id FROM hospitality_technology.reviews WHERE is_public = TRUE AND LOWER(comment) LIKE '%slow%';

[User] Also, only include reviews submitted for property 'P007'.

[Assistant] SELECT review_id, comment, review_date, rating_overall, property_id FROM hospitality_technology.reviews WHERE is_public = TRUE AND LOWER(comment) LIKE '%slow%' AND property_id = 'P007';

[User] Count reviews with an overall rating of 5 for each property.

[Assistant] SELECT property_id, COUNT(*) AS five_star_review_count FROM hospitality_technology.reviews WHERE rating_overall = 5 GROUP BY property_id;

[User] Now, only show properties with more than 10 five-star reviews.

[Assistant] SELECT property_id, COUNT(*) AS five_star_review_count FROM hospitality_technology.reviews WHERE rating_overall = 5 GROUP BY property_id HAVING COUNT(*) > 10;

[User] Sort the results by the count of reviews in descending order and limit to the top 5.

[Assistant] SELECT property_id, COUNT(*) AS five_star_review_count FROM hospitality_technology.reviews WHERE rating_overall = 5 GROUP BY property_id HAVING COUNT(*) > 10 ORDER BY five_star_review_count DESC LIMIT 5;

[User] Get each review with the next review date for the same guest.

[Assistant]
SELECT guest_id, review_id, review_date,
       LEAD(review_date) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_date
FROM hospitality_technology.reviews;

[User] Exclude entries where there's no next review.

[Assistant]
SELECT guest_id, review_id, review_date, next_review_date
FROM (
  SELECT guest_id, review_id, review_date,
         LEAD(review_date) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_date
  FROM hospitality_technology.reviews
) t
WHERE next_review_date IS NOT NULL;

[User] Now join the table to retrieve the comment of the next review as well.

[Assistant]
WITH sequenced AS (
  SELECT guest_id, review_id, review_date,
         LEAD(review_id) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_id,
         LEAD(review_date) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_date
  FROM hospitality_technology.reviews
)
SELECT s.guest_id,
       s.review_id,
       s.review_date,
       r2.review_id AS next_review_id,
       r2.review_date AS next_review_date,
       r2.comment AS next_comment
FROM sequenced s
JOIN hospitality_technology.reviews r2
  ON s.next_review_id = r2.review_id
WHERE s.next_review_id IS NOT NULL;

[User] List all review IDs, comments, and overall ratings for reviews submitted for property 'P123'.

[Assistant] SELECT review_id, comment, rating_overall FROM hospitality_technology.reviews WHERE property_id = 'P123';

[User] Filter this list to only include reviews with an overall rating of 3 or less and order by review date descending.

[Assistant] SELECT review_id, comment, rating_overall FROM hospitality_technology.reviews WHERE property_id = 'P123' AND rating_overall <= 3 ORDER BY review_date DESC;

[User] What is the average overall rating grouped by review_source?

[Assistant]
SELECT review_source, AVG(rating_overall) AS avg_overall_rating, COUNT(*) AS review_count
FROM hospitality_technology.reviews
GROUP BY review_source;

[User] Actually, exclude sources with fewer than 10 reviews.

[Assistant]
SELECT review_source, AVG(rating_overall) AS avg_overall_rating, COUNT(*) AS review_count
FROM hospitality_technology.reviews
GROUP BY review_source
HAVING COUNT(*) >= 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )

[User] List all posts where the content mentions 'meeting'.

[Assistant] SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%'

[User] Also, only include those posts that are public.

[Assistant] SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%' AND visibility = 'public'

[User] How many posts are currently marked as 'private' visibility?

[Assistant] SELECT COUNT(*) FROM social_media.posts WHERE visibility = 'private'

[User] List all posts created by user 'U789'.

[Assistant] SELECT post_id, content, created_at, media_type FROM social_media.posts WHERE user_id = 'U789'

[User] Only show me the posts that have a media type of 'image'.

[Assistant] SELECT post_id, content, created_at, media_type FROM social_media.posts WHERE user_id = 'U789' AND media_type = 'image'

[User] Also, filter these images to only include those created in May 2024.

[Assistant] SELECT post_id, content, created_at, media_type FROM social_media.posts WHERE user_id = 'U789' AND media_type = 'image' AND created_at BETWEEN '2024-05-01 00:00:00' AND '2024-05-31 23:59:59'

[User] Order these results by creation time, with the most recent first.

[Assistant] SELECT post_id, content, created_at, media_type FROM social_media.posts WHERE user_id = 'U789' AND media_type = 'image' AND created_at BETWEEN '2024-05-01 00:00:00' AND '2024-05-31 23:59:59' ORDER BY created_at DESC

[User] Show me all posts created between '2024-06-01' and '2024-06-30', showing post_id, content, and media_type.

[Assistant] SELECT post_id, content, media_type FROM social_media.posts WHERE created_at >= '2024-06-01' AND created_at < '2024-07-01';

[User] Add the visibility status and filter to only show posts where content is NOT NULL.

[Assistant] SELECT post_id, content, media_type, visibility FROM social_media.posts WHERE created_at >= '2024-06-01' AND created_at < '2024-07-01' AND content IS NOT NULL;

[User] Order the results by creation time descending and limit to the top 10.

[Assistant] SELECT post_id, content, media_type, visibility FROM social_media.posts WHERE created_at >= '2024-06-01' AND created_at < '2024-07-01' AND content IS NOT NULL ORDER BY created_at DESC LIMIT 10;

[User] I want to see each post along with the user's previous post and the time difference between them.

[Assistant]
SELECT p2.post_id AS current_post, p1.post_id AS previous_post, EXTRACT(EPOCH FROM (p2.created_at - p1.created_at))/60 AS diff_minutes
FROM social_media.posts p2
JOIN social_media.posts p1
  ON p2.user_id = p1.user_id
  AND p2.created_at > p1.created_at;

[User] Exclude any private posts and only include media_type = 'image'.

[Assistant]
SELECT p2.post_id AS current_post, p1.post_id AS previous_post, EXTRACT(EPOCH FROM (p2.created_at - p1.created_at))/60 AS diff_minutes
FROM social_media.posts p2
JOIN social_media.posts p1
  ON p2.user_id = p1.user_id
  AND p2.created_at > p1.created_at
WHERE p2.visibility = 'public'
  AND p1.visibility = 'public'
  AND p2.media_type = 'image'
  AND p1.media_type = 'image';

[User] Alias the time difference as diff_in_minutes and order by that difference descending.

[Assistant]
SELECT p2.post_id AS current_post, p1.post_id AS previous_post, EXTRACT(EPOCH FROM (p2.created_at - p1.created_at))/60 AS diff_in_minutes
FROM social_media.posts p2
JOIN social_media.posts p1
  ON p2.user_id = p1.user_id
  AND p2.created_at > p1.created_at
WHERE p2.visibility = 'public'
  AND p1.visibility = 'public'
  AND p2.media_type = 'image'
  AND p1.media_type = 'image'
ORDER BY diff_in_minutes DESC;

[User] Show me the count of posts per media_type for public posts.

[Assistant]
SELECT media_type, COUNT(*) AS post_count
FROM social_media.posts
WHERE visibility = 'public'
GROUP BY media_type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text PRIMARY KEY, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] List all users who currently have a 'pending' KYC status, showing their user ID and username.

[Assistant] SELECT u.user_id, u.username FROM users u JOIN kyc_audit k ON u.user_id = k.user_id WHERE k.status = 'pending';

[User] Show all trades that occurred after '2024-06-01', including the trade ID, quantity, price, and the name and symbol of the asset traded.

[Assistant] SELECT t.trade_id, t.quantity, t.price, a.name AS asset_name, a.symbol AS asset_symbol FROM trades t JOIN assets a ON t.asset_id = a.asset_id WHERE t.traded_at > '2024-06-01';

[User] Also include the username of the buyer for each trade.

[Assistant] SELECT t.trade_id, t.quantity, t.price, a.name AS asset_name, a.symbol AS asset_symbol, bu.username AS buyer_username FROM trades t JOIN assets a ON t.asset_id = a.asset_id JOIN users bu ON t.buyer_id = bu.user_id WHERE t.traded_at > '2024-06-01';

[User] Instead of listing individual trades, calculate the total traded value (quantity * price) for each asset traded after '2024-06-01', showing the asset name and symbol and the total value.

[Assistant] SELECT a.name AS asset_name, a.symbol AS asset_symbol, SUM(t.quantity * t.price) AS total_traded_value FROM trades t JOIN assets a ON t.asset_id = a.asset_id WHERE t.traded_at > '2024-06-01' GROUP BY a.asset_id, a.name, a.symbol;

[User] Only show assets where the total traded value is greater than 1000.

[Assistant] SELECT a.name AS asset_name, a.symbol AS asset_symbol, SUM(t.quantity * t.price) AS total_traded_value FROM trades t JOIN assets a ON t.asset_id = a.asset_id WHERE t.traded_at > '2024-06-01' GROUP BY a.asset_id, a.name, a.symbol HAVING SUM(t.quantity * t.price) > 1000;

[User] List users and their latest wallet address if they have one, ordered by username.

[Assistant] SELECT u.username, w.address FROM users u JOIN wallets w ON u.user_id = w.user_id WHERE w.created_at = (SELECT MAX(w2.created_at) FROM wallets w2 WHERE w2.user_id = u.user_id) ORDER BY u.username;

[User] Filter that list to only include users created after '2023-01-01'.

[Assistant] SELECT u.username, w.address FROM users u JOIN wallets w ON u.user_id = w.user_id WHERE w.created_at = (SELECT MAX(w2.created_at) FROM wallets w2 WHERE w2.user_id = u.user_id) AND u.created_at > '2023-01-01' ORDER BY u.username;

[User] Show me each completed order with order_id, the username of the user who placed it, asset_id, quantity, and price.

[Assistant]
SELECT
  o.order_id,
  u.username,
  o.asset_id,
  o.quantity,
  o.price
FROM trading_platform.orders o
JOIN trading_platform.users u ON o.user_id = u.user_id
WHERE o.status = 'completed';

[User] Also include the total executed quantity from trades for each order.

[Assistant]
SELECT
  o.order_id,
  u.username,
  o.asset_id,
  o.quantity,
  o.price,
  COALESCE(t.total_executed, 0) AS executed_quantity
FROM trading_platform.orders o
JOIN trading_platform.users u ON o.user_id = u.user_id
LEFT JOIN (
  SELECT order_id, SUM(quantity) AS total_executed
  FROM trading_platform.trades
  GROUP BY order_id
) t ON o.order_id = t.order_id
WHERE o.status = 'completed';

[User] Only include orders where some trades have occurred and calculate remaining_unfilled as order.quantity minus executed_quantity.

[Assistant]
SELECT
  o.order_id,
  u.username,
  o.asset_id,
  o.quantity,
  t.total_executed AS executed_quantity,
  (o.quantity - t.total_executed) AS remaining_unfilled
FROM trading_platform.orders o
JOIN trading_platform.users u ON o.user_id = u.user_id
JOIN (
  SELECT order_id, SUM(quantity) AS total_executed
  FROM trading_platform.trades
  GROUP BY order_id
) t ON o.order_id = t.order_id
WHERE o.status = 'completed'
  AND t.total_executed > 0;

[User] Limit to the top 5 orders by highest remaining_unfilled quantity.

[Assistant]
SELECT
  o.order_id,
  u.username,
  o.asset_id,
  o.quantity,
  t.total_executed AS executed_quantity,
  (o.quantity - t.total_executed) AS remaining_unfilled
FROM trading_platform.orders o
JOIN trading_platform.users u ON o.user_id = u.user_id
JOIN (
  SELECT order_id, SUM(quantity) AS total_executed
  FROM trading_platform.trades
  GROUP BY order_id
) t ON o.order_id = t.order_id
WHERE o.status = 'completed'
ORDER BY (o.quantity - t.total_executed) DESC
LIMIT 5;

[User] For each user, show their user_id, username, and the total number of trades they have participated in, counting both as buyer and as seller.

[Assistant]
SELECT
  u.user_id,
  u.username,
  COALESCE(b.buy_count, 0) + COALESCE(s.sell_count, 0) AS total_trades
FROM trading_platform.users u
LEFT JOIN (
  SELECT buyer_id AS user_id, COUNT(*) AS buy_count
  FROM trading_platform.trades
  GROUP BY buyer_id
) b ON u.user_id = b.user_id
LEFT JOIN (
  SELECT seller_id AS user_id, COUNT(*) AS sell_count
  FROM trading_platform.trades
  GROUP BY seller_id
) s ON u.user_id = s.user_id;

[User] Exclude users with zero trades and only include those whose total_trades is at least 5.

[Assistant]
SELECT
  u.user_id,
  u.username,
  COALESCE(b.buy_count, 0) + COALESCE(s.sell_count, 0) AS total_trades
FROM trading_platform.users u
LEFT JOIN (
  SELECT buyer_id AS user_id, COUNT(*) AS buy_count
  FROM trading_platform.trades
  GROUP BY buyer_id
) b ON u.user_id = b.user_id
LEFT JOIN (
  SELECT seller_id AS user_id, COUNT(*) AS sell_count
  FROM trading_platform.trades
  GROUP BY seller_id
) s ON u.user_id = s.user_id
WHERE (COALESCE(b.buy_count, 0) + COALESCE(s.sell_count, 0)) >= 5;

[User] List each wallet with its wallet_id, user_id, and the total amount of unspent UTXOs associated with that wallet.

[Assistant]
SELECT
  w.wallet_id,
  w.user_id,
  COALESCE(SUM(u.amount), 0) AS unspent_total
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address
  AND u.spent = false
GROUP BY w.wallet_id, w.user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )

[User] List all policies that have a coverage limit greater than 750000 and a premium amount greater than 1000. Show the policy number, product ID, coverage limit, and premium amount.

[Assistant]
SELECT
  policy_number,
  product_id,
  coverage_limit,
  premium_amount
FROM insurance.policies
WHERE
  coverage_limit > 750000
  AND premium_amount > 1000;

[User] Okay, now only include policies that are currently 'Active' and have been active for at least 90 days.

[Assistant]
SELECT
  policy_number,
  product_id,
  coverage_limit,
  premium_amount
FROM insurance.policies
WHERE
  coverage_limit > 750000
  AND premium_amount > 1000
  AND status = 'Active'
  AND start_date <= CURRENT_DATE - INTERVAL '90 days';

[User] Instead of listing policies, count how many such active policies exist for each product ID. Show the product ID and the count, but only for products that have more than 5 such policies.

[Assistant]
SELECT
  product_id,
  COUNT(policy_id) AS active_policy_count
FROM insurance.policies
WHERE
  coverage_limit > 750000
  AND premium_amount > 1000
  AND status = 'Active'
  AND start_date <= CURRENT_DATE - INTERVAL '90 days'
GROUP BY
  product_id
HAVING
  COUNT(policy_id) > 5
ORDER BY
  active_policy_count DESC;

[User] Great. For those product IDs, also include the total premium amount across all policies included in the count. Order by the total premium amount descending.

[Assistant]
SELECT
  product_id,
  COUNT(policy_id) AS active_policy_count,
  SUM(premium_amount) AS total_premium
FROM insurance.policies
WHERE
  coverage_limit > 750000
  AND premium_amount > 1000
  AND status = 'Active'
  AND start_date <= CURRENT_DATE - INTERVAL '90 days'
GROUP BY
  product_id
HAVING
  COUNT(policy_id) > 5
ORDER BY
  total_premium DESC;

[User] Show all policies that started in 2024, including the policy_id, customer_id, and start_date. Order the results by start_date ascending.

[Assistant]
SELECT policy_id, customer_id, start_date
FROM insurance.policies
WHERE start_date >= '2024-01-01' AND start_date < '2025-01-01'
ORDER BY start_date ASC;

[User] Also, include the status of each policy and only show those with premium_amount over 3000.

[Assistant]
SELECT policy_id, customer_id, start_date, status
FROM insurance.policies
WHERE start_date >= '2024-01-01' AND start_date < '2025-01-01'
  AND premium_amount > 3000
ORDER BY start_date ASC;

[User] Show me all pairs of active policies for the same customer where their coverage periods overlap. Return customer_id, policy1_id, policy2_id, overlap_start, overlap_end.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)   AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.policy_id < p2.policy_id
 AND p1.status = 'active'
 AND p2.status = 'active'
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date;

[User] I only want overlaps longer than 30 days and display the overlap days as overlap_days.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)   AS overlap_end,
       (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.policy_id < p2.policy_id
 AND p1.status = 'active'
 AND p2.status = 'active'
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
HAVING (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) > 30;

[User] Order the results by overlap_days descending and limit to top 10.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)   AS overlap_end,
       (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.policy_id < p2.policy_id
 AND p1.status = 'active'
 AND p2.status = 'active'
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
GROUP BY p1.customer_id, p1.policy_id, p2.policy_id
HAVING (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) > 30
ORDER BY overlap_days DESC
LIMIT 10;

[User] List all replacement policies where a customer received a new policy starting the day after their previous policy was cancelled. Return customer_id, original_policy_id, original_cancellation_date, new_policy_id, new_start_date.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day';

[User] Now include the premium_amount difference as premium_diff and only show cases where the new policy's premium is higher.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date,
       (nw.premium_amount - orig.premium_amount) AS premium_diff
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day'
WHERE nw.premium_amount > orig.premium_amount;

[User] List pairs of policies for the same customer that have the same premium amount but different coverage limits. Show customer ID, policy ID 1, policy ID 2, the premium amount, and the two coverage limits.

[Assistant] SELECT T1.customer_id, T1.policy_id AS policy1_id, T2.policy_id AS policy2_id, T1.premium_amount, T1.coverage_limit AS coverage_limit1, T2.coverage_limit AS coverage_limit2 FROM insurance.policies AS T1 JOIN insurance.policies AS T2 ON T1.customer_id = T2.customer_id AND T1.premium_amount = T2.premium_amount AND T1.coverage_limit <> T2.coverage_limit AND T1.policy_id < T2.policy_id;

[User] Also, only include pairs where both policies are currently active.

[Assistant] SELECT T1.customer_id, T1.policy_id AS policy1_id, T2.policy_id AS policy2_id, T1.premium_amount, T1.coverage_limit AS coverage_limit1, T2.coverage_limit AS coverage_limit2 FROM insurance.policies AS T1 JOIN insurance.policies AS T2 ON T1.customer_id = T2.customer_id AND T1.premium_amount = T2.premium_amount AND T1.coverage_limit <> T2.coverage_limit AND T1.policy_id < T2.policy_id WHERE T1.status = 'active' AND T2.status = 'active';

[User] I need to find all pairs of policies for each customer whose coverage periods overlap. Show customer_id, the two policy_ids for each overlapping pair.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
  AND p1.policy_id < p2.policy_id
  AND p1.start_date <= p2.end_date
  AND p2.start_date <= p1.end_date;

[User] Can you also include the number of days of overlap between the two policies as overlap_days?

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
  AND p1.policy_id < p2.policy_id
  AND p1.start_date <= p2.end_date
  AND p2.start_date <= p1.end_date;

[User] Actually, restrict the results to only include pairs where both policies are currently active.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
  AND p1.policy_id < p2.policy_id
  AND p1.start_date <= p2.end_date
  AND p2.start_date <= p1.end_date
WHERE p1.status = 'active'
  AND p2.status = 'active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] Can you show me all user IDs that have both email and push notifications disabled, along with whether their profile is set to private?

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = false AND push_notifications_enabled = false;

[User] I also want to see the last time they updated their settings.

[Assistant] SELECT user_id, private_profile, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = false AND push_notifications_enabled = false;

[User] Show the user IDs of all users whose theme is set to 'blue'.

[Assistant] SELECT user_id FROM social_media.user_settings WHERE theme = 'blue';

[User] Can you show me the user IDs and their theme settings for all users who have enabled email notifications and have updated their settings in 2024?

[Assistant] SELECT user_id, theme FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND updated_at >= '2024-01-01';

[User] What if I also want to see if their profile is private or not?

[Assistant] SELECT user_id, theme, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND updated_at >= '2024-01-01';

[User] Actually, I want to see users who have both email AND push notifications enabled.

[Assistant] SELECT user_id, theme, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND push_notifications_enabled = TRUE AND updated_at >= '2024-01-01';

[User] Now, limit the results to users whose theme is 'light' only.

[Assistant] SELECT user_id, theme, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND push_notifications_enabled = TRUE AND theme = 'light' AND updated_at >= '2024-01-01';

[User] Show me all user IDs who changed their profile settings after June 1, 2024.

[Assistant] SELECT user_id FROM social_media.user_settings WHERE updated_at > '2024-06-01';

[User] Which users have disabled both email and push notifications? Please provide their user IDs and whether their profiles are private.

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = FALSE;

[User] Also, only include those users who have updated their settings in the last 60 days.

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = FALSE AND updated_at >= NOW() - INTERVAL '60 days';

[User] List the user IDs, theme, and updated_at for users who have disabled email notifications, enabled push notifications, and have a private profile.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE;

[User] Now, only include those whose theme is set to 'light'.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE AND theme = 'light';

[User] Order these results by the updated_at timestamp in descending order.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE AND theme = 'light' ORDER BY updated_at DESC;

[User] Limit the results to the top 5.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE AND theme = 'light' ORDER BY updated_at DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.wallets ( wallet_id.text, user_id.text, address_id.text, private_key.text )

[User] Show me all wallet addresses that belong to user_id 'U12345'.

[Assistant] SELECT address_id FROM blockchain.wallets WHERE user_id = 'U12345';

[User] Now join this with another table to show the private_key for these addresses.

[Assistant] SELECT w.address_id, w.private_key FROM blockchain.wallets w WHERE w.user_id = 'U12345';

[User] Show me all wallet addresses along with their private keys for users who have more than 3 wallets.

[Assistant] SELECT w1.address_id, w1.private_key FROM blockchain.wallets w1 INNER JOIN (SELECT user_id FROM blockchain.wallets GROUP BY user_id HAVING COUNT(*) > 3) w2 ON w1.user_id = w2.user_id;

[User] Now, filter these results to only show wallets where the private_key starts with '0x1'.

[Assistant] SELECT w1.address_id, w1.private_key FROM blockchain.wallets w1 INNER JOIN (SELECT user_id FROM blockchain.wallets GROUP BY user_id HAVING COUNT(*) > 3) w2 ON w1.user_id = w2.user_id WHERE w1.private_key LIKE '0x1%';

[User] Show me the top 5 users with the most wallet addresses, along with the count of their wallets.

[Assistant] SELECT user_id, COUNT(wallet_id) AS wallet_count FROM blockchain.wallets WHERE user_id IS NOT NULL GROUP BY user_id ORDER BY wallet_count DESC LIMIT 5;

[User] Now include the earliest created wallet address for each of these top 5 users.

[Assistant] Note: The wallets table doesn't have a creation timestamp column. Without this information, we cannot determine the earliest created wallet. Please provide a table with creation timestamps if you need this analysis.

[User] Then just show me these top 5 users with their wallet counts and the first wallet_id alphabetically for each user.

[Assistant] SELECT user_id, COUNT(wallet_id) AS wallet_count, MIN(wallet_id) AS first_wallet_id FROM blockchain.wallets WHERE user_id IS NOT NULL GROUP BY user_id ORDER BY wallet_count DESC LIMIT 5;

[User] Show me the username and email of all users who own at least one wallet.

[Assistant] SELECT DISTINCT T1.username, T1.email FROM blockchain.users AS T1 JOIN blockchain.wallets AS T2 ON T1.user_id = T2.user_id;

[User] List all users whose password hash contains the substring 'abc'.

[Assistant] SELECT user_id, username, password_hash FROM blockchain.users WHERE password_hash LIKE '%abc%';

[User] Also include their email address.

[Assistant] SELECT user_id, username, password_hash, email FROM blockchain.users WHERE password_hash LIKE '%abc%';

[User] Filter to only show users whose username does *not* contain 'test'.

[Assistant] SELECT user_id, username, password_hash, email FROM blockchain.users WHERE password_hash LIKE '%abc%' AND username NOT LIKE '%test%';

[User] Show me all wallet addresses along with their public keys and balances, but only for wallets that have a balance greater than 1000.

[Assistant] SELECT w.address_id, a.public_key, a.balance FROM blockchain.wallets w JOIN blockchain.addresses a ON w.address_id = a.address_id WHERE a.balance > 1000;

[User] Now filter these results to only show wallets where the private_key starts with '0x1'.

[Assistant] SELECT w.address_id, a.public_key, a.balance FROM blockchain.wallets w JOIN blockchain.addresses a ON w.address_id = a.address_id WHERE a.balance > 1000 AND w.private_key LIKE '0x1%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )

[User] Get all pairs of locations in the same city, showing both location IDs, names, and the shared city.

[Assistant]
SELECT l1.location_id AS location1_id, l1.name AS location1_name,
       l2.location_id AS location2_id, l2.name AS location2_name,
       l1.city
FROM transportation.locations l1
JOIN transportation.locations l2
  ON l1.city = l2.city
 AND l1.location_id < l2.location_id;

[User] List all pairs of locations within the same state_province where the two locations are of different types. For each pair, show the first location's name, type, city, and the second location's name, type, city, and their shared state_province.

[Assistant]
SELECT l1.name AS name1, l1.type AS type1, l1.city AS city1, l2.name AS name2, l2.type AS type2, l2.city AS city2, l1.state_province
FROM transportation.locations l1
JOIN transportation.locations l2
  ON l1.state_province = l2.state_province
 AND l1.location_id < l2.location_id
 AND l1.type <> l2.type;

[User] Now restrict the results to only include pairs where both locations are in the city of 'Houston'.

[Assistant]
SELECT l1.name AS name1, l1.type AS type1, l1.city AS city1, l2.name AS name2, l2.type AS type2, l2.city AS city2, l1.state_province
FROM transportation.locations l1
JOIN transportation.locations l2
  ON l1.state_province = l2.state_province
 AND l1.city = 'Houston'
 AND l2.city = 'Houston'
 AND l1.location_id < l2.location_id
 AND l1.type <> l2.type;

[User] Show all locations in 'Texas' with their name, city, and type.

[Assistant]
SELECT location_id, name, city, type
FROM transportation.locations
WHERE state_province = 'Texas';

[User] Actually, only include locations in 'Houston' city.

[Assistant]
SELECT location_id, name, city, type
FROM transportation.locations
WHERE state_province = 'Texas'
  AND city = 'Houston';

[User] I want to also see their postal codes.

[Assistant]
SELECT location_id, name, city, type, postal_code
FROM transportation.locations
WHERE state_province = 'Texas'
  AND city = 'Houston';

[User] Please order the results by name in ascending order.

[Assistant]
SELECT location_id, name, city, type, postal_code
FROM transportation.locations
WHERE state_province = 'Texas'
  AND city = 'Houston'
ORDER BY name ASC;

[User] Which locations lack a postal code? For each, display the name, type, city, and state_province.

[Assistant]
SELECT name, type, city, state_province
FROM transportation.locations
WHERE postal_code IS NULL;

[User] Also show the country and order the results by city in ascending order.

[Assistant]
SELECT name, type, city, state_province, country
FROM transportation.locations
WHERE postal_code IS NULL
ORDER BY city ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] Show me a list of players and, for each, list all the different games where they have acquired items. Also include the number of unique item types they've acquired per game.

[Assistant]
SELECT p.player_id, p.username, g.title AS game_title, COUNT(DISTINCT i.item_type) AS unique_item_types
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.players p ON pi.player_id = p.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
GROUP BY p.player_id, p.username, g.title;

[User] Can you show only the player/game combinations where at least 2 unique item types were acquired?

[Assistant]
SELECT p.player_id, p.username, g.title AS game_title, COUNT(DISTINCT i.item_type) AS unique_item_types
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.players p ON pi.player_id = p.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
GROUP BY p.player_id, p.username, g.title
HAVING COUNT(DISTINCT i.item_type) >= 2;

[User] I got too many results. Can you list only players who registered after January 1, 2023?

[Assistant]
SELECT p.player_id, p.username, g.title AS game_title, COUNT(DISTINCT i.item_type) AS unique_item_types
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.players p ON pi.player_id = p.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE p.registration_date > '2023-01-01'
GROUP BY p.player_id, p.username, g.title
HAVING COUNT(DISTINCT i.item_type) >= 2;

[User] Show me each developer's name and the number of different games they have published on each platform.

[Assistant]
SELECT d.name AS developer_name, g.platform, COUNT(DISTINCT g.game_id) AS game_count
FROM gaming_technology.developers d
JOIN gaming_technology.games g ON d.developer_id = g.developer_id
GROUP BY d.name, g.platform;

[User] I only want to include platforms where the developer has published at least 2 games.

[Assistant]
SELECT d.name AS developer_name, g.platform, COUNT(DISTINCT g.game_id) AS game_count
FROM gaming_technology.developers d
JOIN gaming_technology.games g ON d.developer_id = g.developer_id
GROUP BY d.name, g.platform
HAVING COUNT(DISTINCT g.game_id) >= 2;

[User] Can you also return the developer's country for each result?

[Assistant]
SELECT d.name AS developer_name, d.country, g.platform, COUNT(DISTINCT g.game_id) AS game_count
FROM gaming_technology.developers d
JOIN gaming_technology.games g ON d.developer_id = g.developer_id
GROUP BY d.name, d.country, g.platform
HAVING COUNT(DISTINCT g.game_id) >= 2;

[User] Could you get the total spend on rare items for each player along with the player's username?

[Assistant]
SELECT p.player_id,
       p.username,
       SUM(pi.quantity * i.cost_amount) AS total_spend
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.players p ON pi.player_id = p.player_id
WHERE i.rarity = 'rare'
GROUP BY p.player_id, p.username;

[User] Actually, limit to players who registered after 2022-01-01 and include their country_code.

[Assistant]
SELECT p.player_id,
       p.username,
       p.country_code,
       SUM(pi.quantity * i.cost_amount) AS total_spend
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.players p ON pi.player_id = p.player_id
WHERE i.rarity = 'rare'
  AND p.registration_date > '2022-01-01'
GROUP BY p.player_id, p.username, p.country_code;

[User] Also, only consider items from games on the 'PC' platform and order the results by total_spend descending.

[Assistant]
SELECT p.player_id,
       p.username,
       p.country_code,
       SUM(pi.quantity * i.cost_amount) AS total_spend
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.players p ON pi.player_id = p.player_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE i.rarity = 'rare'
  AND p.registration_date > '2022-01-01'
  AND g.platform = 'PC'
GROUP BY p.player_id, p.username, p.country_code
ORDER BY total_spend DESC;

[User] Great, but show only the top 10 players.

[Assistant]
SELECT p.player_id,
       p.username,
       p.country_code,
       SUM(pi.quantity * i.cost_amount) AS total_spend
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.players p ON pi.player_id = p.player_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE i.rarity = 'rare'
  AND p.registration_date > '2022-01-01'
  AND g.platform = 'PC'
GROUP BY p.player_id, p.username, p.country_code
ORDER BY total_spend DESC
LIMIT 10;

[User] List each player along with the number of achievements they have unlocked in game 'SuperQuest'.

[Assistant]
SELECT p.player_id,
       p.username,
       COUNT(pa.achievement_id) AS achievement_count
FROM gaming_technology.player_achievements pa
JOIN gaming_technology.players p ON pa.player_id = p.player_id
JOIN gaming_technology.achievements a ON pa.achievement_id = a.achievement_id
JOIN gaming_technology.games g ON a.game_id = g.game_id
WHERE g.title = 'SuperQuest'
GROUP BY p.player_id, p.username;

[User] Actually, I only want players who unlocked at least 5 achievements and also show their registration_date.

[Assistant]
SELECT p.player_id,
       p.username,
       p.registration_date,
       COUNT(pa.achievement_id) AS achievement_count
FROM gaming_technology.player_achievements pa
JOIN gaming_technology.players p ON pa.player_id = p.player_id
JOIN gaming_technology.achievements a ON pa.achievement_id = a.achievement_id
JOIN gaming_technology.games g ON a.game_id = g.game_id
WHERE g.title = 'SuperQuest'
GROUP BY p.player_id, p.username, p.registration_date
HAVING COUNT(pa.achievement_id) >= 5;

[User] Also include the timestamp of their earliest unlocked achievement for that game.

[Assistant]
SELECT p.player_id,
       p.username,
       p.registration_date,
       COUNT(pa.achievement_id) AS achievement_count,
       MIN(pa.unlocked_at) AS first_unlocked_at
FROM gaming_technology.player_achievements pa
JOIN gaming_technology.players p ON pa.player_id = p.player_id
JOIN gaming_technology.achievements a ON pa.achievement_id = a.achievement_id
JOIN gaming_technology.games g ON a.game_id = g.game_id
WHERE g.title = 'SuperQuest'
GROUP BY p.player_id, p.username, p.registration_date
HAVING COUNT(pa.achievement_id) >= 5;

[User] Give me each server's name, the region, and the maximum number of players that have been connected at once.

[Assistant]
SELECT s.server_id, s.server_name, s.region, MAX(s.current_players) AS max_players_seen
FROM gaming_technology.servers s
GROUP BY s.server_id, s.server_name, s.region;

[User] Could you also include the associated game title for each server?

[Assistant]
SELECT s.server_id, s.server_name, s.region, g.title AS game_title, MAX(s.current_players) AS max_players_seen
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
GROUP BY s.server_id, s.server_name, s.region, g.title;

[User] Now, can you show only servers where the max number of players ever connected exceeded 20?

[Assistant]
SELECT s.server_id, s.server_name, s.region, g.title AS game_title, MAX(s.current_players) AS max_players_seen
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
GROUP BY s.server_id, s.server_name, s.region, g.title
HAVING MAX(s.current_players) > 20;

[User] List all players and the number of distinct games they have grabbed in-game items from, as well as the name of each game.

[Assistant]
SELECT p.player_id, p.username, g.game_id, g.title, COUNT(DISTINCT pi.item_id) AS distinct_items_acquired
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
GROUP BY p.player_id, p.username, g.game_id, g.title;

[User] Could you only show players who have grabbed items from more than one game?

[Assistant]
SELECT p.player_id, p.username, COUNT(DISTINCT g.game_id) AS games_with_items
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
GROUP BY p.player_id, p.username
HAVING COUNT(DISTINCT g.game_id) > 1;

[User] Can you also include the total quantity of all items these players have from each game?

[Assistant]
SELECT p.player_id, p.username, g.game_id, g.title, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
GROUP BY p.player_id, p.username, g.game_id, g.title
HAVING COUNT(DISTINCT g.game_id) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)

[User] I want to see all time entries where the description contains the word 'draft' and that have not been billed yet.

[Assistant]
SELECT *
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false;

[User] Only include entries that were logged in June 2024.

[Assistant]
SELECT *
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false
  AND date_worked BETWEEN '2024-06-01' AND '2024-06-30';

[User] Now only show entries that are billable and where hours_spent is greater than 2.

[Assistant]
SELECT *
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false
  AND is_billable = true
  AND date_worked BETWEEN '2024-06-01' AND '2024-06-30'
  AND hours_spent > 2;

[User] Please only include the entry_id, lawyer_id, date_worked, and hours_spent in the output.

[Assistant]
SELECT entry_id, lawyer_id, date_worked, hours_spent
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false
  AND is_billable = true
  AND date_worked BETWEEN '2024-06-01' AND '2024-06-30'
  AND hours_spent > 2;

[User] Get me all unbilled billable time entries with their entry_id, case_id, lawyer_id, hours_spent, and billing_rate.

[Assistant]
SELECT entry_id,
       case_id,
       lawyer_id,
       hours_spent,
       billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE;

[User] Actually, I only want entries for lawyer 'lawyer_123'.

[Assistant]
SELECT entry_id,
       case_id,
       lawyer_id,
       hours_spent,
       billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND lawyer_id = 'lawyer_123';

[User] Also, sort the results by hours_spent in descending order.

[Assistant]
SELECT entry_id,
       case_id,
       lawyer_id,
       hours_spent,
       billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND lawyer_id = 'lawyer_123'
ORDER BY hours_spent DESC;

[User] Show me all pairs of time entries made by the same lawyer on the same date. Include both entry IDs, lawyer_id, and date_worked.

[Assistant]
SELECT t1.lawyer_id, t1.date_worked, t1.entry_id AS entry_id_1, t2.entry_id AS entry_id_2
FROM legal_services.time_entries t1
JOIN legal_services.time_entries t2
  ON t1.lawyer_id = t2.lawyer_id
  AND t1.date_worked = t2.date_worked
WHERE t1.entry_id < t2.entry_id;

[User] Actually, only include pairs where both entries are billable.

[Assistant]
SELECT t1.lawyer_id, t1.date_worked, t1.entry_id AS entry_id_1, t2.entry_id AS entry_id_2
FROM legal_services.time_entries t1
JOIN legal_services.time_entries t2
  ON t1.lawyer_id = t2.lawyer_id
  AND t1.date_worked = t2.date_worked
WHERE t1.entry_id < t2.entry_id
  AND t1.is_billable = true
  AND t2.is_billable = true;

[User] Also, ensure that the two entries have different hours_spent values.

[Assistant]
SELECT t1.lawyer_id, t1.date_worked, t1.entry_id AS entry_id_1, t2.entry_id AS entry_id_2
FROM legal_services.time_entries t1
JOIN legal_services.time_entries t2
  ON t1.lawyer_id = t2.lawyer_id
  AND t1.date_worked = t2.date_worked
WHERE t1.entry_id < t2.entry_id
  AND t1.is_billable = true
  AND t2.is_billable = true
  AND t1.hours_spent <> t2.hours_spent;

[User] Show me all time entries from the last 90 days, including the entry description, hours spent, the name of the case, and the name of the client.

[Assistant] SELECT T1.description, T1.hours_spent, T2.case_name, T3.first_name, T3.last_name FROM legal_services.time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id JOIN clients AS T3 ON T2.client_id = T3.client_id WHERE T1.date_worked >= CURRENT_DATE - INTERVAL '90 days';

[User] Calculate the total billable hours spent by each lawyer for entries in March 2024.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2024-03-01' AND '2024-03-31'
GROUP BY lawyer_id;

[User] Show me the total hours spent by each lawyer on billable time entries in 2024.

[Assistant]
SELECT
  lawyer_id,
  SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND EXTRACT(YEAR FROM date_worked) = 2024
GROUP BY lawyer_id;

[User] Actually, only include entries that have not yet been billed.

[Assistant]
SELECT
  lawyer_id,
  SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND EXTRACT(YEAR FROM date_worked) = 2024
GROUP BY lawyer_id;

[User] And restrict this to entries recorded after June 30, 2024.

[Assistant]
SELECT
  lawyer_id,
  SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND date_worked > '2024-06-30'
  AND EXTRACT(YEAR FROM date_worked) = 2024
GROUP BY lawyer_id;

[User] Finally, order the results by total_hours descending.

[Assistant]
SELECT
  lawyer_id,
  SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND date_worked > '2024-06-30'
  AND EXTRACT(YEAR FROM date_worked) = 2024
GROUP BY lawyer_id
ORDER BY total_hours DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )

[User] Find pairs of citizens who have the same last name but different national_id_number.

[Assistant]
SELECT c1.citizen_id AS citizen_id_1, c1.first_name AS first_name_1, c1.last_name AS last_name_1, c1.national_id_number AS national_id_1, c2.citizen_id AS citizen_id_2, c2.first_name AS first_name_2, c2.last_name AS last_name_2, c2.national_id_number AS national_id_2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.last_name = c2.last_name
  AND c1.national_id_number <> c2.national_id_number
  AND c1.citizen_id < c2.citizen_id;

[User] Actually, only include pairs where both citizens are verified.

[Assistant]
SELECT c1.citizen_id AS citizen_id_1, c1.first_name AS first_name_1, c1.last_name AS last_name_1, c1.national_id_number AS national_id_1, c2.citizen_id AS citizen_id_2, c2.first_name AS first_name_2, c2.last_name AS last_name_2, c2.national_id_number AS national_id_2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.last_name = c2.last_name
  AND c1.national_id_number <> c2.national_id_number
  AND c1.is_verified = TRUE
  AND c2.is_verified = TRUE
  AND c1.citizen_id < c2.citizen_id;

[User] How many citizens are there in each gender?

[Assistant]
SELECT gender, COUNT(*) AS citizen_count
FROM government_services.citizens
GROUP BY gender;

[User] Filter to only include genders with more than 200 citizens.

[Assistant]
SELECT gender, COUNT(*) AS citizen_count
FROM government_services.citizens
GROUP BY gender
HAVING COUNT(*) > 200;

[User] Also show the most recent registration date for each gender.

[Assistant]
SELECT gender, COUNT(*) AS citizen_count, MAX(registration_date) AS latest_registration
FROM government_services.citizens
GROUP BY gender
HAVING COUNT(*) > 200;

[User] Order the results by citizen_count in descending order and limit to top 2.

[Assistant]
SELECT gender, COUNT(*) AS citizen_count, MAX(registration_date) AS latest_registration
FROM government_services.citizens
GROUP BY gender
HAVING COUNT(*) > 200
ORDER BY citizen_count DESC
LIMIT 2;

[User] Retrieve each gender and the count of verified citizens born before 1990.

[Assistant]
SELECT gender,
       COUNT(*) AS citizen_count
FROM government_services.citizens
WHERE is_verified = TRUE
  AND date_of_birth < '1990-01-01'
GROUP BY gender;

[User] Now only include genders with more than 100 such citizens.

[Assistant]
SELECT gender,
       COUNT(*) AS citizen_count
FROM government_services.citizens
WHERE is_verified = TRUE
  AND date_of_birth < '1990-01-01'
GROUP BY gender
HAVING COUNT(*) > 100;

[User] Also show the average age of these citizens as of today.

[Assistant]
SELECT gender,
       COUNT(*) AS citizen_count,
       AVG(EXTRACT(YEAR FROM age(CURRENT_DATE, date_of_birth))) AS avg_age
FROM government_services.citizens
WHERE is_verified = TRUE
  AND date_of_birth < '1990-01-01'
GROUP BY gender
HAVING COUNT(*) > 100;

[User] Order results by the citizen count descending.

[Assistant]
SELECT gender,
       COUNT(*) AS citizen_count,
       AVG(EXTRACT(YEAR FROM age(CURRENT_DATE, date_of_birth))) AS avg_age
FROM government_services.citizens
WHERE is_verified = TRUE
  AND date_of_birth < '1990-01-01'
GROUP BY gender
HAVING COUNT(*) > 100
ORDER BY citizen_count DESC;

[User] List all pairs of citizens who registered on the same date. Include each citizen's full name and the shared registration date.

[Assistant]
SELECT c1.first_name || ' ' || c1.last_name AS full_name_1,
       c2.first_name || ' ' || c2.last_name AS full_name_2,
       DATE(c1.registration_date) AS registration_date
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON DATE(c1.registration_date) = DATE(c2.registration_date)
  AND c1.citizen_id < c2.citizen_id;

[User] Find pairs of citizens who share the same gender but registered in different years. Show each citizen's first and last name along with their registration year.

[Assistant]
SELECT c1.first_name AS first_name_1,
       c1.last_name  AS last_name_1,
       EXTRACT(YEAR FROM c1.registration_date) AS reg_year_1,
       c2.first_name AS first_name_2,
       c2.last_name  AS last_name_2,
       EXTRACT(YEAR FROM c2.registration_date) AS reg_year_2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.gender = c2.gender
 AND EXTRACT(YEAR FROM c1.registration_date) <> EXTRACT(YEAR FROM c2.registration_date)
 AND c1.citizen_id < c2.citizen_id;

[User] Exclude any pairs where either citizen is not verified.

[Assistant]
SELECT c1.first_name AS first_name_1,
       c1.last_name  AS last_name_1,
       EXTRACT(YEAR FROM c1.registration_date) AS reg_year_1,
       c2.first_name AS first_name_2,
       c2.last_name  AS last_name_2,
       EXTRACT(YEAR FROM c2.registration_date) AS reg_year_2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.gender = c2.gender
 AND EXTRACT(YEAR FROM c1.registration_date) <> EXTRACT(YEAR FROM c2.registration_date)
 AND c1.citizen_id < c2.citizen_id
WHERE c1.is_verified = TRUE
  AND c2.is_verified = TRUE;

[User] Find all male-female citizen pairs born in the same year. Display the male's full name, the female's full name, and their shared birth year.

[Assistant]
SELECT
  m.first_name || ' ' || m.last_name AS male_full_name,
  f.first_name || ' ' || f.last_name AS female_full_name,
  EXTRACT(YEAR FROM m.date_of_birth) AS birth_year
FROM government_services.citizens m
JOIN government_services.citizens f
  ON EXTRACT(YEAR FROM m.date_of_birth) = EXTRACT(YEAR FROM f.date_of_birth)
     AND m.gender = 'Male'
     AND f.gender = 'Female';