[User] For the 'DeFi' narrative, what is the average ROI and the total net inflow (usd_value where type=1) from smart money token inflow?

[Assistant]
SELECT AVG(sm.roi) AS avg_roi, SUM(smt.usd_value) AS total_net_inflow
FROM smart_money_token_inflow smt
JOIN smart_money_profit sm ON smt.chain = sm.chain
WHERE smt.narrative = 'DeFi' AND smt.type = 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE cex_token_balance ( snapshot_time text, chain text, address text, exchange text, token_address text, token_symbol text, balance numeric, usd_value numeric, price numeric )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )


[User] Show me the earliest created smart contract for each creator address.

[Assistant] SELECT sc1.contract_id, sc1.creator_address, sc1.timestamp FROM blockchain.smart_contracts sc1 WHERE sc1.timestamp = (SELECT MIN(sc2.timestamp) FROM blockchain.smart_contracts sc2 WHERE sc2.creator_address = sc1.creator_address);

[User] Now include the total number of contracts each creator has made alongside this information.

[Assistant] SELECT sc1.contract_id, sc1.creator_address, sc1.timestamp, (SELECT COUNT(*) FROM blockchain.smart_contracts sc2 WHERE sc2.creator_address = sc1.creator_address) AS total_contracts FROM blockchain.smart_contracts sc1 WHERE sc1.timestamp = (SELECT MIN(sc3.timestamp) FROM blockchain.smart_contracts sc3 WHERE sc3.creator_address = sc1.creator_address);

[User] Filter this to only show creators who have made at least 10 contracts.

[Assistant] SELECT sc1.contract_id, sc1.creator_address, sc1.timestamp, (SELECT COUNT(*) FROM blockchain.smart_contracts sc2 WHERE sc2.creator_address = sc1.creator_address) AS total_contracts FROM blockchain.smart_contracts sc1 WHERE sc1.timestamp = (SELECT MIN(sc3.timestamp) FROM blockchain.smart_contracts sc3 WHERE sc3.creator_address = sc1.creator_address) AND (SELECT COUNT(*) FROM blockchain.smart_contracts sc4 WHERE sc4.creator_address = sc1.creator_address) >= 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.smart_contracts ( contract_id.text, creator_address.text, code.text, timestamp.timestamp )


[User] Can you list each server along with its game title and how many players it can still accommodate (max_players - current_players)?

[Assistant]
SELECT s.server_id,
       s.server_name,
       g.title AS game_title,
       (s.max_players - s.current_players) AS available_slots
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id;

[User] Only include servers that are currently 'online' or 'idle'.

[Assistant]
SELECT s.server_id,
       s.server_name,
       g.title AS game_title,
       (s.max_players - s.current_players) AS available_slots
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.status IN ('online', 'idle');

[User] Now show only those with available_slots greater than 10, sorted by available_slots descending.

[Assistant]
SELECT s.server_id,
       s.server_name,
       g.title AS game_title,
       (s.max_players - s.current_players) AS available_slots
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.status IN ('online', 'idle')
  AND (s.max_players - s.current_players) > 10
ORDER BY available_slots DESC;

[User] Finally, include the game's release_date and only for games released after 2022-01-01.

[Assistant]
SELECT s.server_id,
       s.server_name,
       g.title AS game_title,
       g.release_date,
       (s.max_players - s.current_players) AS available_slots
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.status IN ('online', 'idle')
  AND (s.max_players - s.current_players) > 10
  AND g.release_date > '2022-01-01'
ORDER BY available_slots DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )


[User] Show me all appointments scheduled for tomorrow with a duration longer than 45 minutes, including patient_id, doctor_id, and appointment_time.

[Assistant] SELECT patient_id, doctor_id, appointment_time FROM healthcare.appointments WHERE DATE(appointment_time) = DATE(NOW() + INTERVAL 1 DAY) AND duration_minutes > 45;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )


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

[Assistant]
SELECT patient_id,
       COUNT(*) AS active_policy_count
FROM healthcare.patient_insurance
WHERE expiration_date IS NULL
   OR expiration_date >= CURRENT_DATE
GROUP BY patient_id;

[User] Actually, only include patients who have more than one active insurance policy.

[Assistant]
SELECT patient_id,
       COUNT(*) AS active_policy_count
FROM healthcare.patient_insurance
WHERE expiration_date IS NULL
   OR expiration_date >= CURRENT_DATE
