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 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, ssn_hash character varying(128), address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL DEFAULT 'USA', phone_number character varying(30), email character varying(128) UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, status character varying(20) NOT NULL DEFAULT 'Active', PRIMARY KEY (customer_id) )
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) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )

[User] Show me the first and last names of all customers with policies having a premium amount greater than 3000, along with their policy number and policy status.

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, p.status
FROM insurance.customers c
JOIN insurance.policies p ON c.customer_id = p.customer_id
WHERE p.premium_amount > 3000;

[User] Can you also include the name and type of the insurance product for each policy?

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, p.status, ip.product_name, ip.product_type
FROM insurance.customers c
JOIN insurance.policies p ON c.customer_id = p.customer_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.premium_amount > 3000;

[User] Only show results for customers living in California.

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, p.status, ip.product_name, ip.product_type
FROM insurance.customers c
JOIN insurance.policies p ON c.customer_id = p.customer_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.premium_amount > 3000 AND c.state = 'CA';

[User] Actually, only include policies that are currently 'Active' and sort the results by premium amount descending.

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, p.status, ip.product_name, ip.product_type, p.premium_amount
FROM insurance.customers c
JOIN insurance.policies p ON c.customer_id = p.customer_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.premium_amount > 3000 AND c.state = 'CA' AND p.status = 'Active'
ORDER BY p.premium_amount 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 healthcare.patients ( patient_id.text, 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.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] List all insurance plans, showing their ID, name, provider, and plan type.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans;

[User] Filter the list to only show plans provided by 'BlueCross BlueShield' and with a plan type of 'EPO'.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'BlueCross BlueShield' AND plan_type = 'EPO';


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.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )

[User] List the vehicle_id, make, model, and acquisition_date for all active vehicles acquired after '2022-01-01'.

[Assistant]
SELECT vehicle_id, make, model, acquisition_date
FROM transportation.vehicles
WHERE status = 'Active'
  AND acquisition_date > '2022-01-01';

[User] Now, filter this list to only include vehicles with capacity greater than 50 and order by acquisition_date ascending.

[Assistant]
SELECT vehicle_id, make, model, acquisition_date
FROM transportation.vehicles
WHERE status = 'Active'
  AND acquisition_date > '2022-01-01'
  AND capacity > 50
ORDER BY acquisition_date 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 hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)

[User] List payment records in USD including guest names and processing staff names.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       g.guest_name,
       s.staff_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id
WHERE p.currency_code = 'USD';

[User] Only include payments with status 'Succeeded' made within the last 30 days.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       g.guest_name,
       s.staff_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id
WHERE p.currency_code = 'USD'
  AND p.status = 'Succeeded'
  AND p.payment_timestamp >= NOW() - INTERVAL '30 days';

[User] Sort by payment timestamp descending and limit to 50 records.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       g.guest_name,
       s.staff_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id
WHERE p.currency_code = 'USD'
  AND p.status = 'Succeeded'
  AND p.payment_timestamp >= NOW() - INTERVAL '30 days'
ORDER BY p.payment_timestamp DESC
LIMIT 50;


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.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )

[User] For each year since 2015, show the total number of games released per year.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
ORDER BY year ASC;

[User] Include the number of distinct developers who released games each year.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games, COUNT(DISTINCT developer_id) AS developer_count
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
ORDER BY year ASC;

[User] Now only show years where more than 20 games were released.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games, COUNT(DISTINCT developer_id) AS developer_count
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
HAVING COUNT(*) > 20
ORDER BY year ASC;

[User] Please also add the average number of games released per developer for each year.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games, COUNT(DISTINCT developer_id) AS developer_count, ROUND(COUNT(*)::numeric / NULLIF(COUNT(DISTINCT developer_id), 0), 2) AS avg_games_per_developer
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
HAVING COUNT(*) > 20
ORDER BY year 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 insurance.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)
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 character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.agents ( agent_id text, 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 character varying(64) NOT NULL, -- unique identifier for the document
    claim_id character varying(64) NOT NULL, -- identifier of the claim this document relates to (FK to claims)
    document_type character varying(50) NOT NULL, -- e.g., Police Report, Photo, Invoice, Medical Bill
    file_name character varying(255) NOT NULL, -- original name of the uploaded file
    file_path character varying(512) NOT NULL, -- storage path (e.g., S3 URL, network path)
    file_size_bytes integer, -- size of the file in bytes
    mime_type character varying(100), -- MIME type of the file (e.g., 'image/jpeg', 'application/pdf')
    uploaded_by character varying(64), -- identifier of the user/system who uploaded (FK to users/customers)
    uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- time of upload
    description text, -- optional description of the document
    PRIMARY KEY (document_id)
)
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )

