[User] List all ERC20 tokens where the price is between $1 and $10, including their names, symbols, and contract addresses.

[Assistant] SELECT name, symbol, address FROM token_prices_latest WHERE price BETWEEN 1 AND 10 AND blockchain = 'ethereum';

[User] I think there's an error in your query - it should be joining with sui_coins_metadata on coin_type not address. Also, can you add the current price to the results?

[Assistant] SELECT scm.name, scm.symbol, scm.coin_type, tpl.price FROM sui_coins_metadata scm JOIN token_prices_latest tpl ON scm.coin_type = tpl.address WHERE tpl.price BETWEEN 1 AND 10;

[User] Now filter these results to only show tokens with decimals equal to 18 and sort by name alphabetically.

[Assistant] SELECT scm.name, scm.symbol, scm.coin_type, tpl.price FROM sui_coins_metadata scm JOIN token_prices_latest tpl ON scm.coin_type = tpl.address WHERE tpl.price BETWEEN 1 AND 10 AND scm.decimals = 18 ORDER BY scm.name ASC;


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

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

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


[User] Show the total payment amount and the count of payments for each payment method with status 'Completed'.

[Assistant] SELECT payment_method, SUM(amount), COUNT(*) FROM government_services.payments WHERE status = 'Completed' GROUP BY payment_method;

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.payments ( payment_id.text, 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 )


[User] List all individual token holdings by CEX addresses on the 'Arbitrum' chain with a USD value greater than $100,000. Show the exchange, token symbol, and USD value.

[Assistant] SELECT exchange, token_symbol, usd_value FROM cex_token_balance WHERE chain = 'Arbitrum' AND usd_value > 100000;

[User] Can you calculate the total USD value held by all CEXes for *each token* on the 'Arbitrum' chain, considering only holdings greater than $100,000? Show the token symbol and the total USD value.

[Assistant] SELECT token_symbol, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'Arbitrum' AND usd_value > 100000 GROUP BY token_symbol;

[User] Now, join this with the basic info table to include the token's narrative and its current price.

[Assistant] SELECT aggregated_cex.token_symbol, aggregated_cex.total_usd_value, tbi.narrative, tbi.price AS current_price FROM ( SELECT token_symbol, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'Arbitrum' AND usd_value > 100000 GROUP BY token_symbol ) AS aggregated_cex JOIN token_basic_info AS tbi ON aggregated_cex.token_symbol = tbi.token_symbol AND 'Arbitrum' = tbi.chain;

[User] Filter these results to only show tokens belonging to the 'DeFi' or 'AI' narratives and order by total USD value descending, showing the top 5.

[Assistant] SELECT aggregated_cex.token_symbol, aggregated_cex.total_usd_value, tbi.narrative, tbi.price AS current_price FROM ( SELECT token_symbol, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'Arbitrum' AND usd_value > 100000 GROUP BY token_symbol ) AS aggregated_cex JOIN token_basic_info AS tbi ON aggregated_cex.token_symbol = tbi.token_symbol AND 'Arbitrum' = tbi.chain WHERE tbi.narrative IN ('DeFi', 'AI') ORDER BY aggregated_cex.total_usd_value 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_basic_info ( coin_id.text, token_name.text, token_symbol.text, token_address.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, highest_price_24h.numeric, lowest_price_24h.numeric, market_cap.numeric, market_cap_rank.numeric, market_cap_change_percentage_24h.text, total_volume.text, narrative.text, trend_rank.numeric )
CREATE TABLE token_dexpool_info ( pair_address.text, token_name.text, token_symbol.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_6h.numeric, price_change_percentage_24h.numeric, makers_24h.numeric, volume_24h.numeric, liquidity.numeric, market_cap.numeric, trend_rank.numeric )
CREATE TABLE cex_token_balance ( snapshot_time.text, chain.text, address.text, exchange.text, token_address.text, token_symbol.text, balance.numeric, usd_value.numeric, price.numeric )
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )


[User] For each achievement, show its name, the game_id it belongs to, and the number of distinct players who have played a session for that game.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id;

[User] Now, filter to only include achievements for games that have at least 50 players who have played a session.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id
HAVING COUNT(DISTINCT gs.player_id) >= 50;

[User] Please also include the number of times each achievement has been unlocked by unique players, labeled as unique_unlocks.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions,
       (SELECT COUNT(DISTINCT gs2.player_id)
        FROM gaming_technology.game_sessions gs2
        WHERE gs2.game_id = a.game_id) AS unique_unlocks
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id
HAVING COUNT(DISTINCT gs.player_id) >= 50;