GROUP BY patient_id
HAVING COUNT(*) > 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
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 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)
)
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.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List each appointment with appointment ID, appointment time, doctor's last name, and the patient's primary insurance plan name.

[Assistant]
SELECT a.appointment_id,
       a.appointment_time,
       d.last_name AS doctor_last_name,
       p.plan_name
FROM healthcare.appointments a
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
JOIN healthcare.patient_insurance pi ON a.patient_id = pi.patient_id AND pi.is_primary = true
JOIN healthcare.insurance_plans p ON pi.plan_id = p.plan_id;

[User] Filter to only show appointments with status 'Completed' in the year 2024.

[Assistant]
SELECT a.appointment_id,
       a.appointment_time,
       d.last_name AS doctor_last_name,
       p.plan_name
FROM healthcare.appointments a
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
JOIN healthcare.patient_insurance pi ON a.patient_id = pi.patient_id AND pi.is_primary = true
JOIN healthcare.insurance_plans p ON pi.plan_id = p.plan_id
WHERE a.status = 'Completed'
  AND a.appointment_time >= '2024-01-01'
  AND a.appointment_time < '2025-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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.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, 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.json, created_at.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 character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List all rooms that have a 'Jacuzzi' feature, including the room_number, property_id, type_name, and base_rate.

[Assistant]
SELECT r.room_number,
       r.property_id,
       rt.type_name,
       rt.base_rate
FROM hospitality_technology.rooms AS r
JOIN hospitality_technology.room_types AS rt
  ON r.room_type_id = rt.room_type_id
 AND r.property_id = rt.property_id
WHERE r.features ILIKE '%Jacuzzi%';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id.text, 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.staff ( staff_id.text, 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.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
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, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )


[User] Show me all business center services (category = 'Business Center') along with their property IDs and descriptions, where the service is available.

[Assistant] SELECT service_name, property_id, description FROM hospitality_technology.services WHERE category = 'Business Center' AND is_available = true;

[User] Now, join this with another query to include the property names from the properties table (assuming properties table has property_id and property_name columns).

[Assistant] SELECT s.service_name, s.property_id, s.description, p.property_name FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true;

[User] The query is missing the price information. Can you include that as well?

[Assistant] SELECT s.service_name, s.property_id, s.description, p.property_name, s.price FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true;

[User] Actually, I need to see only services priced per hour (unit = 'Per Hour'), and order them by property name in alphabetical order.

[Assistant] SELECT s.service_name, s.property_id, s.description, p.property_name, s.price FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true AND s.unit = 'Per Hour' ORDER BY p.property_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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)
)


[User] List each lawyer's full name with the full name of the partner at the same firm.

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true;

[User] Actually, I only want those lawyers whose specialization includes 'Corporate Law'. Could you update the query?

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true
WHERE l.specialization ILIKE '%Corporate Law%';

[User] Also only show those who were hired after 2020-01-01.

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true
WHERE l.specialization ILIKE '%Corporate Law%'
  AND l.hire_date > '2020-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)


[User] 特定のプラットフォームID 'plat_123' に関連するメンテナンス記録を取得するのを手伝っていただけますか？また、記録のステータスも含めてください。

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGETALL maintenance_record:<record_id>

[User] ステータスが 'Completed' の記録だけを表示するようにフィルタリングしていただけますか？

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGET maintenance_record:<record_id> status
HGETALL maintenance_record:<record_id> (only if status = 'Completed')

[User] 関連する資産タイプも結果に含めていただけますか？

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGET maintenance_record:<record_id> status
HGETALL maintenance_record:<record_id> (only if status = 'Completed')

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
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...

// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
// Use Hashes for maintenance record details. Key format: maintenance_record:<record_id>
// HSET maintenance_record:maint_rec_001 record_id "maint_rec_001" asset_id "train_789" asset_type "Train" ... status "Completed"

// To link records to assets (optional):
// SADD train:train_789:maintenance maintenance_record:maint_rec_001
// SADD platform:plat_123:maintenance maintenance_record:maint_rec_002


[User] Show me all insurance plans that cover more than 10 patients as their primary insurance, along with the provider name and contact information.

