[User] Show me all active policies for customers who live in California, along with their total premium payments made so far.

[Assistant] SELECT p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount, SUM(pp.amount_paid) AS total_payments_made FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id LEFT JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id WHERE p.status = 'Active' AND c.state = 'California' GROUP BY p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount;

[User] I also want to see how many claims each of these policies has had.

[Assistant] SELECT p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount, SUM(pp.amount_paid) AS total_payments_made, COUNT(cl.claim_id) AS claim_count FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id LEFT JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id LEFT JOIN insurance.claims cl ON p.policy_id = cl.policy_id WHERE p.status = 'Active' AND c.state = 'California' GROUP BY p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount;

[User] Actually, I only want to see policies that have at least one claim.

[Assistant] SELECT p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount, SUM(pp.amount_paid) AS total_payments_made, COUNT(cl.claim_id) AS claim_count FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id LEFT JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id JOIN insurance.claims cl ON p.policy_id = cl.policy_id WHERE p.status = 'Active' AND c.state = 'California' GROUP BY p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount HAVING COUNT(cl.claim_id) > 0;

[User] Now show me the average settlement amount for these policies' claims.

[Assistant] SELECT p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount, SUM(pp.amount_paid) AS total_payments_made, COUNT(cl.claim_id) AS claim_count, AVG(cl.settlement_amount) AS avg_settlement FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id LEFT JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id JOIN insurance.claims cl ON p.policy_id = cl.policy_id WHERE p.status = 'Active' AND c.state = 'California' GROUP BY p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount HAVING COUNT(cl.claim_id) > 0;

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.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)
CREATE TABLE insurance.policies (
    policy_id 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.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_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)
)
CREATE TABLE insurance.claim_documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document
    claim_id character varying(64) NOT NULL, -- identifier of the claim this document relates to (FK to claims)
    document_type character varying(50) NOT NULL, -- e.g., Police Report, Photo, Invoice, Medical Bill
    file_name character varying(255) NOT NULL, -- original name of the uploaded file
    file_path character varying(512) NOT NULL, -- storage path (e.g., S3 URL, network path)
    file_size_bytes integer, -- size of the file in bytes
    mime_type character varying(100), -- MIME type of the file (e.g., 'image/jpeg', 'application/pdf')
    uploaded_by character varying(64), -- identifier of the user/system who uploaded (FK to users/customers)
    uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- time of upload
    description text, -- optional description of the document
    PRIMARY KEY (document_id)
)


[User] Retrieve pairs of law firms that share the same managing_partner_id, showing the firm names and the managing_partner_id.

[Assistant] SELECT lf1.firm_name AS firm1, lf2.firm_name AS firm2, lf1.managing_partner_id FROM legal_services.law_firms lf1 JOIN legal_services.law_firms lf2 ON lf1.managing_partner_id = lf2.managing_partner_id;

[User] Only include non-null managing_partner_id and avoid duplicate pairs.

[Assistant] SELECT lf1.firm_name AS firm1, lf2.firm_name AS firm2, lf1.managing_partner_id FROM legal_services.law_firms lf1 JOIN legal_services.law_firms lf2 ON lf1.managing_partner_id = lf2.managing_partner_id AND lf1.firm_id < lf2.firm_id WHERE lf1.managing_partner_id IS NOT NULL;

[User] Also sort the results by managing_partner_id and then by firm1 name.

[Assistant] SELECT lf1.firm_name AS firm1, lf2.firm_name AS firm2, lf1.managing_partner_id FROM legal_services.law_firms lf1 JOIN legal_services.law_firms lf2 ON lf1.managing_partner_id = lf2.managing_partner_id AND lf1.firm_id < lf2.firm_id WHERE lf1.managing_partner_id IS NOT NULL ORDER BY lf1.managing_partner_id, lf1.firm_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 legal_services.law_firms (
    firm_id character varying(64) NOT NULL,  -- unique identifier for the law firm
    firm_name character varying(200) NOT NULL, -- official name of the law firm
    address text NOT NULL, -- primary address of the firm
    phone character varying(32), -- firm's main phone number
    website character varying(255), -- firm's website URL
    founded_date date, -- date the firm was established
    managing_partner_id character varying(64), -- FK to lawyers table (optional)
    PRIMARY KEY (firm_id)
)