[User] I think unique_unlocks should be the count of distinct players who have unlocked each specific achievement, not just played a session. Can you correct that?

[Assistant] -- With the provided tables, there is no direct record of players unlocking a specific achievement, unless unlocking is inferred elsewhere. If you have an achievement unlocks table, you could join it here. Otherwise, only possible to count sessions per game.

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, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )


[User] Retrieve the most recent log entry for each user, including action and logged_at.

[Assistant]
SELECT l1.user_id,
       l1.action,
       l1.logged_at
FROM trading_platform.logs l1
WHERE l1.logged_at = (
  SELECT MAX(l2.logged_at)
  FROM trading_platform.logs l2
  WHERE l2.user_id = l1.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 trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_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)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)


[User] Show me each achievement name and the number of players who have unlocked it.

[Assistant]
SELECT a.name,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name;

[User] Now only include achievements with at least 20 unlocks, and display their points as well.

[Assistant]
SELECT a.name,
       a.points,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name, a.points
HAVING COUNT(pa.player_id) >= 20;

[User] Finally, include the game_id for each achievement and sort by unlock_count descending.

[Assistant]
SELECT a.game_id,
       a.name,
       a.points,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.game_id, a.name, a.points
HAVING COUNT(pa.player_id) >= 20
ORDER BY unlock_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 gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.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, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )


[User] Count how many achievements were unlocked on each calendar day. Show the date and the count.

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count FROM gaming_technology.player_achievements GROUP BY unlock_date;

[User] Only include dates where more than 50 achievements were unlocked.

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count FROM gaming_technology.player_achievements GROUP BY unlock_date HAVING COUNT(*) > 50;

[User] Additionally, include the number of *distinct players* who unlocked achievements on each of those dates.

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count, COUNT(DISTINCT player_id) AS distinct_players FROM gaming_technology.player_achievements GROUP BY unlock_date HAVING COUNT(*) > 50;

[User] Order the results by the distinct player count in descending order.

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count, COUNT(DISTINCT player_id) AS distinct_players FROM gaming_technology.player_achievements GROUP BY unlock_date HAVING COUNT(*) > 50 ORDER BY distinct_players 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(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.developers ( developer_id uuid NOT NULL DEFAULT gen_random_uuid(), name character varying(150) NOT NULL UNIQUE, country character varying(100), founded_year integer, website character varying(255), created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (developer_id) )
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, name character varying(150) NOT NULL, description text NOT NULL, icon_url character varying(255), points integer DEFAULT 0, hidden boolean DEFAULT false, PRIMARY KEY (achievement_id) )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )


[User] List all medical record entries where the treatment_plan mentions a medication name. Return patient_id, record_id, and the matching medication_name.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%';

[User] Actually, only include medications manufactured by 'Pfizer'.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE m.manufacturer = 'Pfizer';

[User] Also sort the results by record_date descending.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE m.manufacturer = 'Pfizer'
ORDER BY mr.record_date 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.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List all securities (security_id, ticker_symbol, security_name) that have a currency of 'EUR' and were last updated within the last 30 days, along with their exchange and sector information.

[Assistant] SELECT security_id, ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE currency = 'EUR' AND last_updated >= CURRENT_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 financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)


[User] Show me all claim documents uploaded by customers between January 1, 2023 and December 31, 2023. Include document ID, file name, uploaded time, and the customer ID.

[Assistant] SELECT T1.document_id, T1.file_name, T1.uploaded_at, T2.customer_id FROM insurance.claim_documents AS T1 JOIN insurance.customers AS T2 ON T1.uploaded_by = T2.customer_id WHERE T1.uploaded_at BETWEEN '2023-01-01 00:00:00' AND '2023-12-31 23:59:59';

[User] For those documents uploaded by customers in 2023, count how many were uploaded by customers whose status is 'inactive'. Show the count.

[Assistant] SELECT COUNT(T1.document_id) FROM insurance.claim_documents AS T1 JOIN insurance.customers AS T2 ON T1.uploaded_by = T2.customer_id WHERE T1.uploaded_at BETWEEN '2023-01-01 00:00:00' AND '2023-12-31 23:59:59' AND T2.status = 'inactive';

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.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )


[User] Count the number of posts that have a media URL but no textual content.