[Assistant] SELECT ip.plan_name, ip.insurance_provider, ip.contact_phone, ip.website, COUNT(pi.patient_id) AS patient_count FROM healthcare.insurance_plans ip JOIN healthcare.patient_insurance pi ON ip.plan_id = pi.plan_id WHERE pi.is_primary = true GROUP BY ip.plan_id HAVING COUNT(pi.patient_id) > 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
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.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    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 character varying(64) NOT NULL, -- unique identifier for the prescription
    record_id character varying(64) NOT NULL, -- FK linking to the medical record where it was prescribed
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to prescribing doctor
    medication_id character varying(64) NOT NULL, -- FK to medications table
    dosage character varying(100) NOT NULL, -- e.g., '100mg', '1 tablet'
    frequency character varying(100) NOT NULL, -- e.g., 'Once daily', 'Twice a day with meals'
    route character varying(50), -- e.g., 'Oral', 'Topical', 'Intravenous'
    start_date date NOT NULL, -- date prescription begins
    end_date date, -- date prescription ends (if applicable)
    quantity_dispensed numeric(10,2), -- amount dispensed (e.g., number of tablets)
    refills_allowed integer NOT NULL DEFAULT 0, -- number of allowed refills
    prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (prescription_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List all room types and available services for each property, showing the property ID, room type name, base rate, service name, and service price.

[Assistant] SELECT T1.property_id ,  T1.type_name ,  T1.base_rate ,  T2.service_name ,  T2.price FROM hospitality_technology.room_types AS T1 INNER JOIN hospitality_technology.services AS T2 ON T1.property_id  =  T2.property_id WHERE T2.is_available  =  true

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
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)
)


[User] Show me each service order along with the next order placed by the same guest, including both order IDs and the time difference in minutes between the two orders.

[Assistant]
SELECT a.order_id,
       b.order_id AS next_order_id,
       EXTRACT(EPOCH FROM (b.order_timestamp - a.order_timestamp)) / 60 AS diff_minutes
FROM hospitality_technology.service_orders a
JOIN hospitality_technology.service_orders b
  ON a.guest_id = b.guest_id
 AND b.order_timestamp > a.order_timestamp;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )


[User] List each group conversation with its group name and the number of verified users who have posted in it.

[Assistant]
SELECT c.conversation_id, c.group_name, COUNT(DISTINCT u.user_id) AS verified_posters
FROM social_media.conversations c
JOIN social_media.posts p ON p.location_lat IS NOT NULL -- Simulate posts linked to conversation (since no mapping, using location as a proxy)
JOIN social_media.users u ON p.user_id = u.user_id AND u.is_verified = true
WHERE c.is_group_chat = true
GROUP BY c.conversation_id, c.group_name;

[User] Actually, only show groups created after May 1, 2024.

[Assistant]
SELECT c.conversation_id, c.group_name, COUNT(DISTINCT u.user_id) AS verified_posters
FROM social_media.conversations c
JOIN social_media.posts p ON p.location_lat IS NOT NULL -- Simulate posts linked to conversation (since no mapping, using location as a proxy)
JOIN social_media.users u ON p.user_id = u.user_id AND u.is_verified = true
WHERE c.is_group_chat = true AND c.created_at > '2024-05-01'
GROUP BY c.conversation_id, c.group_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.hashtags ( hashtag_id text PRIMARY KEY, tag_name text, created_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )


[User] Show me wallet addresses that hold more than 1000 of any ERC1155 token, along with the token ID and contract address, from the nft_holders table.

[Assistant] SELECT wallet_address, token_id, contract_address FROM nft_holders WHERE contract_type = 'ERC1155' AND CAST(amount AS decimal) > 1000;

[User] Can you also include the name of each token from the nft_collections table?