[User] Show me assets along with their associated 'symbol' metadata value. Assume an assets table with asset_id exists.

[Assistant] SELECT a.asset_id, m.value FROM assets a JOIN metadata m ON a.asset_id = m.asset_id WHERE m.key = 'symbol'

[User] Now, also include the 'name' metadata value for these assets in the same result.

[Assistant] SELECT a.asset_id, m_symbol.value AS symbol, m_name.value AS name FROM assets a LEFT JOIN metadata m_symbol ON a.asset_id = m_symbol.asset_id AND m_symbol.key = 'symbol' LEFT JOIN metadata m_name ON a.asset_id = m_name.asset_id AND m_name.key = 'name'

[User] For assets that have both 'symbol' and 'name' metadata, list the asset ID and the count of *all* metadata entries they have.

[Assistant] SELECT a.asset_id, COUNT(m_all.metadata_id) FROM assets a JOIN metadata m_symbol ON a.asset_id = m_symbol.asset_id AND m_symbol.key = 'symbol' JOIN metadata m_name ON a.asset_id = m_name.asset_id AND m_name.key = 'name' JOIN metadata m_all ON a.asset_id = m_all.asset_id GROUP BY a.asset_id

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] List the medication_name and manufacturer for all medications where the description is null or an empty string.

[Assistant] SELECT medication_name, manufacturer FROM healthcare.medications WHERE description IS NULL OR description = '';

[User] Now, refine the query to only include medications whose ndc_code starts with '5'.

[Assistant] SELECT medication_name, manufacturer FROM healthcare.medications WHERE (description IS NULL OR description = '') AND ndc_code LIKE '5%';

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] Count the number of law firms founded in each decade. Show the decade (e.g., 1990s, 2000s) and the count.

[Assistant] SELECT CONCAT(FLOOR(EXTRACT(YEAR FROM founded_date) / 10) * 10, 's') AS decade, COUNT(*) AS firm_count FROM law_firms WHERE founded_date IS NOT NULL GROUP BY decade ORDER BY decade;

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.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )


[User] Find the top 5 ERC20 tokens by number of approval events in `erc20_approval`. Show `contract_address`, `symbol`, and `total_approvals`.

[Assistant]
SELECT ea.contract_address,
       tm.symbol,
       COUNT(*) AS total_approvals
FROM erc20_approval ea
JOIN token_metas tm ON ea.contract_address = tm.contract_address
WHERE tm.is_erc20 = 1
GROUP BY ea.contract_address, tm.symbol
ORDER BY total_approvals DESC
LIMIT 5;

[User] Also include `decimals` for each token.

[Assistant]
SELECT ea.contract_address,
       tm.symbol,
       tm.decimals,
       COUNT(*) AS total_approvals
FROM erc20_approval ea
JOIN token_metas tm ON ea.contract_address = tm.contract_address
WHERE tm.is_erc20 = 1
GROUP BY ea.contract_address, tm.symbol, tm.decimals
ORDER BY total_approvals DESC
LIMIT 5;

[User] Only include tokens where `is_proxy = 0`.

[Assistant]
SELECT ea.contract_address,
       tm.symbol,
       tm.decimals,
       COUNT(*) AS total_approvals
FROM erc20_approval ea
JOIN token_metas tm ON ea.contract_address = tm.contract_address
WHERE tm.is_erc20 = 1
  AND tm.is_proxy = 0
GROUP BY ea.contract_address, tm.symbol, tm.decimals
ORDER BY total_approvals DESC
LIMIT 5;

[User] Now add the latest USD price for each token by joining `token_prices` using the most recent timestamp per address.

[Assistant]
SELECT ea.contract_address,
       tm.symbol,
       tm.decimals,
       COUNT(*) AS total_approvals,
       tp.price AS latest_price
FROM erc20_approval ea
JOIN token_metas tm ON ea.contract_address = tm.contract_address
LEFT JOIN token_prices tp
  ON tp.address = tm.contract_address
  AND tp.timestamp = (
    SELECT MAX(tp2.timestamp)
    FROM token_prices tp2
    WHERE tp2.address = tm.contract_address
  )
WHERE tm.is_erc20 = 1
  AND tm.is_proxy = 0
GROUP BY ea.contract_address, tm.symbol, tm.decimals, tp.price
ORDER BY total_approvals DESC
LIMIT 5;

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.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
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 varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash 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, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )


[User] List all vehicles that use diesel fuel, showing their make, model, and year.

[Assistant] SELECT make, model, year FROM transportation.vehicles WHERE fuel_type = 'diesel';

[User] Now include only vehicles acquired in the last 5 years.

[Assistant] SELECT make, model, year FROM transportation.vehicles WHERE fuel_type = 'diesel' AND acquisition_date >= CURRENT_DATE - INTERVAL '5 years';

[User] Can you also show their status and order the results by year in descending order?

[Assistant] SELECT make, model, year, status FROM transportation.vehicles WHERE fuel_type = 'diesel' AND acquisition_date >= CURRENT_DATE - INTERVAL '5 years' ORDER BY year DESC;

[User] Actually, I only want to see active vehicles in this list.

[Assistant] SELECT make, model, year, status FROM transportation.vehicles WHERE fuel_type = 'diesel' AND acquisition_date >= CURRENT_DATE - INTERVAL '5 years' AND status = 'active' ORDER BY year 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 transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )


[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] Show the usernames and emails of all users who registered on the same day as at least one other user, along with the registration date.

[Assistant]
SELECT u1.username, u1.email, u1.created_at
FROM web3.users u1
JOIN web3.users u2
  ON u1.created_at::date = u2.created_at::date
  AND u1.user_id <> u2.user_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.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] For each token, show its token_id, decimals, and the average total_supply of all tokens with the same decimals.

[Assistant]
SELECT t.token_id,
       t.decimals,
       avg_data.avg_total_supply
FROM web3.tokens t
JOIN (
  SELECT decimals,
         AVG(total_supply) AS avg_total_supply
  FROM web3.tokens
  GROUP BY decimals
) AS avg_data
  ON t.decimals = avg_data.decimals;

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] Show me the full name and hire date for all lawyers hired after 2022, along with the name of the law firm they work for.

[Assistant] SELECT l.first_name, l.last_name, l.hire_date, f.firm_name FROM legal_services.lawyers AS l JOIN legal_services.law_firms AS f ON l.firm_id = f.firm_id WHERE l.hire_date > '2022-12-31';

[User] Okay, now only include those lawyers who are *not* partners.

[Assistant] SELECT l.first_name, l.last_name, l.hire_date, f.firm_name FROM legal_services.lawyers AS l JOIN legal_services.law_firms AS f ON l.firm_id = f.firm_id WHERE l.hire_date > '2022-12-31' AND l.is_partner = FALSE;

[User] Finally, order the results by the lawyer's last name and then by their first name.

[Assistant] SELECT l.first_name, l.last_name, l.hire_date, f.firm_name FROM legal_services.lawyers AS l JOIN legal_services.law_firms AS f ON l.firm_id = f.firm_id WHERE l.hire_date > '2022-12-31' AND l.is_partner = FALSE ORDER BY l.last_name, l.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 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] Find all pairs of customers who live in the same state but have different risk profiles.

[Assistant]
SELECT a.customer_id AS customer_id_a, a.first_name || ' ' || a.last_name AS full_name_a, a.risk_profile AS risk_profile_a, b.customer_id AS customer_id_b, b.first_name || ' ' || b.last_name AS full_name_b, b.risk_profile AS risk_profile_b, a.state
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.state = b.state
  AND a.risk_profile <> b.risk_profile;

[User] Now restrict to states that have more than 5 customers total.

[Assistant]
SELECT a.customer_id AS customer_id_a, a.first_name || ' ' || a.last_name AS full_name_a, a.risk_profile AS risk_profile_a, b.customer_id AS customer_id_b, b.first_name || ' ' || b.last_name AS full_name_b, b.risk_profile AS risk_profile_b, a.state
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.state = b.state
  AND a.risk_profile <> b.risk_profile
WHERE a.state IN (
  SELECT state
  FROM financial_services.customers
  GROUP BY state
  HAVING COUNT(*) > 5
);

[User] Also include the state in the result.

[Assistant]
SELECT a.customer_id AS customer_id_a, a.first_name || ' ' || a.last_name AS full_name_a, b.customer_id AS customer_id_b, b.first_name || ' ' || b.last_name AS full_name_b, a.state
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.state = b.state
  AND a.risk_profile <> b.risk_profile