[User] Show me all claims with police reports that were filed in the last 3 months, along with their policy details and estimated loss amounts.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.incident_date, cl.reported_date, cl.estimated_loss, cl.police_report_number, p.policy_number, p.start_date, p.end_date, p.coverage_limit FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Now include the customer's full name and the product type for these policies.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.incident_date, cl.reported_date, cl.estimated_loss, cl.police_report_number, p.policy_number, p.start_date, p.end_date, p.coverage_limit, c.first_name || ' ' || c.last_name AS customer_name, ip.product_type FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.insurance_products ip ON p.product_id = ip.product_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Filter these results to only show claims where the estimated loss is above $10,000 and include the agent who handled the claim.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.incident_date, cl.reported_date, cl.estimated_loss, cl.police_report_number, p.policy_number, p.start_date, p.end_date, p.coverage_limit, c.first_name || ' ' || c.last_name AS customer_name, ip.product_type, a.first_name || ' ' || a.last_name AS agent_name FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.insurance_products ip ON p.product_id = ip.product_id LEFT JOIN insurance.agents a ON cl.claim_handler_id = a.agent_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND cl.estimated_loss > 10000;

[User] Finally, order the results by the highest estimated loss first and include only claims that have been settled.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.incident_date, cl.reported_date, cl.estimated_loss, cl.police_report_number, p.policy_number, p.start_date, p.end_date, p.coverage_limit, c.first_name || ' ' || c.last_name AS customer_name, ip.product_type, a.first_name || ' ' || a.last_name AS agent_name FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.insurance_products ip ON p.product_id = ip.product_id LEFT JOIN insurance.agents a ON cl.claim_handler_id = a.agent_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND cl.estimated_loss > 10000 AND cl.status = 'Settled' ORDER BY cl.estimated_loss 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 trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
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, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )

[User] Show me the metadata key and value for each asset where the key contains 'info', along with the asset name and symbol.

[Assistant]
SELECT a.asset_id, a.name, a.symbol, m.key, m.value
FROM trading_platform.assets a
JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
WHERE m.key ILIKE '%info%'
ORDER BY a.name;

[User] Only include assets of type 'token' and show the asset type as well.

[Assistant]
SELECT a.asset_id, a.name, a.symbol, a.type, m.key, m.value
FROM trading_platform.assets a
JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
WHERE a.type = 'token' AND m.key ILIKE '%info%'
ORDER BY a.name;

[User] Now show me only the assets that have at least 2 metadata entries with key containing 'info'.

[Assistant]
WITH info_metadata AS (
  SELECT a.asset_id, a.name, a.symbol, a.type, m.key, m.value
  FROM trading_platform.assets a
  JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
  WHERE a.type = 'token' AND m.key ILIKE '%info%'
)
SELECT asset_id, name, symbol, type
FROM info_metadata
GROUP BY asset_id, name, symbol, type
HAVING COUNT(*) >= 2
ORDER BY name;

[User] Instead, for these assets, show the asset_id, name, symbol, type, and a comma-separated list of all their metadata keys containing 'info'.

[Assistant]
SELECT a.asset_id, a.name, a.symbol, a.type, STRING_AGG(m.key, ', ') AS info_keys
FROM trading_platform.assets a
JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
WHERE a.type = 'token' AND m.key ILIKE '%info%'
GROUP BY a.asset_id, a.name, a.symbol, a.type
HAVING COUNT(*) >= 2
ORDER BY a.name;


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.doctors ( doctor_id.text, first_name.text, last_name.text, specialty.text, license_number.text, phone_number.text, email.text, hospital_affiliation_id.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, 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 )
CREATE TABLE healthcare.medications ( medication_id.text, medication_name.text, generic_name.text, manufacturer.text, ndc_code.text, description.text )
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 )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )

[User] How many insurance policies does each patient have? Return patient_id and policy_count.