[Assistant] SELECT nh.wallet_address, nh.token_id, nh.contract_address, nc.name FROM nft_holders nh JOIN nft_collections nc ON nh.contract_address = nc.contract_address WHERE nh.contract_type = 'ERC1155' AND CAST(nh.amount AS decimal) > 1000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas (
    block_timestamp timestamp(6) NOT NULL,  -- Timestamp of the block when token metadata was recorded
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    transaction_hash varchar NOT NULL, -- Hash value of the transaction
    transaction_index bigint NOT NULL, -- Index of the transaction within the block
    from_address varchar NOT NULL, -- Address from which the transaction originated
    contract_address varchar NOT NULL, -- Address of the token contract
    symbol varchar NOT NULL, -- Symbol of the token
    total_supply varchar NOT NULL, -- erc20 contract total supply
    name varchar NOT NULL, -- Name of the token
    decimals bigint NOT NULL, -- Number of decimal places for the token
    is_erc20 integer NOT NULL, -- Flag indicating if the token is an ERC-20 token (0 or 1)
    is_erc721 integer NOT NULL, -- Flag indicating if the token is an ERC-721 token (0 or 1)
    is_erc1155 integer NOT NULL, -- Flag indicating if the token is an ERC-1155 token (0 or 1)
    is_proxy integer NOT NULL, -- Flag indicating if the token is a proxy (0 or 1)
    extra_info varchar NOT NULL, -- Additional information about the token
    pk integer NOT NULL  -- Partition key for the table(floor(block_number / 5760))
)
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holders (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter)
    token_id varchar NOT NULL, -- NFT token id
    contract_type varchar NOT NULL, -- NFT contract type
    amount varchar NOT NULL, -- Number of held NFTs
    pk varchar NOT NULL  -- The last string partition of the contract.
)
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
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 token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(255) 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_bitcoin ( 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 token_activities_avalanche ( 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 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 )


[User] What are the environmental impact assessments for the production of the Airbus A350 model?

[Assistant] I'm sorry, but I don't have access to data regarding the environmental impact assessments for the production of specific aircraft models like the Airbus A350. My information is limited to the technical specifications and basic details stored in the database, such as model name, manufacturer, and capacity. If you have a question related to the available data, I'd be happy to assist.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE manufacturing.aircraft_models ( model_id text PRIMARY KEY, model_name text, manufacturer text, passenger_capacity int, max_range_km int, engine_type text, wingspan_m numeric, status text, first_flight_date date )


[User] List all guests from California who are loyalty members and have provided their email addresses, ordered by last name.

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL AND email IS NOT NULL ORDER BY last_name;

[User] Now, include only guests who have communication consent and were created in the last year.

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number, created_at FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL AND email IS NOT NULL AND communication_consent = true AND created_at >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) ORDER BY last_name;

[User] The query is missing their loyalty member IDs. Can you include that as well?

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number, loyalty_member_id, created_at FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL AND email IS NOT NULL AND communication_consent = true AND created_at >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) ORDER BY last_name;

[User] Actually, I only need guests from Los Angeles and San Francisco, and order by created date from newest to oldest.

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number, loyalty_member_id, created_at FROM hospitality_technology.guests WHERE state_province = 'California' AND city IN ('Los Angeles', 'San Francisco') AND loyalty_member_id IS NOT NULL AND email IS NOT NULL AND communication_consent = true AND created_at >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) ORDER BY created_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id.text, property_name.text, address_line1.text, address_line2.text, city.text, state_province.text, postal_code.text, country_code.text, phone_number.text, email_address.text, property_type.text, star_rating.numeric, timezone.text, manager_staff_id.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id.text, 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.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )


[User] What is the total USD value held by all centralized exchanges (CEX) for the token with the symbol 'BTC'?

[Assistant] SELECT SUM(usd_value) AS total_btc_cex_value FROM cex_token_balance WHERE token_symbol = 'BTC';

[User] Can you break down the total USD value for 'BTC' held by CEXes by chain?

[Assistant] SELECT chain, SUM(usd_value) AS total_btc_cex_value FROM cex_token_balance WHERE token_symbol = 'BTC' GROUP BY chain ORDER BY total_btc_cex_value DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE token_dexpool_info ( pair_address.text, token_name.text, token_symbol.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_6h.numeric, price_change_percentage_24h.numeric, makers_24h.numeric, volume_24h.numeric, liquidity.numeric, market_cap.numeric, trend_rank.numeric )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp chain character varying(128) NOT NULL, -- the chain that the token resides address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX exchange character varying(512) NOT NULL, -- a centralized exchange name token_address character varying(128) NOT NULL, -- token contract address token_symbol character varying(512), --token symbol balance numeric(38,10), -- token balance usd_value numeric(38,14), -- value of the token held in USD price double precision, --price of the token in USD ,PRIMARY KEY (snapshot_time, exchange, address, chain, token_address) )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )
CREATE TABLE smart_money_token_inflow ( token_address.text, token_symbol.text, token_amount.numeric, usd_value.numeric, avg_price.numeric, type.numeric, address_amount.numeric, narrative.text, chain.text )


[User] Can you provide the total number of cars associated with a specific train with train_id 'train_789'?

[Assistant] SCARD train:train_789:cars

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
// Use Hashes for platform details. Key format: platform:<platform_id>
// HSET platform:plat_123 platform_id "plat_123" station_id "station_xyz" platform_number "1A" track_number "T1" status "Operational" length_meters 250.50 accessible 1