WHERE a.state IN (
  SELECT state
  FROM financial_services.customers
  GROUP BY state
  HAVING COUNT(*) > 5
);

[User] Finally, order the output by state and then by a.customer_id.

[Assistant]
SELECT a.customer_id AS customer_id_a, a.first_name || ' ' || a.last_name AS full_name_a, b.customer_id AS customer_id_b, b.first_name || ' ' || b.last_name AS full_name_b, a.state
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.state = b.state
  AND a.risk_profile <> b.risk_profile
WHERE a.state IN (
  SELECT state
  FROM financial_services.customers
  GROUP BY state
  HAVING COUNT(*) > 5
)
ORDER BY a.state, a.customer_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 financial_services.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address.text, city.text, state.text, zip_code.text, country.text, email.text, phone_number.text, created_at.timestamp, status.text, risk_profile.text )


[User] I need the total fuel cost per vehicle for each fuel type.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
GROUP BY vehicle_id, fuel_type;

[User] Filter this to only include records where the cost_per_unit is greater than 1.50.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type;

[User] Also, sort the result by the total cost in descending order.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type
ORDER BY total_cost_per_type DESC;

[User] Finally, limit the output to the top 5 entries.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type
ORDER BY total_cost_per_type DESC
LIMIT 5;

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.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)


[User] Find all currently employed staff whose managers are no longer employed. Show the employee's full name, hire date, the manager's full name, and the manager's termination_date.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, e.hire_date, m.first_name || ' ' || m.last_name AS manager_name, m.termination_date FROM government_services.employees e JOIN government_services.employees m ON e.manager_employee_id = m.employee_id WHERE e.termination_date IS NULL AND m.termination_date IS NOT NULL;

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 government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )


[User] Provide a count of notifications, separated by whether they have been read or not.

[Assistant] SELECT CASE WHEN T1.read_at IS NULL THEN 'Unread' ELSE 'Read' END, count(T1.notification_id) FROM trading_platform.notifications AS T1 GROUP BY CASE WHEN T1.read_at IS NULL THEN 'Unread' ELSE 'Read' END

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.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] List pairs of distinct routes that originate from the same location but go to different destinations. Show the route ID and route number for both routes and the common origin location ID.

[Assistant]
SELECT
  r1.route_id AS route1_id,
  r1.route_number AS route1_number,
  r2.route_id AS route2_id,
  r2.route_number AS route2_number,
  r1.origin_location_id AS shared_origin_location_id
FROM transportation.routes AS r1
JOIN transportation.routes AS r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id < r2.route_id
WHERE
  r1.destination_location_id != r2.destination_location_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 transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )


[User] Show me a list of all achievements with their name, point value, and the title of the game they are part of.

[Assistant]
SELECT
  T1.name,
  T1.points,
  T2.title
FROM gaming_technology.achievements AS T1
JOIN gaming_technology.games AS T2
  ON T1.game_id = T2.game_id;

[User] Filter the list to only include achievements that are not hidden and have a point value greater than 10.

[Assistant]
SELECT
  T1.name,
  T1.points,
  T2.title
FROM gaming_technology.achievements AS T1
JOIN gaming_technology.games AS T2
  ON T1.game_id = T2.game_id
WHERE
  T1.hidden = FALSE AND T1.points > 10;

[User] Now, calculate the total points for these filtered achievements, grouped by game title.

[Assistant]
SELECT
  T2.title,
  SUM(T1.points) AS total_points
FROM gaming_technology.achievements AS T1
JOIN gaming_technology.games AS T2
  ON T1.game_id = T2.game_id
WHERE
  T1.hidden = FALSE AND T1.points > 10
GROUP BY
  T2.title
ORDER BY
  total_points 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.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.developers (
    developer_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the developer studio
    name character varying(150) NOT NULL UNIQUE, -- name of the development studio
    country character varying(100), -- country where the studio is based
    founded_year integer, -- year the studio was founded
    website character varying(255), -- developer's official website
    created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (developer_id)
)
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)


[User] For each ERC20 token, I need the total historical balance and number of unique holders from erc20_balances_historical. Include contract_address, total_balance, holder_count, symbol, and decimals.

[Assistant]
SELECT bh.contract_address,
       SUM(CAST(bh.amount AS numeric)) AS total_balance,
       COUNT(DISTINCT bh.wallet_address) AS holder_count,
       tm.symbol,
       tm.decimals