[Assistant]
SELECT patient_id,
       COUNT(*) AS policy_count
FROM healthcare.patient_insurance
GROUP BY patient_id;

[User] Only show patients with more than 2 policies and order by policy_count descending.

[Assistant]
SELECT patient_id,
       COUNT(*) AS policy_count
FROM healthcare.patient_insurance
GROUP BY patient_id
HAVING COUNT(*) > 2
ORDER BY policy_count 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 healthcare.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_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.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] Can you show me the number of unique doctors by specialty who were created after January 1st, 2024?

[Assistant]
SELECT specialty, COUNT(DISTINCT doctor_id) AS doctor_count
FROM healthcare.doctors
WHERE created_at > '2024-01-01'
GROUP BY specialty

[User] Only include specialties that have at least 3 doctors, and order the results by doctor_count descending.

[Assistant]
SELECT specialty, COUNT(DISTINCT doctor_id) AS doctor_count
FROM healthcare.doctors
WHERE created_at > '2024-01-01'
GROUP BY specialty
HAVING COUNT(DISTINCT doctor_id) >= 3
ORDER BY doctor_count 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 legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )

[User] Calculate the average length of the description for each case_type.

[Assistant]
SELECT case_type,
       AVG(LENGTH(description)) AS avg_desc_length
FROM legal_services.cases
GROUP BY case_type;

[User] Only include case_types that have more than two cases.

[Assistant]
SELECT case_type,
       AVG(LENGTH(description)) AS avg_desc_length
FROM legal_services.cases
GROUP BY case_type
HAVING COUNT(*) > 2;

[User] And restrict the calculation to cases opened in 2023.

[Assistant]
SELECT case_type,
       AVG(LENGTH(description)) AS avg_desc_length
FROM legal_services.cases
WHERE date_opened >= '2023-01-01'::timestamp
  AND date_opened < '2024-01-01'::timestamp
GROUP BY case_type
HAVING COUNT(*) > 2;

[User] Finally, sort the results by avg_desc_length in descending order.

[Assistant]
SELECT case_type,
       AVG(LENGTH(description)) AS avg_desc_length
FROM legal_services.cases
WHERE date_opened >= '2023-01-01'::timestamp
  AND date_opened < '2024-01-01'::timestamp
GROUP BY case_type
HAVING COUNT(*) > 2
ORDER BY avg_desc_length 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.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )

[User] For each application, show the application ID, the full name of the assigned employee, and the number of payments made for that application.

[Assistant]
SELECT a.application_id, CONCAT(e.first_name, ' ', e.last_name) AS employee_full_name, COUNT(p.payment_id) AS payment_count
FROM government_services.applications a
LEFT JOIN government_services.payments p ON a.application_id = p.application_id
LEFT JOIN government_services.employees e ON a.assigned_employee_id = e.employee_id
GROUP BY a.application_id, e.first_name, e.last_name;


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 smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )

[User] What are the top 3 narratives by average USD purchase value per address (for buy transactions) across all chains?

[Assistant]
SELECT narrative, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative
ORDER BY avg_usd_per_address DESC
LIMIT 3;

[User] Also include the chain in the output and compute results per narrative and chain.

[Assistant]
SELECT narrative, chain, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative, chain
ORDER BY avg_usd_per_address DESC
LIMIT 3;

[User] Only show combinations where the total address_amount is greater than 50.

[Assistant]
SELECT narrative, chain, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address, SUM(address_amount) AS total_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative, chain
HAVING SUM(address_amount) > 50
ORDER BY avg_usd_per_address DESC
LIMIT 3;

[User] Add the total usd_value for each narrative and chain as a column in the result.

[Assistant]
SELECT narrative, chain, SUM(usd_value) AS total_usd_value, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address, SUM(address_amount) AS total_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative, chain
HAVING SUM(address_amount) > 50
ORDER BY avg_usd_per_address DESC
LIMIT 3;


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.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
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)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)

[User] Show me all time entries, including the case name they are associated with.

[Assistant] SELECT T1.*, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id

[User] Only show me time entries for lawyer with ID 'lawyer_789'.

[Assistant] SELECT T1.*, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.lawyer_id = 'lawyer_789'