// To link platforms to stations (optional):
// SADD station:station_xyz:platforms platform:plat_123 platform:plat_456
// Use Hashes for train details. Key format: train:<train_id>
// HSET train:train_789 train_id "train_789" train_number "Acela 2151" model "Siemens Velaro" ... status "Active" ...

// To find train by train_number (optional index):
// SET train_number:"Acela 2151" train:train_789
// Use Hashes for car details. Key format: car:<car_id>
// HSET car:car_abc car_id "car_abc" train_id "train_789" car_number "C3" car_type "Passenger" class "Business" capacity 60 features "WiFi,Power Outlet"

// To link cars to trains (optional):
// SADD train:train_789:cars car:car_abc car:car_def
// Use Hashes for details. Key format: route_station:<route_station_id>
// HSET route_station:rs_ne_1 route_station_id "rs_ne_1" route_id "route_ne_corr" station_id "station_bos" sequence_order 1 ...

// To find stops for a route, use a Sorted Set (score by sequence_order):
// ZADD route:route_ne_corr:stops 1 route_station:rs_ne_1
// ZADD route:route_ne_corr:stops 2 route_station:rs_ne_2
// Use Hashes for schedule details. Key format: schedule:<schedule_id>
// HSET schedule:sched_1122 schedule_id "sched_1122" train_id "train_789" route_id "route_ne_corr" departure_datetime "2024-05-10T08:00:00-04:00" ... status "Scheduled"
// Use Hashes for details. Key format: schedule_stop:<stop_id>
// HSET schedule_stop:stop_sched1122_1 stop_id "stop_sched1122_1" schedule_id "sched_1122" station_id "station_bos" ...

// To find stops for a schedule, use a Sorted Set (score by sequence_order):
// ZADD schedule:sched_1122:stops 1 schedule_stop:stop_sched1122_1
// ZADD schedule:sched_1122:stops 2 schedule_stop:stop_sched1122_2
// Use Hashes for passenger details. Key format: passenger:<passenger_id>
// HSET passenger:pass_pqr passenger_id "pass_pqr" first_name "Alice" last_name "Smith" email "alice.smith@example.com" ...

// To find passenger by email (optional index):
// SET passenger_email:"alice.smith@example.com" passenger:pass_pqr
// Use Hashes for booking details. Key format: booking:<booking_id>
// HSET booking:book_zyx booking_id "book_zyx" passenger_id "pass_pqr" schedule_id "sched_1122" ... status "Confirmed" ...

// To link bookings to passengers/schedules (optional):
// SADD passenger:pass_pqr:bookings booking:book_zyx
// SADD schedule:sched_1122:bookings booking:book_zyx
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...

// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
// Use Hashes for staff details. Key format: staff:<staff_id>
// HSET staff:staff_mno staff_id "staff_mno" first_name "Bob" ... employee_number "E12345" ... is_active 1

// To find staff by employee number (optional index):
// SET staff_employee_number:"E12345" staff:staff_mno
// Use Hashes for maintenance record details. Key format: maintenance_record:<record_id>
// HSET maintenance_record:maint_rec_001 record_id "maint_rec_001" asset_id "train_789" asset_type "Train" ... status "Completed"

// To link records to assets (optional):
// SADD train:train_789:maintenance maintenance_record:maint_rec_001
// SADD platform:plat_123:maintenance maintenance_record:maint_rec_002


[User] Find the total amount paid for all premium payments made in the last 30 days.

[Assistant] SELECT SUM(amount_paid) FROM insurance.premium_payments WHERE payment_date >= CURRENT_DATE - INTERVAL '30 day';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)


[User] Show me wallet addresses that hold more than 1000 of any ERC1155 token, along with the token ID and amount, from the nft_holders table.

[Assistant] SELECT wallet_address, token_id, amount FROM nft_holders WHERE contract_type = 'ERC1155' AND CAST(amount AS decimal) > 1000;

[User] Can you join this with the nft_metadata table to include the name and image_uri of each token?