FROM erc20_balances_historical AS bh
JOIN token_metas AS tm
  ON bh.contract_address = tm.contract_address
GROUP BY bh.contract_address, tm.symbol, tm.decimals
ORDER BY total_balance DESC;

[User] Now filter only tokens where total_balance > 1000000 and sort by total_balance descending.

[Assistant]
SELECT bh.contract_address,
       SUM(CAST(bh.amount AS numeric)) AS total_balance,
       COUNT(DISTINCT bh.wallet_address) AS holder_count,
       tm.symbol,
       tm.decimals
FROM erc20_balances_historical AS bh
JOIN token_metas AS tm
  ON bh.contract_address = tm.contract_address
GROUP BY bh.contract_address, tm.symbol, tm.decimals
HAVING SUM(CAST(bh.amount AS numeric)) > 1000000
ORDER BY total_balance DESC;

[User] Also limit to top 5 tokens and include the latest USD price by joining token_prices_latest on address = contract_address.

[Assistant]
SELECT t.contract_address,
       t.total_balance,
       t.holder_count,
       t.symbol,
       t.decimals,
       tpl.price AS latest_price
FROM (
  SELECT bh.contract_address,
         SUM(CAST(bh.amount AS numeric)) AS total_balance,
         COUNT(DISTINCT bh.wallet_address) AS holder_count,
         tm.symbol,
         tm.decimals
  FROM erc20_balances_historical AS bh
  JOIN token_metas AS tm
    ON bh.contract_address = tm.contract_address
  GROUP BY bh.contract_address, tm.symbol, tm.decimals
  HAVING SUM(CAST(bh.amount AS numeric)) > 1000000
) AS t
JOIN token_prices_latest AS tpl
  ON t.contract_address = tpl.address
ORDER BY t.total_balance DESC
LIMIT 5;

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 erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances ( block_number bigint, contract_address 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 nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_coins ( object_id varchar, status varchar, coin_type varchar, balance varchar, owner 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_collections ( blockchain varchar, contract_address varchar, name varchar, symbol varchar, deploy_block_number bigint, deploy_block_time bigint, erc_type varchar, owner varchar, traits varchar, description varchar, slug varchar, media_info varchar, image_url varchar, banner_image_url varchar, updated_at bigint, banner varchar, token_count bigint, floor_price varchar, floor_price_symbol varchar, floor_price_contract varchar, 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_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_info_bitcoin ( 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_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, 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 the block_id, timestamp, and the total amount of transactions for each block, along with the sender and receiver addresses for each transaction that occurred on April 10th, 2023.

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, t.receiver_address, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
WHERE DATE(t.timestamp) = '2023-04-10'
GROUP BY b.block_id, b.timestamp, t.sender_address, t.receiver_address;

[User] Can you also include the balance of both sender and receiver addresses at the time of the transaction?

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, sa.balance AS sender_balance, t.receiver_address, ra.balance AS receiver_balance, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
LEFT JOIN blockchain.addresses sa ON t.sender_address = sa.address_id
LEFT JOIN blockchain.addresses ra ON t.receiver_address = ra.address_id
WHERE DATE(t.timestamp) = '2023-04-10'
GROUP BY b.block_id, b.timestamp, t.sender_address, sa.balance, t.receiver_address, ra.balance;

[User] Now only show those transactions where the sender's balance was greater than 5000 at that time.

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, sa.balance AS sender_balance, t.receiver_address, ra.balance AS receiver_balance, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
LEFT JOIN blockchain.addresses sa ON t.sender_address = sa.address_id
LEFT JOIN blockchain.addresses ra ON t.receiver_address = ra.address_id
WHERE DATE(t.timestamp) = '2023-04-10' AND sa.balance > 5000
GROUP BY b.block_id, b.timestamp, t.sender_address, sa.balance, t.receiver_address, ra.balance;

[User] Sorry, the sender_address seems incorrect. Use sender_address from transactions table instead of addresses.

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, sa.balance AS sender_balance, t.receiver_address, ra.balance AS receiver_balance, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
LEFT JOIN blockchain.addresses sa ON t.sender_address = sa.address_id
LEFT JOIN blockchain.addresses ra ON t.receiver_address = ra.address_id
WHERE DATE(t.timestamp) = '2023-04-10' AND sa.balance > 5000
GROUP BY b.block_id, b.timestamp, t.sender_address, sa.balance, t.receiver_address, ra.balance;

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 text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.addresses ( address_id text, public_key text, balance numeric )
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )


[User] Which locations have received fuel logs greater than 300 liters in total? Please include the location name and city.

[Assistant]
SELECT l.name AS location_name, l.city, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
GROUP BY l.location_id, l.name, l.city
HAVING SUM(f.quantity) > 300;

[User] Can you also include the number of times fuel was logged at each location?

[Assistant]
SELECT l.name AS location_name, l.city, COUNT(f.fuel_log_id) AS log_count, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
GROUP BY l.location_id, l.name, l.city
HAVING SUM(f.quantity) > 300;

[User] Actually, could you restrict it to only locations that are in 'New York' city?

[Assistant]
SELECT l.name AS location_name, l.city, COUNT(f.fuel_log_id) AS log_count, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
WHERE l.city = 'New York'
GROUP BY l.location_id, l.name, l.city
HAVING SUM(f.quantity) > 300;

[User] I got an error about ambiguous column in GROUP BY, can you fix and show only the columns used in SELECT in the GROUP BY?

[Assistant]
SELECT l.name AS location_name, l.city, COUNT(f.fuel_log_id) AS log_count, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
WHERE l.city = 'New York'
GROUP BY l.name, l.city
HAVING SUM(f.quantity) > 300;

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.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
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 )
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )


[User] Find currently employed employees whose direct manager has been terminated. Display the employee's full name, hire date, manager's full name, and manager's termination date.

[Assistant]
SELECT e.employee_id,
       CONCAT(e.first_name, ' ', e.last_name) AS employee_full_name,
       e.hire_date,
       CONCAT(m.first_name, ' ', m.last_name) AS manager_full_name,
       m.termination_date
FROM government_services.employees e
JOIN government_services.employees m ON e.manager_employee_id = m.employee_id
WHERE e.termination_date IS NULL
  AND m.termination_date IS NOT NULL;

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 government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )


[User] Show me the policy number, claim ID, document file name, and document type for all policies that have associated claim documents.

[Assistant] SELECT T1.policy_number, T2.claim_id, T3.file_name, T3.document_type FROM insurance.policies AS T1 JOIN insurance.claims AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.claim_documents AS T3 ON T2.claim_id = T3.claim_id;

[User] Only include policies that are currently 'Active'.

[Assistant] SELECT T1.policy_number, T2.claim_id, T3.file_name, T3.document_type FROM insurance.policies AS T1 JOIN insurance.claims AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.claim_documents AS T3 ON T2.claim_id = T3.claim_id WHERE T1.status = 'Active';

[User] Also, filter to only show documents with a file size greater than 1MB (1048576 bytes) and include the file size in the results.

[Assistant] SELECT T1.policy_number, T2.claim_id, T3.file_name, T3.document_type, T3.file_size_bytes FROM insurance.policies AS T1 JOIN insurance.claims AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.claim_documents AS T3 ON T2.claim_id = T3.claim_id WHERE T1.status = 'Active' AND T3.file_size_bytes IS NOT NULL AND T3.file_size_bytes > 1048576;

[User] Okay, just show the policy number, document file name, and file size, and sort by file size descending.

[Assistant] SELECT T1.policy_number, T3.file_name, T3.file_size_bytes FROM insurance.policies AS T1 JOIN insurance.claims AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.claim_documents AS T3 ON T2.claim_id = T3.claim_id WHERE T1.status = 'Active' AND T3.file_size_bytes IS NOT NULL AND T3.file_size_bytes > 1048576 ORDER BY T3.file_size_bytes 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 insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] Which doctors do not have an email address listed? Please show their doctor ID, first name, last name, and the hospital they are affiliated with.

[Assistant] SELECT doctor_id, first_name, last_name, hospital_affiliation_id FROM healthcare.doctors WHERE email IS NULL OR email = '';

[User] Add the created_at timestamp for each doctor and only include those created in 2024.

[Assistant] SELECT doctor_id, first_name, last_name, hospital_affiliation_id, created_at FROM healthcare.doctors WHERE (email IS NULL OR email = '') AND EXTRACT(YEAR FROM created_at) = 2024;

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, 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 )