[User] Actually, I only want entries for the date '2024-07-30', and just show the entry description, hours spent, and case name.

[Assistant] SELECT T1.description, T1.hours_spent, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.lawyer_id = 'lawyer_789' AND T1.date_worked = '2024-07-30'


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.insurance_products ( product_id.text, 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.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 character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )

[User] List the product_id, product_name, and description of any insurance products created before 2024 whose description contains the word 'theft'.

[Assistant]
SELECT product_id, product_name, description
FROM insurance.insurance_products
WHERE created_at < '2024-01-01'
  AND description ILIKE '%theft%';


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 financial_services.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, account_number character varying(128) NOT NULL UNIQUE, account_type character varying(50) NOT NULL, balance numeric(19, 4) NOT NULL DEFAULT 0.00, currency character varying(3) NOT NULL, opened_date date NOT NULL, status character varying(32) NOT NULL, interest_rate numeric(5, 4), last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) )
CREATE TABLE financial_services.transactions ( transaction_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, related_account_id character varying(64), transaction_type character varying(50) NOT NULL, amount numeric(19, 4) NOT NULL, currency character varying(3) NOT NULL, transaction_date timestamp NOT NULL, effective_date date NOT NULL, description text, status character varying(32) NOT NULL, reference_number character varying(128), PRIMARY KEY (transaction_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id) )
CREATE TABLE financial_services.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
CREATE TABLE financial_services.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, department character varying(100), branch_id character varying(64), email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, manager_id character varying(64), status character varying(32) NOT NULL, PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )

[User] I want to see for each account the total outgoing and incoming transaction amounts in the past 30 days.

[Assistant]
SELECT t.account_id,
       SUM(CASE WHEN t.transaction_type = 'DEBIT' THEN t.amount ELSE 0 END) AS total_outgoing,
       SUM(CASE WHEN t.transaction_type = 'CREDIT' THEN t.amount ELSE 0 END) AS total_incoming
FROM financial_services.transactions t
WHERE t.transaction_date >= now() - interval '30 days'
GROUP BY t.account_id;

[User] Actually, only include transactions with status = 'COMPLETED', and treat incoming as any amount where the account appears in related_account_id.

[Assistant]
WITH out_tx AS (
  SELECT account_id, SUM(amount) AS total_outgoing
  FROM financial_services.transactions
  WHERE status = 'COMPLETED'
    AND transaction_type = 'DEBIT'
    AND transaction_date >= now() - interval '30 days'
  GROUP BY account_id
),
in_tx AS (
  SELECT related_account_id AS account_id, SUM(amount) AS total_incoming
  FROM financial_services.transactions
  WHERE status = 'COMPLETED'
    AND related_account_id IS NOT NULL
    AND transaction_date >= now() - interval '30 days'
  GROUP BY related_account_id
)
SELECT COALESCE(o.account_id, i.account_id) AS account_id,
       COALESCE(o.total_outgoing, 0) AS total_outgoing,
       COALESCE(i.total_incoming, 0) AS total_incoming
FROM out_tx o
FULL JOIN in_tx i ON o.account_id = i.account_id;

[User] Also include the account_number from the accounts table.

[Assistant]
WITH out_tx AS (
  SELECT account_id, SUM(amount) AS total_outgoing
  FROM financial_services.transactions
  WHERE status = 'COMPLETED'
    AND transaction_type = 'DEBIT'
    AND transaction_date >= now() - interval '30 days'
  GROUP BY account_id
),
in_tx AS (
  SELECT related_account_id AS account_id, SUM(amount) AS total_incoming
  FROM financial_services.transactions
  WHERE status = 'COMPLETED'
    AND related_account_id IS NOT NULL
    AND transaction_date >= now() - interval '30 days'
  GROUP BY related_account_id
)
SELECT a.account_id,
       a.account_number,
       COALESCE(o.total_outgoing, 0) AS total_outgoing,
       COALESCE(i.total_incoming, 0) AS total_incoming
FROM financial_services.accounts a
LEFT JOIN out_tx o ON a.account_id = o.account_id
LEFT JOIN in_tx i ON a.account_id = i.account_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 legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )

[User] Compute the total invoiced amount and average payment delay (in days) by status for invoices issued between 2024-01-01 and 2024-06-30.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status;