[Assistant] SELECT nh.wallet_address, nh.token_id, nh.amount, nm.name, nm.image_uri FROM nft_holders nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_type = 'ERC1155' AND CAST(nh.amount AS decimal) > 1000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities ( 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 mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_activities_avalanche ( 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_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )


[User] List all passengers along with their ages and loyalty program membership status.

[Assistant] SELECT passenger_id, first_name, last_name, date_of_birth, loyalty_program_id, DATE_PART('year', AGE(current_date, date_of_birth)) AS age FROM transportation.passengers ORDER BY last_name, first_name;

[User] I need to see only passengers who are at least 30 years old.

[Assistant] SELECT passenger_id, first_name, last_name, date_of_birth, loyalty_program_id, DATE_PART('year', AGE(current_date, date_of_birth)) AS age FROM transportation.passengers WHERE DATE_PART('year', AGE(current_date, date_of_birth)) >= 30 ORDER BY last_name, first_name;

[User] Can you also exclude passengers without a registered email address?

[Assistant] SELECT passenger_id, first_name, last_name, date_of_birth, loyalty_program_id, DATE_PART('year', AGE(current_date, date_of_birth)) AS age FROM transportation.passengers WHERE DATE_PART('year', AGE(current_date, date_of_birth)) >= 30 AND email IS NOT NULL ORDER BY last_name, first_name;

[User] Actually, add their phone number and order by age descending.

[Assistant] SELECT passenger_id, first_name, last_name, date_of_birth, loyalty_program_id, email, phone_number, DATE_PART('year', AGE(current_date, date_of_birth)) AS age FROM transportation.passengers WHERE DATE_PART('year', AGE(current_date, date_of_birth)) >= 30 AND email IS NOT NULL ORDER BY age DESC, last_name, first_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)


[User] Provide a list of all log entries recorded since the start of 2024, including the user ID, action, and the exact time the log occurred.

[Assistant] SELECT user_id, action, logged_at FROM logs WHERE logged_at >= '2024-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.logs ( log_id.text, 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] For each event recorded, list its ID, name, and the status and value of the transaction in which it occurred.

[Assistant] SELECT E.event_id, E.event_name, E.transaction_id, T.status, T.value FROM web3.events AS E JOIN web3.transactions AS T ON E.transaction_id = T.transaction_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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 character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] List all pairs of wallets that were created within 10 minutes of each other, showing both wallet IDs, the user_id, and both creation timestamps.

[Assistant]
SELECT
  w1.wallet_id AS wallet1_id,
  w2.wallet_id AS wallet2_id,
  w1.user_id,
  w1.created_at AS created_at1,
  w2.created_at AS created_at2
FROM web3.wallets w1
JOIN web3.wallets w2
  ON w1.user_id = w2.user_id
  AND w1.wallet_id < w2.wallet_id
  AND ABS(EXTRACT(EPOCH FROM (w1.created_at - w2.created_at))) <= 600;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )


[User] List all peers who were last seen after July 10, 2024, along with their IP address and port.

[Assistant]
SELECT peer_id, ip_address, port, last_seen
FROM trading_platform.peers
WHERE last_seen > '2024-07-10'
ORDER BY last_seen DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, 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.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
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 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)
)
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.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] List the token symbol and name for all tokens whose associated contract address has emitted at least one event. Also include the contract address.

[Assistant] SELECT T.token_symbol, T.token_name, T.contract_address FROM web3.tokens AS T JOIN contracts AS C ON T.contract_address = C.address JOIN events AS E ON C.contract_id = E.contract_id GROUP BY T.token_symbol, T.token_name, T.contract_address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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)
)


[User] Can you show, for each employee, the full name and job title of their direct manager, as well as the employee's department and branch_id?

[Assistant]
SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, e.branch_id AS employee_branch_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.job_title AS manager_job_title
FROM financial_services.employees e
LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id;

[User] Actually, show only employees who have a manager assigned, and include only those where the manager works at a different branch than the employee.

[Assistant]
SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, e.branch_id AS employee_branch_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.job_title AS manager_job_title, m.branch_id AS manager_branch_id
FROM financial_services.employees e
INNER JOIN financial_services.employees m ON e.manager_id = m.employee_id
WHERE e.branch_id IS DISTINCT FROM m.branch_id;

[User] Now, only include employees who were hired after 2021-01-01.

[Assistant]
SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, e.branch_id AS employee_branch_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.job_title AS manager_job_title, m.branch_id AS manager_branch_id
FROM financial_services.employees e
INNER JOIN financial_services.employees m ON e.manager_id = m.employee_id
WHERE e.branch_id IS DISTINCT FROM m.branch_id
  AND e.hire_date > '2021-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 )