[Assistant] SELECT COUNT(*) FROM social_media.posts AS T1 WHERE T1.media_url IS NOT NULL AND (T1.content IS NULL OR T1.content = '');

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)


[User] List the plan ID, name, provider, and type for all insurance plans from 'Healthcare Partners' with a plan type of 'PPO'.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO';

[User] Now, only show those plans that also have a website listed.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL;

[User] Further refine the results to only include plans where the plan name contains the word 'Plus'.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL AND plan_name ILIKE '%Plus%';

[User] Finally, count how many such plans exist.

[Assistant] SELECT COUNT(*) FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL AND plan_name ILIKE '%Plus%';

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.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )


[User] Now, sort the results by the date opened, oldest first, and show only the top 10.

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE lead_lawyer_id = 'lawyer_abc' AND status = 'Open' AND case_type = 'Criminal' ORDER BY date_opened ASC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )


[User] List the first and last names of employees and the full name of the citizens for whom they have scheduled appointments.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T3.first_name ,  T3.last_name FROM government_services.employees AS T1 JOIN government_services.appointments AS T2 ON T1.employee_id  =  T2.employee_id JOIN government_services.citizens AS T3 ON T2.citizen_id  =  T3.citizen_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 government_services.citizens ( citizen_id text PRIMARY KEY, 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 text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
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 text PRIMARY KEY, 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 )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] How many claims were reported in the last 90 days?

[Assistant] SELECT COUNT(*) FROM claims WHERE reported_date >= CURRENT_DATE - INTERVAL '90 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 insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, 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, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
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] How many unread notifications are there with the type 'mention'?

[Assistant] SELECT COUNT(*) FROM social_media.notifications WHERE read_at IS NULL AND notification_type = 'mention';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)


[User] For each user, show their user ID and the count of unique wallet addresses they own.

[Assistant] SELECT user_id, COUNT(DISTINCT address) FROM wallets GROUP BY 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 trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )


[User] List all patients who have insurance plans with group numbers, showing their patient IDs and the count of such plans per patient.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id;

[User] Actually, I only need patients who have more than 2 such plans.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

[User] Can you also include the earliest effective date among these plans for each patient?

[Assistant] SELECT patient_id, COUNT(*) AS plan_count, MIN(effective_date) AS earliest_effective_date FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

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.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List all active SUI coins with status 'exists' in metadata, showing coin_type, symbol, name, balance, and description.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sc.balance, sm.description
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists';

[User] Limit to coins where balance > 1000000 and order by balance descending.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sc.balance, sm.description
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
ORDER BY CAST(sc.balance AS numeric) DESC;