[User] Also show the count of invoices per status.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days,
       COUNT(*) AS invoice_count
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status;

[User] Exclude statuses where total_invoiced is less than 10000.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days,
       COUNT(*) AS invoice_count
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status
HAVING SUM(total_amount) >= 10000;

[User] Finally, order the results by avg_payment_delay_days ascending.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days,
       COUNT(*) AS invoice_count
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status
HAVING SUM(total_amount) >= 10000
 ORDER BY avg_payment_delay_days 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
Collection 'inspections'. Document structure: { _id: <ObjectId (or inspection_id)>, inspection_id: String, build_id: String (reference), component_id: String (reference, optional), step_id: String (reference, optional), inspection_type: String, inspector_employee_id: String (reference), inspection_timestamp: ISODate, result: String, remarks: String }. Required: inspection_id, build_id, inspection_type, inspector_employee_id, inspection_timestamp, result. Indexes on build_id, component_id, step_id, inspector_employee_id, result.

[User] 我想查询所有检查结果为'Pass'的记录，包括检查类型、检查时间和检查备注，同时关联到对应的组件信息。

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      result: 'Pass'
    }
  },
  {
    $lookup: {
      from: 'components',
      localField: 'component_id',
      foreignField: 'component_id',
      as: 'component_info'
    }
  },
  {
    $unwind: {
      path: '$component_info',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      inspection_type: 1,
      inspection_timestamp: 1,
      remarks: 1,
      'component_info.component_name': 1,
      'component_info.description': 1
    }
  }
]);

[User] 如果我想只看检查时间在2023年1月1日之后的记录，应该怎么修改？

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      result: 'Pass',
      inspection_timestamp: {
        $gte: ISODate('2023-01-01T00:00:00Z')
      }
    }
  },
  {
    $lookup: {
      from: 'components',
      localField: 'component_id',
      foreignField: 'component_id',
      as: 'component_info'
    }
  },
  {
    $unwind: {
      path: '$component_info',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      inspection_type: 1,
      inspection_timestamp: 1,
      remarks: 1,
      'component_info.component_name': 1,
      'component_info.description': 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 transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )

[User] Retrieve the driver_id, first_name, and last_name for all drivers whose license_expiry_date falls within the next 6 months from today.

[Assistant]
SELECT driver_id, first_name, last_name
FROM transportation.drivers
WHERE license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '6 months';

[User] Now, also include those drivers' email addresses and sort the results by license_expiry_date ascending.

[Assistant]
SELECT driver_id, first_name, last_name, email
FROM transportation.drivers
WHERE license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '6 months'
ORDER BY license_expiry_date 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 trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)

[User] List each user's username and the total number of trades they've participated in as buyers, including users who have not made any trades, sorted by the trade count descending.

[Assistant]
SELECT u.username, COUNT(t.trade_id) AS buy_trade_count
FROM trading_platform.users u
LEFT JOIN trading_platform.trades t ON u.user_id = t.buyer_id
GROUP BY u.username
ORDER BY buy_trade_count DESC;

[User] Actually, restrict the result to users who have made at least 2 trades and include their email address as well.

[Assistant]
SELECT u.username, u.email, COUNT(t.trade_id) AS buy_trade_count
FROM trading_platform.users u
JOIN trading_platform.trades t ON u.user_id = t.buyer_id
GROUP BY u.username, u.email
HAVING COUNT(t.trade_id) >= 2
ORDER BY buy_trade_count 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 web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )

[User] For each contract deployed on network 'mainnet', show its address, status, the number of tokens created by that contract's address, and the total number of events emitted by that contract.

[Assistant]
SELECT
  c.address AS contract_address,
  c.status,
  COUNT(DISTINCT t.token_id) AS token_count,
  COUNT(e.event_id) AS event_count
FROM web3.contracts c
LEFT JOIN web3.tokens t
  ON c.address = t.contract_address
LEFT JOIN web3.events e
  ON c.contract_id = e.contract_id