CREATE TABLE financial_services.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    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.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)
CREATE TABLE financial_services.loans ( loan_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL UNIQUE, loan_type character varying(50) NOT NULL, principal_amount numeric(19, 4) NOT NULL, current_principal_balance numeric(19, 4) NOT NULL, interest_rate numeric(6, 4) NOT NULL, term_months integer NOT NULL, origination_date date NOT NULL, maturity_date date NOT NULL, monthly_payment numeric(12, 4), collateral_description text, status character varying(32) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id) )


[User] What is the schedule of trains arriving at platform 1A at station XYZ on December 25th, 2023?

[Assistant] I'm sorry, but I can't provide information about train schedules or specific arrival times as this data is not included in the platform management table. For train schedules, please refer to the train timetable or contact the station's customer service.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.platforms (
    platform_id character varying(64) NOT NULL, -- Unique identifier for the platform
    station_id character varying(64) NOT NULL, -- Foreign key referencing stations
    platform_number character varying(10) NOT NULL, -- Platform identifier (e.g., '1A', '5')
    track_number character varying(10), -- Associated track number, if different
    status character varying(32) NOT NULL DEFAULT 'Operational', -- e.g., Operational, Maintenance, Closed
    length_meters numeric(8,2), -- Length of the platform in meters
    accessible boolean NOT NULL DEFAULT false, -- Is the platform accessible (e.g., wheelchair)?
    PRIMARY KEY (platform_id),
    FOREIGN KEY (station_id) REFERENCES train_station_management.stations(station_id)
)


[User] Show me the make and model of vehicles along with the route number and distance for all routes that are serviced by vehicles with a fuel_type of 'Electric'.

[Assistant]
SELECT v.make, v.model, r.route_number, r.distance_km
FROM transportation.vehicles v
JOIN transportation.routes r ON v.vehicle_id = r.route_id
WHERE v.fuel_type = 'Electric';

[User] Oops, I want to include the estimated duration for each route as well, and only show routes where the estimated duration is less than 90 minutes.

[Assistant]
SELECT v.make, v.model, r.route_number, r.distance_km, r.estimated_duration_minutes
FROM transportation.vehicles v
JOIN transportation.routes r ON v.vehicle_id = r.route_id
WHERE v.fuel_type = 'Electric' AND r.estimated_duration_minutes < 90;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 )
CREATE TABLE transportation.drivers (
    driver_id character varying(64) NOT NULL,  -- unique identifier for the driver
    employee_id character varying(64) NOT NULL UNIQUE, -- employee reference number
    first_name character varying(128) NOT NULL, -- driver's first name
    last_name character varying(128) NOT NULL, -- driver's last name
    license_number character varying(64) NOT NULL UNIQUE, -- driving license number
    license_expiry_date date NOT NULL, -- expiry date of the license
    contact_number character varying(32), -- phone number
    email character varying(128) UNIQUE, -- email address
    hire_date date NOT NULL, -- date the driver was hired
    status character varying(32) NOT NULL, -- e.g., Active, On Leave, Terminated
    PRIMARY KEY (driver_id)
)
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )


[User] Show a list of group chat names with their conversation_id, the total number of participants, and the total number of messages sent in each group chat.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(cp.participant_id) AS participant_count,
       COUNT(m.message_id) AS message_count
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
LEFT JOIN social_media.messages m ON c.conversation_id = m.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY c.conversation_id, c.group_name;

[User] Please filter to include only group chats that have at least 5 participants.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(cp.participant_id) AS participant_count,
       COUNT(m.message_id) AS message_count
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
LEFT JOIN social_media.messages m ON c.conversation_id = m.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY c.conversation_id, c.group_name
HAVING COUNT(cp.participant_id) >= 5;

[User] Now order the results by message_count descending and limit to the top 10 group chats.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(cp.participant_id) AS participant_count,
       COUNT(m.message_id) AS message_count
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
LEFT JOIN social_media.messages m ON c.conversation_id = m.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY c.conversation_id, c.group_name
HAVING COUNT(cp.participant_id) >= 5
ORDER BY message_count DESC
LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
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 )
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )


[User] List document names and versions for documents that share the same case_id, showing each pair of versions.

[Assistant] SELECT d1.case_id, d1.document_name AS doc_name_v1, d1.version AS version1, d2.document_name AS doc_name_v2, d2.version AS version2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.case_id = d2.case_id AND d1.version < d2.version;