[User] How many medications does each manufacturer have?

[Assistant]
SELECT manufacturer, COUNT(*) AS med_count
FROM healthcare.medications
GROUP BY manufacturer;

[User] Only include manufacturers with more than 10 medications.

[Assistant]
SELECT manufacturer, COUNT(*) AS med_count
FROM healthcare.medications
GROUP BY manufacturer
HAVING COUNT(*) > 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.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )


[User] What is the history of incidents or accidents that occurred on platform 5 at station GHI?

[Assistant] I'm sorry, but I can't provide information about the history of incidents or accidents on platform 5 at station GHI. My data is limited to the structural and operational details of the platforms, such as platform ID, station ID, and status. For incident history, you may need to consult a different database or contact the relevant authorities.

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.text, station_id.text, platform_number.text, track_number.text, status.text, length_meters.numeric, accessible.boolean )


[User] Show me the top 5 ERC20 tokens with the highest total supply, along with their names and contract addresses, but only include tokens with decimals equal to 18.

[Assistant] SELECT name, contract_address, total_supply FROM token_metas WHERE is_erc20 = 1 AND decimals = 18 ORDER BY CAST(total_supply AS decimal) DESC LIMIT 5;

[User] Can you join this with the erc20_balances table to show the total balance held across all wallets for each of these tokens?

[Assistant] SELECT tm.name, tm.contract_address, tm.total_supply, SUM(CAST(eb.amount AS decimal)) AS total_balance FROM token_metas tm JOIN erc20_balances eb ON tm.contract_address = eb.contract_address WHERE tm.is_erc20 = 1 AND tm.decimals = 18 GROUP BY tm.name, tm.contract_address, tm.total_supply ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] I think there's an error in your query - it should be SUM(CAST(eb.amount AS decimal)) without the extra parenthesis. Also, can you add the percentage of total supply that's currently held in wallets?

[Assistant] SELECT tm.name, tm.contract_address, tm.total_supply, SUM(CAST(eb.amount AS decimal)) AS total_balance, (SUM(CAST(eb.amount AS decimal)) / CAST(tm.total_supply AS decimal) * 100 AS percentage_held FROM token_metas tm JOIN erc20_balances eb ON tm.contract_address = eb.contract_address WHERE tm.is_erc20 = 1 AND tm.decimals = 18 GROUP BY tm.name, tm.contract_address, tm.total_supply ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

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 is the average speed of train number T9876 during its last journey?

[Assistant] I'm sorry, but I can't provide information on the average speed of train number T9876 during its last journey. The data in the trains table does not include details about travel speed or journey-specific performance metrics.

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.trains ( train_id.text, train_number.text, model.text, manufacturer.text, year_manufactured.integer, capacity.integer, status.text, last_maintenance_date.date, next_maintenance_date.date )


[User] Show each player's highest score for each game they have played.

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id;

[User] Only include games where the player's highest score is at least 500.

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500;

[User] For each result, could you also include the number of sessions that player has for that game?

[Assistant] SELECT player_id, game_id, COUNT(*) AS session_count, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500;

[User] Order the results by highest_score in descending order.

[Assistant] SELECT player_id, game_id, COUNT(*) AS session_count, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500 ORDER BY highest_score 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.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )


[User] How many distinct private keys are stored in the wallets table?

[Assistant] SELECT COUNT(DISTINCT private_key) FROM web3.wallets;

[User] Now, show me the distinct private keys themselves, along with the count of wallets associated with each key.

[Assistant] SELECT private_key, COUNT(wallet_id) AS wallet_count FROM web3.wallets GROUP BY private_key ORDER BY wallet_count 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 web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )


[User] What is the ticket price for a journey on train number T4321?

[Assistant] I'm sorry, but I don't have access to information about ticket prices for specific trains. The data I have is limited to train details such as model, manufacturer, capacity, and maintenance schedules. For ticket pricing, please consult the ticketing office or the official website.

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.trains ( train_id text PRIMARY KEY, train_number text UNIQUE, model text, manufacturer text, year_manufactured int, capacity int, status text, last_maintenance_date date, next_maintenance_date date )


[User] Find services that have associated documents with a 'Pending' verification status. Show the service name and the document type name.