WHERE c.network_id = 'mainnet'
GROUP BY c.address, c.status;


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.routes (
    route_id character varying(64) NOT NULL,  -- unique identifier for the route
    route_number character varying(32) NOT NULL UNIQUE, -- public-facing route number/name
    description text, -- description of the route
    origin_location_id character varying(64) NOT NULL, -- identifier of the starting location
    destination_location_id character varying(64) NOT NULL, -- identifier of the ending location
    distance_km numeric(10, 2), -- estimated distance in kilometers
    estimated_duration_minutes integer, -- estimated travel time in minutes
    type character varying(32) NOT NULL, -- e.g., City Bus, Intercity Train, Cargo Delivery
    PRIMARY KEY (route_id)
)

[User] What is the average estimated_duration_minutes for each route type?

[Assistant] SELECT type, AVG(estimated_duration_minutes) AS avg_duration FROM transportation.routes GROUP BY type;

[User] Exclude route types where the average duration is less than 60 minutes, and sort the results by avg_duration DESC.

[Assistant] SELECT type, AVG(estimated_duration_minutes) AS avg_duration FROM transportation.routes GROUP BY type HAVING AVG(estimated_duration_minutes) >= 60 ORDER BY avg_duration 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 hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] List all properties and the room types they offer, including the base rate for each room type.

[Assistant] SELECT T1.property_name, T2.type_name, T2.base_rate FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id = T2.property_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 government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )

[User] Find all applications whose last update occurred on a weekend. Show application_id, citizen full name, last_updated_at, and status.

[Assistant]
SELECT
a.application_id,
(c.first_name || ' ' || c.last_name) AS full_name,
a.last_updated_at,
a.status
FROM government_services.applications a
JOIN government_services.citizens c
  ON a.citizen_id = c.citizen_id
WHERE EXTRACT(DOW FROM a.last_updated_at) IN (0, 6);


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, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, 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, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, 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, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] List all distinct asset types from the assets table.

[Assistant]
SELECT DISTINCT type
FROM trading_platform.assets;


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.agents ( agent_id.text, 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 )

[User] Which five license states have the highest count of active agents? Return the license_state and agent_count.

[Assistant]
SELECT license_state,
       COUNT(*) AS agent_count
FROM insurance.agents
WHERE status = 'Active'
GROUP BY license_state
ORDER BY agent_count 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 transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)

[User] Show me the trip_id, status, and passenger_count for all trips where the scheduled_departure and scheduled_arrival are on the same day, but the actual_arrival is later than the scheduled_arrival.

[Assistant]
SELECT trip_id, status, passenger_count
FROM transportation.trips
WHERE DATE(scheduled_departure) = DATE(scheduled_arrival)
  AND actual_arrival > scheduled_arrival;

[User] Can you also calculate the delay in minutes between the scheduled_arrival and actual_arrival and include it in the result?

[Assistant]
SELECT trip_id, status, passenger_count, EXTRACT(EPOCH FROM (actual_arrival - scheduled_arrival))/60 AS delay_minutes
FROM transportation.trips
WHERE DATE(scheduled_departure) = DATE(scheduled_arrival)
  AND actual_arrival > scheduled_arrival;

[User] Actually, limit the results to only those trips where the delay is more than 60 minutes and order by delay_minutes descending.

[Assistant]
SELECT trip_id, status, passenger_count, EXTRACT(EPOCH FROM (actual_arrival - scheduled_arrival))/60 AS delay_minutes
FROM transportation.trips
WHERE DATE(scheduled_departure) = DATE(scheduled_arrival)
  AND actual_arrival > scheduled_arrival
  AND EXTRACT(EPOCH FROM (actual_arrival - scheduled_arrival))/60 > 60
ORDER BY delay_minutes 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 financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )

[User] List all accounts opened in the last year. Show account_id, account_type, status, and opened_date.

[Assistant] SELECT account_id, account_type, status, opened_date FROM financial_services.accounts WHERE opened_date >= CURRENT_DATE - INTERVAL '1 year'

[User] Exclude accounts with a 'Closed' status from this list.

[Assistant] SELECT account_id, account_type, status, opened_date FROM financial_services.accounts WHERE opened_date >= CURRENT_DATE - INTERVAL '1 year' AND status != 'Closed'

[User] Also, include the currency and filter to only show accounts with a balance greater than 1000.

[Assistant] SELECT account_id, account_type, status, opened_date, currency FROM financial_services.accounts WHERE opened_date >= CURRENT_DATE - INTERVAL '1 year' AND status != 'Closed' AND balance > 1000


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.contracts ( contract_id text PRIMARY KEY, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )

[User] List all failed transactions along with the from and to addresses, and the gas used.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used FROM web3.transactions WHERE status = 'failed';

[User] Actually, I also need to see the block number and timestamp for these failed transactions.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used, block_number, timestamp FROM web3.transactions WHERE status = 'failed';

[User] There's a typo in your SQL, it should be 'timestamp' not 'timestamp'. Also, sort the results by block number in descending order.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used, block_number, timestamp FROM web3.transactions WHERE status = 'failed' ORDER BY block_number DESC;

[User] Now filter to only show transactions with gas used greater than 100,000.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used, block_number, timestamp FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000 ORDER BY block_number 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 erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE erc20_balances_historical ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.integer )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_collections (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    name varchar NOT NULL, -- name fields for the functionType  in contract
    symbol varchar NOT NULL, -- symbol fields for the functionType  in contract
    deploy_block_number bigint NOT NULL, -- deploy_block_number fields for the functionType  in contract
    deploy_block_time bigint NOT NULL, -- deploy_block_time fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    description varchar NOT NULL, -- description fields for the functionType  in contract
    slug varchar NOT NULL, -- slug fields for the functionType  in contract
    media_info varchar NOT NULL, -- media_info fields for the functionType  in contract
    image_url varchar NOT NULL, -- image_url fields for the functionType  in contract
    banner_image_url varchar NOT NULL, -- banner_image_url fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    banner varchar NOT NULL, -- banner fields for the functionType  in contract
    token_count bigint NOT NULL, -- token_count fields for the functionType  in contract
    floor_price varchar NOT NULL, -- floor_price fields for the functionType  in contract
    floor_price_symbol varchar NOT NULL, -- floor_price_symbol fields for the functionType  in contract
    floor_price_contract varchar NOT NULL, -- floor_price_contract fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(deploy_block_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info_avalanche (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(20) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL, -- Address originating the inscription (matches from_address in transactions table)
    minted decimal(38,0) NOT NULL, -- Sum of minted amount
    holders decimal(38,0) NOT NULL, -- Count of holders
    txs decimal(38,0) NOT NULL, -- Count of transactions
    updated_timestamp timestamp(3) NOT NULL, -- Timestamp of update
    completed_timestamp timestamp(3) NOT NULL, -- Timestamp of minted completed
    id varchar(255) NOT NULL  -- id fields for the functionType  in contract asc20
)

[User] Show me the current ERC20 token balances for the wallet address '0x1A2b3C4dE5f6A7b8C9d0E1f2A3b4C5d6E7f8A9b0'.

[Assistant] SELECT contract_address, amount FROM erc20_balances WHERE wallet_address = '0x1A2b3C4dE5f6A7b8C9d0E1f2A3b4C5d6E7f8A9b0';

[User] Can you also include the token symbol and name for these balances, and only show tokens where the amount is greater than '1000000000000000000' (representing 1 unit for a token with 18 decimals)?

[Assistant] SELECT b.contract_address, m.symbol, m.name, b.amount FROM erc20_balances AS b JOIN token_metas AS m ON b.contract_address = m.address WHERE b.wallet_address = '0x1A2b3C4dE5f6A7b8C9d0E1f2A3b4C5d6E7f8A9b0' AND CAST(b.amount AS DECIMAL) > 1000000000000000000;


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.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] How many documents has each lawyer uploaded? Return uploaded_by_lawyer_id and the count, only include lawyers with at least 3 documents, sorted by count descending.

[Assistant]
SELECT uploaded_by_lawyer_id,
       COUNT(*) AS doc_count
FROM legal_services.documents
GROUP BY uploaded_by_lawyer_id
HAVING COUNT(*) >= 3
ORDER BY doc_count 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 trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.utxos ( utxo_id character varying(64) NOT NULL, transaction_id character varying(64) NOT NULL, output_index integer NOT NULL, address character varying(128) NOT NULL, amount numeric(38,14) NOT NULL, spent boolean NOT NULL, PRIMARY KEY (utxo_id) )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, status character varying(32) NOT NULL, reviewed_at timestamp NOT NULL, PRIMARY KEY (kyc_audit_id) )
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
CREATE TABLE trading_platform.notifications ( notification_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, message text NOT NULL, sent_at timestamp NOT NULL, read_at timestamp, PRIMARY KEY (notification_id) )