[User] Actually, I only want to compare the highest version against the second highest version per case.

[Assistant] SELECT d_prev.case_id, d_prev.document_name AS prev_doc, d_prev.version AS prev_version, d_latest.document_name AS latest_doc, d_latest.version AS latest_version FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id);

[User] Also include the upload timestamps and restrict to cases with at least three versions.

[Assistant] SELECT d_latest.case_id, d_prev.document_name AS prev_doc, d_prev.upload_timestamp AS prev_upload, d_latest.document_name AS latest_doc, d_latest.upload_timestamp AS latest_upload FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id) AND (SELECT COUNT(*) FROM legal_services.documents d2 WHERE d2.case_id = d_latest.case_id) >= 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)


[User] Find all users who have placed buy orders but never sell orders, along with their email addresses.

[Assistant] SELECT DISTINCT u.user_id, u.email FROM trading_platform.users u JOIN trading_platform.orders o ON u.user_id = o.user_id WHERE o.order_type = 'buy' AND u.user_id NOT IN (SELECT DISTINCT user_id FROM trading_platform.orders WHERE order_type = 'sell');

[User] Now modify the query to include the total quantity of assets they've ordered and the average order price.

[Assistant] SELECT u.user_id, u.email, SUM(o.quantity) AS total_quantity, AVG(o.price) AS avg_price FROM trading_platform.users u JOIN trading_platform.orders o ON u.user_id = o.user_id WHERE o.order_type = 'buy' AND u.user_id NOT IN (SELECT DISTINCT user_id FROM trading_platform.orders WHERE order_type = 'sell') GROUP BY u.user_id, u.email;

[User] Actually, I want to see only users who have placed more than 5 buy orders and have a total order quantity over 100.

[Assistant] SELECT u.user_id, u.email, SUM(o.quantity) AS total_quantity, AVG(o.price) AS avg_price, COUNT(o.order_id) AS order_count FROM trading_platform.users u JOIN trading_platform.orders o ON u.user_id = o.user_id WHERE o.order_type = 'buy' AND u.user_id NOT IN (SELECT DISTINCT user_id FROM trading_platform.orders WHERE order_type = 'sell') GROUP BY u.user_id, u.email HAVING COUNT(o.order_id) > 5 AND SUM(o.quantity) > 100;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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.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 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.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_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.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] Find all users who registered with a Yahoo email address, along with their registration dates.

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

[User] This query doesn't show registration dates. Can you modify it to include the registration date?

[Assistant] I notice the users table doesn't have a registration date column. Would you like me to show other available information from the users table?

[User] Then just show me the count of Yahoo email users instead.

[Assistant] SELECT COUNT(*) as yahoo_user_count FROM blockchain.users WHERE email LIKE '%@yahoo.com';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text, previous_block_id text, timestamp timestamp, nonce integer, merkle_root text, difficulty integer )
CREATE TABLE blockchain.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction
    sender_address character varying(128) NOT NULL, -- address of the sender
    receiver_address character varying(128) NOT NULL, -- address of the receiver
    amount numeric(38,14) NOT NULL, -- amount transferred
    timestamp timestamp NOT NULL, -- time when the transaction was created
    signature text NOT NULL, -- digital signature of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE blockchain.addresses ( address_id text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.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, PRIMARY KEY (user_id) )


[User] For each driver, show their driver_id, first_name, last_name, along with any other driver whose license_expiry_date is earlier than theirs.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date;

[User] Exclude pairs where the two expiry dates are not in the same calendar year.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date);

[User] Also only include pairs where the difference between their expiry dates is more than 30 days.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date,
       DATE_PART('day', d1.license_expiry_date - d2.license_expiry_date) AS days_difference
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
WHERE d1.license_expiry_date - d2.license_expiry_date > INTERVAL '30 days';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id.text, 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] Find all patients who have been prescribed medications with dosage greater than 50mg, along with their medication details and prescribing doctor's name.

[Assistant] SELECT p.patient_id, p.first_name, p.last_name, pr.dosage, pr.medication_id, pr.start_date, doc.first_name AS doctor_first_name, doc.last_name AS doctor_last_name FROM healthcare.patients p JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id JOIN healthcare.doctors doc ON pr.doctor_id = doc.doctor_id WHERE CAST(SUBSTRING_INDEX(pr.dosage, 'mg', 1) AS UNSIGNED) > 50;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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.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.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 )