[User] Also include the number of distinct owners per coin_type.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sm.description,
       SUM(CAST(sc.balance AS numeric)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
GROUP BY sc.coin_type, sm.symbol, sm.name, sm.description
ORDER BY total_balance DESC;

[User] Only show the top 3 coins by total_balance.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sm.description,
       SUM(CAST(sc.balance AS numeric)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
GROUP BY sc.coin_type, sm.symbol, sm.name, sm.description
ORDER BY total_balance DESC
LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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 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 text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
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 token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( 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, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


[User] List all auto loans (loan_id, principal_amount, interest_rate) where the current principal balance is less than 40% of the original principal amount, along with the account_id and the difference between principal_amount and current_principal_balance.

[Assistant] SELECT loan_id, principal_amount, interest_rate, account_id, (principal_amount - current_principal_balance) AS amount_paid FROM financial_services.loans WHERE loan_type = 'Auto' AND current_principal_balance < (0.4 * principal_amount);

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.loans ( loan_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL UNIQUE, loan_type character varying(50) NOT NULL, principal_amount numeric(19, 4) NOT NULL, current_principal_balance numeric(19, 4) NOT NULL, interest_rate numeric(6, 4) NOT NULL, term_months integer NOT NULL, origination_date date NOT NULL, maturity_date date NOT NULL, monthly_payment numeric(12, 4), collateral_description text, status character varying(32) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id) )


[User] List the full names and email addresses of citizens who have submitted an application but have not uploaded any documents for that application. Display the citizen's full name, application_id, and submitted_at.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name,
       c.contact_email,
       a.application_id,
       a.submitted_at
FROM government_services.applications a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
LEFT JOIN government_services.documents d ON a.application_id = d.application_id
WHERE d.document_id IS 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 character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
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 )
CREATE TABLE government_services.service_locations ( location_id.text, 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 text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )


[User] List all wallets holding the NFT with contract_address '0xabc123' and token_id '100' and the amount held.

[Assistant]
SELECT wallet_address, amount
FROM nft_holders
WHERE contract_address = '0xabc123'
  AND token_id = '100';

[User] Also include the NFT name from nft_metadata by joining on contract_address and token_id.

[Assistant]
SELECT nh.wallet_address,
       nh.amount,
       nm.name
FROM nft_holders nh
JOIN nft_metadata nm ON nh.contract_address = nm.contract_address
                   AND nh.token_id = nm.token_id
WHERE nh.contract_address = '0xabc123'
  AND nh.token_id = '100';

[User] Finally, add the collection name from nft_collections where blockchain is 'Ethereum'.

[Assistant]
SELECT nh.wallet_address,
       nh.amount,
       nm.name,
       nc.name AS collection_name
FROM nft_holders nh
JOIN nft_metadata nm ON nh.contract_address = nm.contract_address
                   AND nh.token_id = nm.token_id
JOIN nft_collections nc ON nh.contract_address = nc.contract_address
                      AND nc.blockchain = 'Ethereum'
WHERE nh.contract_address = '0xabc123'
  AND nh.token_id = '100';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
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 erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
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, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id varchar NOT NULL, status varchar NOT NULL, collection_type varchar NOT NULL, package_id varchar NOT NULL, previous_transaction varchar NOT NULL, display varchar NOT NULL, owner varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
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 NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp(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(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )


[User] Show the latest version number of each document_name for every case.

[Assistant]
SELECT case_id,
       document_name,
       MAX(version) AS latest_version
FROM legal_services.documents
GROUP BY case_id, document_name;

[User] Actually, I also need the upload_timestamp of that latest version.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id,
         document_name,
         MAX(version) AS latest_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) sub
  ON d.case_id = sub.case_id
 AND d.document_name = sub.document_name
 AND d.version = sub.latest_version;

[User] Also include the uploaded_by_lawyer_id for each latest version.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version AS latest_version,
       d.upload_timestamp,
       d.uploaded_by_lawyer_id
FROM legal_services.documents d
JOIN (
  SELECT case_id,
         document_name,
         MAX(version) AS latest_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) sub
  ON d.case_id = sub.case_id
 AND d.document_name = sub.document_name
 AND d.version = sub.latest_version;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )


[User] List usernames and the length of their 'bio' field for users whose 'is_verified' status is true.

[Assistant] SELECT username, LENGTH(bio) AS bio_length FROM social_media.users WHERE is_verified IS TRUE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )


[User] Find all nodes that were last seen in the last 7 days, along with their IP addresses and ports.

[Assistant] SELECT node_id, ip_address, port FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '7 days';

[User] Now filter these results to only show nodes with port numbers between 8000 and 9000.

[Assistant] SELECT node_id, ip_address, port FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '7 days' AND port BETWEEN 8000 AND 9000;

[User] How many unique IP addresses are there among these active nodes?

[Assistant] SELECT COUNT(DISTINCT ip_address) FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '7 days' AND port BETWEEN 8000 AND 9000;

[User] Can you show me the count of nodes for each unique IP address?

[Assistant] SELECT ip_address, COUNT(node_id) AS node_count FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '7 days' AND port BETWEEN 8000 AND 9000 GROUP BY ip_address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text, previous_block_id text, timestamp timestamp, nonce integer, merkle_root text, difficulty integer )
CREATE TABLE blockchain.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction
    sender_address character varying(128) NOT NULL, -- address of the sender
    receiver_address character varying(128) NOT NULL, -- address of the receiver
    amount numeric(38,14) NOT NULL, -- amount transferred
    timestamp timestamp NOT NULL, -- time when the transaction was created
    signature text NOT NULL, -- digital signature of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE blockchain.addresses ( address_id text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.nodes (
    node_id character varying(64) NOT NULL,  -- unique identifier for the node
    ip_address character varying(15) NOT NULL, -- IP address of the node
    port integer NOT NULL, -- port number of the node
    last_seen timestamp NOT NULL, -- last time the node was active
    PRIMARY KEY (node_id)
)
CREATE TABLE blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )


[User] Count the number of smart contracts deployed for each unique creator address.

[Assistant] SELECT creator_address, COUNT(*) FROM blockchain.smart_contracts GROUP BY creator_address;

[User] Show me only those creators who have deployed more than 50 contracts in total.