[User] Get the number of log entries for each user where the action contains 'fail' in the last 30 days.

[Assistant]
SELECT l.user_id, COUNT(*) AS fail_count
FROM trading_platform.logs l
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY l.user_id;

[User] Only include users with at least 3 such log entries.

[Assistant]
SELECT l.user_id, COUNT(*) AS fail_count
FROM trading_platform.logs l
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY l.user_id
HAVING COUNT(*) >= 3;

[User] Also include the username from the users table.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS fail_count
FROM trading_platform.users u
JOIN trading_platform.logs l ON u.user_id = l.user_id
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY u.user_id, u.username
HAVING COUNT(l.log_id) >= 3;

[User] Order the results by fail_count descending and limit to the top 5 users.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS fail_count
FROM trading_platform.users u
JOIN trading_platform.logs l ON u.user_id = l.user_id
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY u.user_id, u.username
HAVING COUNT(l.log_id) >= 3
ORDER BY fail_count 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 insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] For each claim, retrieve the document_id, file_name, and uploaded_at of the earliest and the latest uploaded document.

[Assistant]
SELECT
    c1.claim_id,
    c1.document_id AS earliest_document_id,
    c1.file_name AS earliest_file_name,
    c1.uploaded_at AS earliest_uploaded_at,
    c2.document_id AS latest_document_id,
    c2.file_name AS latest_file_name,
    c2.uploaded_at AS latest_uploaded_at
FROM insurance.claim_documents c1
JOIN insurance.claim_documents c2
  ON c1.claim_id = c2.claim_id
  AND c1.uploaded_at = (
    SELECT MIN(cd.uploaded_at)
    FROM insurance.claim_documents cd
    WHERE cd.claim_id = c1.claim_id
  )
  AND c2.uploaded_at = (
    SELECT MAX(cd.uploaded_at)
    FROM insurance.claim_documents cd
    WHERE cd.claim_id = c2.claim_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 healthcare.patients ( patient_id.text, 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 )

[User] How many unique patient records are there for each gender?

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


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.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)

[User] Find all medical records associated with an appointment, and show the record_id, appointment_id, and the record_date.

[Assistant]
SELECT record_id, appointment_id, record_date
FROM healthcare.medical_records
WHERE appointment_id 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 social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )

[User] List the sender_user_id and the total number of messages they have sent that include media attachments, along with the conversation_id.

[Assistant]
SELECT sender_user_id, conversation_id, COUNT(*) AS media_message_count
FROM social_media.messages
WHERE media_url IS NOT NULL AND media_url <> ''
GROUP BY sender_user_id, conversation_id;

[User] Only include media attachments where media_type is 'video'.

[Assistant]
SELECT sender_user_id, conversation_id, COUNT(*) AS video_media_message_count
FROM social_media.messages
WHERE media_url IS NOT NULL AND media_url <> '' AND media_type = 'video'
GROUP BY sender_user_id, conversation_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 hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] List the total number of service orders placed by each staff member who delivered the service.

[Assistant] SELECT staff_id_delivered, COUNT(*) AS order_count FROM hospitality_technology.service_orders GROUP BY staff_id_delivered;

[User] Show only those staff members who have delivered at least 20 service orders and order the results by order_count descending.

[Assistant] SELECT staff_id_delivered, COUNT(*) AS order_count FROM hospitality_technology.service_orders GROUP BY staff_id_delivered HAVING COUNT(*) >= 20 ORDER BY order_count 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 healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
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 character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
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 )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] For each medication manufacturer, show the total number of distinct generic names they produce.

[Assistant] SELECT manufacturer, COUNT(DISTINCT generic_name) AS distinct_generic_name_count FROM healthcare.medications WHERE generic_name IS NOT NULL AND manufacturer IS NOT NULL GROUP BY manufacturer ORDER BY manufacturer;


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 )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] Show the application ID, payment amount, and payment method for all payments that have a status of 'Completed' and are related to services in the 'Licensing' category.

[Assistant]
SELECT p.application_id, p.amount, p.payment_method
FROM government_services.payments p
JOIN government_services.services s ON p.service_id = s.service_id
WHERE p.status = 'Completed' AND s.category = 'Licensing';