[Assistant] SELECT DISTINCT s.service_name, dt.document_type_name FROM government_services.services AS s JOIN government_services.applications AS a ON s.service_id = a.service_id JOIN government_services.application_documents AS ad ON a.application_id = ad.application_id JOIN government_services.document_types AS dt ON ad.document_type_id = dt.document_type_id WHERE ad.verification_status = 'Pending';

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 government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)


[User] Find all wallets that were created on the same day and list their wallet IDs, addresses, and the creation date.

[Assistant] SELECT w1.wallet_id, w1.address, w1.created_at::date AS creation_date FROM web3.wallets w1 JOIN (SELECT created_at::date AS creation_date FROM web3.wallets GROUP BY created_at::date HAVING COUNT(*) > 1) w2 ON w1.created_at::date = w2.creation_date ORDER BY creation_date, w1.wallet_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.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)


[User] What is the total market cap for all tokens listed on the 'Polygon' chain?

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon';

[User] Only sum the market cap for tokens on 'Polygon' that have a 24-hour volume greater than 500000.

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Also show the number of unique tokens that meet these criteria.

[Assistant] SELECT COUNT(DISTINCT token_symbol), SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Can you show the total market cap and token count for *each* chain that meets these volume criteria, ordered by total market cap descending?

[Assistant] SELECT chain, COUNT(DISTINCT token_symbol) AS token_count, SUM(market_cap) AS total_market_cap FROM token_dexpool_info WHERE volume_24h > 500000 GROUP BY chain ORDER BY total_market_cap 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 token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool 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_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )


[User] List all assets mentioned in DApp descriptions along with the DApp name and URL.

[Assistant]
SELECT a.name AS asset_name,
       a.symbol AS asset_symbol,
       d.name AS dapp_name,
       d.url
FROM trading_platform.assets a
JOIN trading_platform.dapps d
  ON d.description ILIKE '%' || a.symbol || '%';

[User] Actually, only include assets of type 'cryptocurrency'.

[Assistant]
SELECT a.name AS asset_name,
       a.symbol AS asset_symbol,
       d.name AS dapp_name,
       d.url
FROM trading_platform.assets a
JOIN trading_platform.dapps d
  ON d.description ILIKE '%' || a.symbol || '%'
WHERE a.type = 'cryptocurrency';

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.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)


[User] I need to find all components associated with a specific supplier. Can you help with that?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE

[User] Can you also show me the material ID for each of these components?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE
HGET component:<component_id> material_id

[User] What if I want to exclude components with a specific material ID?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE
HGET component:<component_id> material_id
IF HGET component:<component_id> material_id != 'mat:TI64' THEN INCLUDE

[User] Can you add the component name to the result as well?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE
HGET component:<component_id> material_id
IF HGET component:<component_id> material_id != 'mat:TI64' THEN INCLUDE
HGET component:<component_id> component_name

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Use Hashes. Key pattern: 'component:<component_id>'. Example: HSET component:LGSTRUT01 part_number "PN-5521-A" component_name "Landing Gear Strut" material_id "mat:TI64" supplier_id "sup:ACME_AERO" ... Consider Sets for reverse lookups (e.g., 'material_components:<material_id>' -> Set<component_id>).


[User] Show me all reservations with their reservation_id, room_number, room status, and check_in_date.

[Assistant]
SELECT r.reservation_id,
       rm.room_number,
       rm.status AS room_status,
       r.check_in_date
FROM hospitality_technology.reservations r
LEFT JOIN hospitality_technology.rooms rm
  ON r.room_id = rm.room_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 hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )


[User] List all events and any token transfers that occurred in the same transaction, showing event_id, event_name, transfer_id, and token_symbol.

[Assistant]
SELECT
  e.event_id,
  e.event_name,
  tt.transfer_id,
  tk.token_symbol
FROM web3.events e
LEFT JOIN web3.token_transfers tt
  ON e.transaction_id = tt.transaction_id
LEFT JOIN web3.tokens tk
  ON tt.token_id = tk.token_id
ORDER BY e.transaction_id, e.log_index;

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.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] For each patient, calculate the total duration of all their completed appointments. Show the patient ID and the total duration in minutes, sorted by total duration descending.

[Assistant] SELECT patient_id, SUM(duration_minutes) AS total_completed_duration FROM healthcare.appointments WHERE status = 'Completed' GROUP BY patient_id ORDER BY total_completed_duration 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 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)
)