[Assistant] SELECT creator_address, COUNT(*) FROM blockchain.smart_contracts GROUP BY creator_address HAVING COUNT(*) > 50;

[User] Order the results by the contract count in descending order.

[Assistant] SELECT creator_address, COUNT(*) FROM blockchain.smart_contracts GROUP BY creator_address HAVING COUNT(*) > 50 ORDER BY 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 blockchain.smart_contracts ( contract_id.text, creator_address.text, code.text, timestamp.timestamp )


[User] For each group chat, list its ID, name, creation time, and the creation time of the next group chat created after it, ordered by creation time.

[Assistant] SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ORDER BY created_at;

[User] Only show pairs where the next group chat was created within 48 hours of the current one, and also include the time difference in hours.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 ORDER BY created_at;

[User] Further refine: Only include group chats whose names contain 'Discuss'.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 AND group_name LIKE '%Discuss%' ORDER BY created_at;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )


[User] I want to find the total number of ERC1155 "approval-for-all" events per contract. Show contract_address and the approval_count.

[Assistant]
SELECT contract_address, COUNT(*) AS approval_count
FROM erc1155_approval_for_all
GROUP BY contract_address;

[User] Also show the number of unique wallet holders currently holding any token from those contracts by joining to nft_holders.

[Assistant]
SELECT a.contract_address,
       a.approval_count,
       COALESCE(b.holder_count, 0) AS holder_count
FROM (
  SELECT contract_address, COUNT(*) AS approval_count
  FROM erc1155_approval_for_all
  GROUP BY contract_address
) a
LEFT JOIN (
  SELECT contract_address, COUNT(DISTINCT wallet_address) AS holder_count
  FROM nft_holders
  GROUP BY contract_address
) b
  ON a.contract_address = b.contract_address;

[User] Filter to only include contracts where holder_count is greater than 50.

[Assistant]
SELECT a.contract_address,
       a.approval_count,
       b.holder_count
FROM (
  SELECT contract_address, COUNT(*) AS approval_count
  FROM erc1155_approval_for_all
  GROUP BY contract_address
) a
JOIN (
  SELECT contract_address, COUNT(DISTINCT wallet_address) AS holder_count
  FROM nft_holders
  GROUP BY contract_address
  HAVING COUNT(DISTINCT wallet_address) > 50
) b
  ON a.contract_address = b.contract_address;

[User] Sort results by approval_count descending and limit to the top 10.

[Assistant]
SELECT a.contract_address,
       a.approval_count,
       b.holder_count
FROM (
  SELECT contract_address, COUNT(*) AS approval_count
  FROM erc1155_approval_for_all
  GROUP BY contract_address
) a
JOIN (
  SELECT contract_address, COUNT(DISTINCT wallet_address) AS holder_count
  FROM nft_holders
  GROUP BY contract_address
  HAVING COUNT(DISTINCT wallet_address) > 50
) b
  ON a.contract_address = b.contract_address
ORDER BY a.approval_count DESC
LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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_historical ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_metadata (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )


[User] How many employees work in each department? List the department name and the count.

[Assistant] SELECT department, COUNT(*) FROM government_services.employees GROUP BY department

[User] Only show departments with more than 5 employees.

[Assistant] SELECT department, COUNT(*) FROM government_services.employees GROUP BY department HAVING COUNT(*) > 5

[User] For these departments, also list the job titles present.

[Assistant] SELECT department, COUNT(*), STRING_AGG(DISTINCT job_title, ', ') FROM government_services.employees GROUP BY department HAVING COUNT(*) > 5

[User] Add the total number of employees hired in 2023 for each of these departments.

[Assistant] SELECT department, COUNT(*), STRING_AGG(DISTINCT job_title, ', '), SUM(CASE WHEN EXTRACT(YEAR FROM hire_date) = 2023 THEN 1 ELSE 0 END) AS employees_hired_in_2023 FROM government_services.employees GROUP BY department HAVING COUNT(*) > 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 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 text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
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 )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )


[User] Show me all room types with 'King' in the bed_type field, along with their property IDs and base rates.

[Assistant] SELECT room_type_id, property_id, type_name, bed_type, base_rate FROM hospitality_technology.room_types WHERE bed_type LIKE '%King%';

[User] Now, join this with the guests table to show only room types from properties where the guest's country code is 'USA' and the guest is a loyalty member.

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.type_name, rt.bed_type, rt.base_rate FROM hospitality_technology.room_types rt JOIN hospitality_technology.guests g ON rt.property_id = g.property_id WHERE rt.bed_type LIKE '%King%' AND g.country_code = 'USA' AND g.loyalty_member_id IS NOT NULL;

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

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.type_name, rt.bed_type, rt.base_rate, rt.max_occupancy FROM hospitality_technology.room_types rt JOIN hospitality_technology.guests g ON rt.property_id = g.property_id WHERE rt.bed_type LIKE '%King%' AND g.country_code = 'USA' AND g.loyalty_member_id IS NOT NULL;

[User] Actually, I need to see only room types with a base rate below $300, and order them by max occupancy in descending order.

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.type_name, rt.bed_type, rt.base_rate, rt.max_occupancy FROM hospitality_technology.room_types rt JOIN hospitality_technology.guests g ON rt.property_id = g.property_id WHERE rt.bed_type LIKE '%King%' AND g.country_code = 'USA' AND g.loyalty_member_id IS NOT NULL AND rt.base_rate < 300 ORDER BY rt.max_occupancy DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )


[User] Find all wallets created by users in the last 7 days along with any tokens that have a total supply greater than 10 million, showing the wallet address and token details.

[Assistant] SELECT w.address AS wallet_address, t.token_name, t.token_symbol, t.total_supply, t.contract_address FROM web3.wallets w JOIN web3.tokens t ON t.total_supply > 10000000 WHERE w.created_at >= CURRENT_DATE - INTERVAL '7 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 web3.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) )
CREATE TABLE web3.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )


[User] For each employee who has verified more than one document, list their employee ID, the first document they verified, and the next document they verified, along with both verification timestamps.

[Assistant]
SELECT
  d1.verified_by_employee_id AS employee_id,
  d1.document_id AS first_verified_document,
  d1.verification_timestamp AS first_verification_time,
  d2.document_id AS next_verified_document,
  d2.verification_timestamp AS next_verification_time
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.verified_by_employee_id = d2.verified_by_employee_id
  AND d2.verification_timestamp > d1.verification_timestamp
WHERE d1.verification_status = 'Verified'
  AND d2.verification_status = 'Verified';

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.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )


[User] Find appointments that are longer than 30 minutes.

[Assistant] SELECT * FROM legal_services.appointments WHERE end_time IS NOT NULL AND start_time IS NOT NULL AND end_time > start_time + INTERVAL '30 minutes'

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.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )


[User] List all claims that were reported more than 30 days after the incident date.

[Assistant] SELECT claim_id, policy_id, customer_id, incident_date, reported_date FROM insurance.claims WHERE DATEDIFF(reported_date, incident_date) > 30;

[User] Now show only claims that are still pending (status = 'pending').

[Assistant] SELECT claim_id, policy_id, customer_id, incident_date, reported_date FROM insurance.claims WHERE DATEDIFF(reported_date, incident_date) > 30 AND 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 insurance.claims ( claim_id.text, 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 )


[User] Show me all transactions (transaction_id, amount, transaction_type) where the transaction_type is 'Transfer' and the status is 'Completed', along with the account_id and related_account_id.

[Assistant] SELECT transaction_id, amount, transaction_type, account_id, related_account_id FROM financial_services.transactions WHERE transaction_type = 'Transfer' AND status = 'Completed';

[User] Now modify the query to include only transfers with amounts greater than $1,000 and sort them by transaction_date in descending order.

[Assistant] SELECT transaction_id, amount, transaction_type, account_id, related_account_id FROM financial_services.transactions WHERE transaction_type = 'Transfer' AND status = 'Completed' AND amount > 1000 ORDER BY transaction_date 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 financial_services.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    PRIMARY KEY (transaction_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id)
)
CREATE TABLE financial_services.trades ( trade_id text, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )


[User] List all 'Evidence' documents uploaded in the last 30 days, including document_name, case_number, case_name, and upload_timestamp.

[Assistant]
SELECT d.document_name, c.case_number, c.case_name, d.upload_timestamp
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id
WHERE d.document_type = 'Evidence'
  AND d.upload_timestamp >= NOW() - 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 legal_services.cases ( case_id text PRIMARY KEY, case_number text UNIQUE, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.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 )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )


[User] What is the total amount paid across all premium payments for payments marked as 'Failed'?

[Assistant] SELECT sum(amount_paid) FROM insurance.premium_payments WHERE status = 'Failed';

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.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.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, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
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 )