System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )

[User] Show the tokens with a negative net flow this month on all chains.

[Assistant] SELECT token_symbol, chain, net_flow FROM smart_money_token_performance WHERE net_flow < 0 AND date_trunc('month', CURRENT_DATE) = date_trunc('month', now());

[User] Order them by net flow ascending and only show the bottom 5.

[Assistant] SELECT token_symbol, chain, net_flow FROM smart_money_token_performance WHERE net_flow < 0 AND date_trunc('month', CURRENT_DATE) = date_trunc('month', now()) ORDER BY net_flow ASC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), 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 the contact phone and website for all insurance plans provided by 'Continental Health'.

[Assistant]
SELECT plan_name, contact_phone, website
FROM healthcare.insurance_plans
WHERE insurance_provider = 'Continental Health';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )

[User] Which are the top 5 smart money addresses with the highest ROI on the BSC chain, and what are their profit, realized ratio, and most profitable token?

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token FROM smart_money_profit WHERE chain = 'BSC' ORDER BY roi DESC LIMIT 5;

[User] Can you also include their rank and last trade time in the output?

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' ORDER BY roi DESC LIMIT 5;

[User] I only want to see addresses with a profit above $10,000 and a realized ratio higher than 0.8.

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' AND profit > 10000 AND realized_ratio > 0.8 ORDER BY roi DESC LIMIT 5;

[User] Now, show the top one among these by profit instead of ROI.

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' AND profit > 10000 AND realized_ratio > 0.8 ORDER BY profit DESC LIMIT 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )

[User] Show me each invoice and the invoice_number of the next invoice for the same client, along with how many days apart their issue_dates are.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date;

[User] Please restrict to pairs where the days_between is greater than 30.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date
 WHERE (b.issue_date - a.issue_date) > 30;

[User] And only include pairs where both invoices have status 'Overdue'.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date
 WHERE (b.issue_date - a.issue_date) > 30
   AND a.status = 'Overdue'
   AND b.status = 'Overdue';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )

[User] Could you list the title of each game and the total quantity of items acquired by players for that specific game?

[Assistant] SELECT g.title, SUM(pi.quantity) AS total_acquired_quantity FROM gaming_technology.games g JOIN gaming_technology.player_inventory pi ON g.game_id = pi.item_id GROUP BY g.title;

[User] Now, I only want to include games where the total acquired quantity is more than 100.

[Assistant] SELECT g.title, SUM(pi.quantity) AS total_acquired_quantity FROM gaming_technology.games g JOIN gaming_technology.player_inventory pi ON g.game_id = pi.item_id GROUP BY g.title HAVING SUM(pi.quantity) > 100;

[User] Please filter the results further to include only games from the 'Action' genre.

[Assistant] SELECT g.title, SUM(pi.quantity) AS total_acquired_quantity FROM gaming_technology.games g JOIN gaming_technology.player_inventory pi ON g.game_id = pi.item_id WHERE g.genre = 'Action' GROUP BY g.title HAVING SUM(pi.quantity) > 100;

[User] Finally, order the results by the total acquired quantity in descending order.

[Assistant] SELECT g.title, SUM(pi.quantity) AS total_acquired_quantity FROM gaming_technology.games g JOIN gaming_technology.player_inventory pi ON g.game_id = pi.item_id WHERE g.genre = 'Action' GROUP BY g.title HAVING SUM(pi.quantity) > 100 ORDER BY total_acquired_quantity DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.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.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )

[User] How many posts have been updated after they were created?

[Assistant]
SELECT COUNT(*) AS updated_post_count
FROM social_media.posts
WHERE updated_at IS NOT NULL AND updated_at > created_at;


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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )
CREATE TABLE token_basic_info ( coin_id.text, token_name.text, token_symbol.text, token_address.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, highest_price_24h.numeric, lowest_price_24h.numeric, market_cap.numeric, market_cap_rank.numeric, market_cap_change_percentage_24h.text, total_volume.text, narrative.text, trend_rank.numeric )
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
CREATE TABLE 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_profit ( address.text, rank.numeric, profit.numeric, roi.numeric, realized_ratio.numeric, most_profit_token.text, last_trade_time.text, chain.text )
CREATE TABLE smart_money_token_inflow ( token_address.text, token_symbol.text, token_amount.numeric, usd_value.numeric, avg_price.numeric, type.numeric, address_amount.numeric, narrative.text, chain.text )

[User] List all projects that raised funds in March 2023. For each project, show its name, amount raised, fundraising round, and the token symbol and price of its associated token.

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023-03%'

[User] Can you also include the current market cap and chain of each token in the result?

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price, t.market_cap, t.chain
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023-03%'

[User] I only want to see projects that raised more than $5,000,000. Please update the query.

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price, t.market_cap, t.chain
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023-03%' AND p.investment_value > 5000000

[User] It seems some tokens are not matched because names are not identical. Can you try joining where the token_name contains the project_name (case-insensitive)?

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price, t.market_cap, t.chain
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(t.token_name) LIKE '%' || LOWER(p.project_name) || '%'
WHERE p.investment_date LIKE '2023-03%' AND p.investment_value > 5000000


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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )

[User] Show all users who registered before 2023-01-01, along with their usernames and registration dates.

[Assistant]
SELECT user_id, username, created_at
FROM web3.users
WHERE created_at < '2023-01-01';

[User] Can you additionally include their email addresses in the result?

[Assistant]
SELECT user_id, username, email, created_at
FROM web3.users
WHERE created_at < '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text 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 )

[User] Show me the first and last names of citizens along with their dates of birth and contact emails for all citizens who registered after January 1, 2023.

[Assistant] SELECT first_name, last_name, date_of_birth, contact_email FROM government_services.citizens WHERE registration_date > '2023-01-01';

[User] Only include citizens whose accounts are verified.

[Assistant] SELECT first_name, last_name, date_of_birth, contact_email FROM government_services.citizens WHERE registration_date > '2023-01-01' AND is_verified = true;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text 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.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.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.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] Show the names of all services and the names of their corresponding agencies that are offered at accessible locations in 'Chicago'.

[Assistant]
SELECT s.service_name, sl.agency_id
FROM government_services.service_locations sl
JOIN government_services.services s ON sl.agency_id = s.agency_id
WHERE sl.city = 'Chicago' AND sl.is_accessible = TRUE;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
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 'exists'-status coins from sui_coins_metadata with more than 8 decimals, showing coin_type, symbol, name, and decimals.

[Assistant] SELECT coin_type, symbol, name, decimals FROM sui_coins_metadata WHERE status = 'exists' AND decimals > 8;

[User] Add the total balance for each coin_type by joining with sui_coins.

[Assistant] SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, SUM(sc.balance) AS total_balance FROM sui_coins_metadata scm JOIN sui_coins sc ON scm.coin_type = sc.coin_type WHERE scm.status = 'exists' AND scm.decimals > 8 GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals;

[User] Can you also include only coins where the total_balance is greater than 1,000,000 and show the description?

[Assistant] SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description, SUM(sc.balance) AS total_balance FROM sui_coins_metadata scm JOIN sui_coins sc ON scm.coin_type = sc.coin_type WHERE scm.status = 'exists' AND scm.decimals > 8 GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description HAVING SUM(sc.balance) > 1000000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    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 (property_id)
)
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text 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.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )

[User] List all room types that have at least one service in the 'Spa' category, including the room type name, property name, and service name.

[Assistant]
SELECT DISTINCT rt.type_name, p.property_name, s.service_name
FROM hospitality_technology.room_types AS rt
JOIN hospitality_technology.properties AS p ON rt.property_id = p.property_id
JOIN hospitality_technology.services AS s ON rt.property_id = s.property_id
WHERE s.category = 'Spa';

[User] Actually, only show room types with a base_rate above 200.

[Assistant]
SELECT DISTINCT rt.type_name, p.property_name, s.service_name
FROM hospitality_technology.room_types AS rt
JOIN hospitality_technology.properties AS p ON rt.property_id = p.property_id
JOIN hospitality_technology.services AS s ON rt.property_id = s.property_id
WHERE s.category = 'Spa'
  AND rt.base_rate > 200;

[User] Also sort the results by base_rate descending and limit to 10.

[Assistant]
SELECT DISTINCT rt.type_name, p.property_name, s.service_name
FROM hospitality_technology.room_types AS rt
JOIN hospitality_technology.properties AS p ON rt.property_id = p.property_id
JOIN hospitality_technology.services AS s ON rt.property_id = s.property_id
WHERE s.category = 'Spa'
  AND rt.base_rate > 200
ORDER BY rt.base_rate DESC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 )

[User] Show me the full names and email addresses of all customers who registered after January 1st, 2024.

[Assistant] SELECT first_name, last_name, email FROM insurance.customers WHERE created_at > '2024-01-01';

[User] I also want to see their city and state in the result.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01';

[User] Sort the output by the created_at timestamp, newest first.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01' ORDER BY created_at DESC;

[User] Limit the result to the top 10 most recently registered customers.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01' ORDER BY created_at DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )

[User] For each transaction, find the next transaction initiated by the same sender. List the original transaction_id, the next transaction_id, the sender address, and the time difference in hours between them.

[Assistant]
SELECT t1.transaction_id AS original_tx,
       t2.transaction_id AS next_tx,
       t1.from_address,
       EXTRACT(EPOCH FROM (t2.timestamp - t1.timestamp)) / 3600 AS hours_diff
FROM transactions t1
JOIN transactions t2
  ON t1.from_address = t2.from_address
 AND t2.timestamp = (
       SELECT MIN(timestamp)
       FROM transactions t3
       WHERE t3.from_address = t1.from_address
         AND t3.timestamp > t1.timestamp
   );


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
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.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] Find the first name, last name, and contact email of citizens who have scheduled appointments in March 2024.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T1.contact_email FROM government_services.citizens AS T1 JOIN government_services.appointments AS T2 ON T1.citizen_id = T2.citizen_id WHERE T2.scheduled_start_time >= '2024-03-01' AND T2.scheduled_start_time < '2024-04-01';

[User] Now, only include appointments that have the status 'Completed'.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T1.contact_email FROM government_services.citizens AS T1 JOIN government_services.appointments AS T2 ON T1.citizen_id = T2.citizen_id WHERE T2.scheduled_start_time >= '2024-03-01' AND T2.scheduled_start_time < '2024-04-01' AND T2.status = 'Completed';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
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 character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )

[User] For each upcoming appointment in the next 7 days, list the appointment_id, scheduled_start_time, full name of the citizen, and the name of the service.

[Assistant]
SELECT a.appointment_id, a.scheduled_start_time,
       c.first_name || ' ' || c.last_name AS full_name,
       s.service_name
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE a.scheduled_start_time BETWEEN NOW() AND NOW() + INTERVAL '7 days';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.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.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] List the payment ID, amount, and the name of the service for all payments associated with services in the 'Licensing' category.

[Assistant] SELECT p.payment_id, p.amount, s.service_name FROM government_services.payments p JOIN government_services.services s ON p.service_id = s.service_id WHERE s.category = 'Licensing';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )

[User] Show me the top 5 tokens by 24-hour trading volume on the Ethereum chain, along with their price and 24-hour price change percentage.

[Assistant] SELECT token_name, token_symbol, price, price_change_percentage_24h, volume_24h FROM token_dexpool_info WHERE chain = 'Ethereum' ORDER BY volume_24h DESC LIMIT 5;

[User] Can you also include the market cap and liquidity for these tokens?

[Assistant] SELECT token_name, token_symbol, price, price_change_percentage_24h, volume_24h, market_cap, liquidity FROM token_dexpool_info WHERE chain = 'Ethereum' ORDER BY volume_24h DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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) )

[User] Find pairs of players from the same country who have different last login dates. Show their usernames, country code, and last login dates. Exclude pairs where either last login date is null.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login;

[User] Filter the results to only include pairs where the last login date difference is more than 30 days.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login AND ABS(EXTRACT(EPOCH FROM (p1.last_login - p2.last_login))) > 30 * 86400;

[User] Exclude pairs where the country code is NULL.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login AND ABS(EXTRACT(EPOCH FROM (p1.last_login - p2.last_login))) > 30 * 86400 AND p1.country_code IS NOT NULL;

[User] Order the results by the country code and then by the larger of the two last login dates in descending order. Limit to the top 10 results.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login AND ABS(EXTRACT(EPOCH FROM (p1.last_login - p2.last_login))) > 30 * 86400 AND p1.country_code IS NOT NULL ORDER BY p1.country_code, GREATEST(p1.last_login, p2.last_login) DESC LIMIT 10;


[User] For each agent, show the total number of policies they have sold and the sum of the premium amounts. Include the agent_id.

[Assistant]
SELECT agent_id, COUNT(*) AS policy_count, SUM(premium_amount) AS total_premium
FROM insurance.policies
WHERE agent_id IS NOT NULL
GROUP BY agent_id;

[User] Can you filter to only include agents who have sold more than 20 policies?

[Assistant]
SELECT agent_id, COUNT(*) AS policy_count, SUM(premium_amount) AS total_premium
FROM insurance.policies
WHERE agent_id IS NOT NULL
GROUP BY agent_id
HAVING COUNT(*) > 20;

[User] Actually, could you also show the average premium amount per policy for each qualifying agent?

[Assistant]
SELECT agent_id, COUNT(*) AS policy_count, SUM(premium_amount) AS total_premium, AVG(premium_amount) AS avg_premium
FROM insurance.policies
WHERE agent_id IS NOT NULL
GROUP BY agent_id
HAVING COUNT(*) > 20;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.time_entries ( entry_id 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 )

[User] Show me all time entries for case ID 'case_abc', including the entry ID, date worked, hours spent, and the first and last name of the lawyer.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc';

[User] Okay, now only show the entries that are marked as billable.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc' AND te.is_billable = TRUE;

[User] Also, include the description for these entries and sort them by date worked, oldest first.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name, te.description FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc' AND te.is_billable = TRUE ORDER BY te.date_worked ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )

[User] List all food and beverage services (category = 'Food & Beverage') with their names, prices, and units, where the price is less than $20.

[Assistant] SELECT service_name, price, unit FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20;

[User] Now, filter these results to only include services that are priced per item (unit = 'Per Item').

[Assistant] SELECT service_name, price, unit FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20 AND unit = 'Per Item';

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

[Assistant] SELECT service_name, price, unit, department FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20 AND unit = 'Per Item';

[User] Actually, I only need services from the 'F&B' department, and order them by price in ascending order.

[Assistant] SELECT service_name, price, unit, department FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20 AND unit = 'Per Item' AND department = 'F&B' ORDER BY price ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, 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 )
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)

[User] Show each player and the total number of game sessions they have participated in.

[Assistant] SELECT T1.player_id, T1.username, count(T2.session_id) FROM gaming_technology.players AS T1 LEFT JOIN gaming_technology.game_sessions AS T2 ON T1.player_id = T2.player_id GROUP BY T1.player_id, T1.username;

[User] Exclude players who have played fewer than 5 sessions.

[Assistant] SELECT T1.player_id, T1.username, count(T2.session_id) FROM gaming_technology.players AS T1 JOIN gaming_technology.game_sessions AS T2 ON T1.player_id = T2.player_id GROUP BY T1.player_id, T1.username HAVING count(T2.session_id) >= 5;

[User] For these players, show the average session duration as well.

[Assistant] SELECT T1.player_id, T1.username, count(T2.session_id), avg(T2.duration_seconds) FROM gaming_technology.players AS T1 JOIN gaming_technology.game_sessions AS T2 ON T1.player_id = T2.player_id GROUP BY T1.player_id, T1.username HAVING count(T2.session_id) >= 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )

[User] List the NDC code and description for any medication that has an NDC code starting with '5'.

[Assistant] SELECT ndc_code, description FROM healthcare.medications WHERE ndc_code LIKE '5%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )

[User] For each chain, show the total number of smart money addresses and the count of addresses with positive profit.

[Assistant] SELECT chain, COUNT(address) AS total_addresses, COUNT(CASE WHEN profit > 0 THEN address END) AS positive_profit_addresses FROM smart_money_profit GROUP BY chain

[User] Filter the results to only include chains where the total number of addresses is greater than 100. Also, include the percentage of addresses with positive profit for each chain.

[Assistant] SELECT chain, COUNT(address) AS total_addresses, COUNT(CASE WHEN profit > 0 THEN address END) AS positive_profit_addresses, CAST(COUNT(CASE WHEN profit > 0 THEN address END) AS REAL) * 100 / COUNT(address) AS positive_profit_percentage FROM smart_money_profit GROUP BY chain HAVING COUNT(address) > 100


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )

[User] Show me the notification ID, recipient user ID, and notification type for notifications received by users that user 'user123' is following.

[Assistant] SELECT n.notification_id, n.recipient_user_id, n.notification_type FROM social_media.notifications AS n JOIN social_media.follows AS f ON n.recipient_user_id = f.following_user_id WHERE f.follower_user_id = 'user123';

[User] Filter this list to only include notifications created after '2024-06-01' and also show the notification creation time.

[Assistant] SELECT n.notification_id, n.recipient_user_id, n.notification_type, n.created_at FROM social_media.notifications AS n JOIN social_media.follows AS f ON n.recipient_user_id = f.following_user_id WHERE f.follower_user_id = 'user123' AND n.created_at >= '2024-06-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.developers (
    developer_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the developer studio
    name character varying(150) NOT NULL UNIQUE, -- name of the development studio
    country character varying(100), -- country where the studio is based
    founded_year integer, -- year the studio was founded
    website character varying(255), -- developer's official website
    created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (developer_id)
)
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)

[User] Retrieve the player_id, username, and game title for all players who have at least one item in their inventory.

[Assistant]
SELECT DISTINCT p.player_id, p.username, g.title
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id;

[User] Now include the total quantity of items each player holds per game.

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

[User] Filter out entries where the total_quantity is less than 5.

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

[User] Sort the results by total_quantity in descending order and limit to the top 10.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
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.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, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )

[User] Find the total number of documents uploaded by each citizen along with their first and last names.

[Assistant]
SELECT c.citizen_id, c.first_name, c.last_name, COUNT(d.document_id) AS document_count
FROM government_services.citizens c
LEFT JOIN government_services.documents d ON c.citizen_id = d.citizen_id
GROUP BY c.citizen_id, c.first_name, c.last_name;

[User] Actually, I only want to include those citizens who have uploaded documents in the last 30 days.

[Assistant]
SELECT c.citizen_id, c.first_name, c.last_name, COUNT(d.document_id) AS document_count
FROM government_services.citizens c
JOIN government_services.documents d ON c.citizen_id = d.citizen_id
WHERE d.upload_timestamp >= NOW() - INTERVAL '30 days'
GROUP BY c.citizen_id, c.first_name, c.last_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )

[User] Retrieve the top 5 players by the number of distinct achievements unlocked. Show player_id and distinct_unlocks.

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC
LIMIT 5;

[User] Now limit the results to players whose status is 'active'.

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE p.status = 'active'
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC
LIMIT 5;

[User] Sort the list by distinct_unlocks descending and then by player_id ascending.

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE p.status = 'active'
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC, p.player_id ASC
LIMIT 5;

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

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE p.status = 'active'
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC, p.player_id ASC
LIMIT 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text, transaction_id text, output_index integer, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text, user_id text, status text, reviewed_at timestamp )

[User] I want a summary of each asset showing the total number of trades executed and the average trade price, including asset name and symbol.

[Assistant]
SELECT a.asset_id,
       a.name,
       a.symbol,
       COUNT(t.trade_id) AS trades_count,
       AVG(t.price) AS avg_price
FROM trading_platform.assets a
LEFT JOIN trading_platform.trades t ON a.asset_id = t.asset_id
GROUP BY a.asset_id, a.name, a.symbol;

[User] Actually, exclude trades before '2024-05-01'.

[Assistant]
SELECT a.asset_id,
       a.name,
       a.symbol,
       COUNT(t.trade_id) AS trades_count,
       AVG(t.price) AS avg_price
FROM trading_platform.assets a
LEFT JOIN trading_platform.trades t ON a.asset_id = t.asset_id
  AND t.traded_at >= '2024-05-01'
GROUP BY a.asset_id, a.name, a.symbol;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
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 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.text, 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_balances (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar NOT NULL, -- Token tick
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block 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_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) 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] Get the number of distinct wallet holders and total amount held for each NFT collection on Ethereum. Include collection name and contract_address.

[Assistant]
SELECT nc.contract_address, nc.name, COUNT(DISTINCT nh.wallet_address) AS holder_count, SUM(CAST(nh.amount AS DECIMAL)) AS total_amount
FROM nft_collections nc
JOIN nft_holders nh ON nh.contract_address = nc.contract_address
WHERE nc.blockchain = 'Ethereum'
GROUP BY nc.contract_address, nc.name;

[User] Now only include collections with more than 50 holders.

[Assistant]
SELECT sub.contract_address, sub.name, sub.holder_count, sub.total_amount
FROM (
  SELECT nc.contract_address, nc.name, COUNT(DISTINCT nh.wallet_address) AS holder_count, SUM(CAST(nh.amount AS DECIMAL)) AS total_amount
  FROM nft_collections nc
  JOIN nft_holders nh ON nh.contract_address = nc.contract_address
  WHERE nc.blockchain = 'Ethereum'
  GROUP BY nc.contract_address, nc.name
) sub
WHERE sub.holder_count > 50;

[User] Add the average amount per holder as avg_amount.

[Assistant]
SELECT nc.contract_address, nc.name, COUNT(DISTINCT nh.wallet_address) AS holder_count, SUM(CAST(nh.amount AS DECIMAL)) AS total_amount, SUM(CAST(nh.amount AS DECIMAL)) / COUNT(DISTINCT nh.wallet_address) AS avg_amount
FROM nft_collections nc
JOIN nft_holders nh ON nh.contract_address = nc.contract_address
WHERE nc.blockchain = 'Ethereum'
GROUP BY nc.contract_address, nc.name
HAVING COUNT(DISTINCT nh.wallet_address) > 50;

[User] Sort by avg_amount descending and limit to top 10.

[Assistant]
SELECT sub.contract_address, sub.name, sub.holder_count, sub.total_amount, sub.avg_amount
FROM (
  SELECT nc.contract_address, nc.name, COUNT(DISTINCT nh.wallet_address) AS holder_count, SUM(CAST(nh.amount AS DECIMAL)) AS total_amount, SUM(CAST(nh.amount AS DECIMAL)) / COUNT(DISTINCT nh.wallet_address) AS avg_amount
  FROM nft_collections nc
  JOIN nft_holders nh ON nh.contract_address = nc.contract_address
  WHERE nc.blockchain = 'Ethereum'
  GROUP BY nc.contract_address, nc.name
  HAVING COUNT(DISTINCT nh.wallet_address) > 50
) sub
ORDER BY sub.avg_amount DESC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
  "CREATE TABLE smart_money_token_inflow (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token",
    "usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token",
    "avg_price numeric(38,6), -- the average cost price of user spent on this token",
    "type int, -- the direction of the trade on this token. 1 means buying, 2 means selling",
    "address_amount integer, -- the amount of the user bought this token",
    "narrative character varying(100), -- the category or narrative of the token",
    "chain character varying(100), -- the chain that the token resides",
    ",PRIMARY KEY (token_address, chain)",

[User] Compute the average realized_ratio and average pnl for smart money token performance grouped by chain.

[Assistant]
SELECT chain, AVG(realized_ratio) AS avg_realized_ratio, AVG(pnl) AS avg_pnl
FROM smart_money_token_performance
GROUP BY chain;

[User] Show only the chains where the average pnl is greater than 10000.

[Assistant]
SELECT chain, AVG(realized_ratio) AS avg_realized_ratio, AVG(pnl) AS avg_pnl
FROM smart_money_token_performance
GROUP BY chain
HAVING AVG(pnl) > 10000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers (
    driver_id character varying(64) NOT NULL,  -- unique identifier for the driver
    employee_id character varying(64) NOT NULL UNIQUE, -- employee reference number
    first_name character varying(128) NOT NULL, -- driver's first name
    last_name character varying(128) NOT NULL, -- driver's last name
    license_number character varying(64) NOT NULL UNIQUE, -- driving license number
    license_expiry_date date NOT NULL, -- expiry date of the license
    contact_number character varying(32), -- phone number
    email character varying(128) UNIQUE, -- email address
    hire_date date NOT NULL, -- date the driver was hired
    status character varying(32) NOT NULL, -- e.g., Active, On Leave, Terminated
    PRIMARY KEY (driver_id)
)
CREATE TABLE transportation.routes (
    route_id character varying(64) NOT NULL,  -- unique identifier for the route
    route_number character varying(32) NOT NULL UNIQUE, -- public-facing route number/name
    description text, -- description of the route
    origin_location_id character varying(64) NOT NULL, -- identifier of the starting location
    destination_location_id character varying(64) NOT NULL, -- identifier of the ending location
    distance_km numeric(10, 2), -- estimated distance in kilometers
    estimated_duration_minutes integer, -- estimated travel time in minutes
    type character varying(32) NOT NULL, -- e.g., City Bus, Intercity Train, Cargo Delivery
    PRIMARY KEY (route_id)
)
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)
CREATE TABLE transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)

[User] Show me all drivers and the vehicles they are assigned for trips that have status 'Delayed'. Include driver first_name, driver last_name, vehicle license_plate, trip_id, and actual_departure.

[Assistant]
SELECT d.first_name, d.last_name, v.license_plate, t.trip_id, t.actual_departure
FROM transportation.trips t
JOIN transportation.drivers d ON t.driver_id = d.driver_id
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
WHERE t.status = 'Delayed';

[User] Now limit to delays where the actual_departure is more than 15 minutes after scheduled_departure and order by the delay duration in descending order.

[Assistant]
SELECT d.first_name, d.last_name, v.license_plate, t.trip_id, t.actual_departure,
       EXTRACT(EPOCH FROM (t.actual_departure - t.scheduled_departure))/60 AS delay_minutes
FROM transportation.trips t
JOIN transportation.drivers d ON t.driver_id = d.driver_id
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
WHERE t.status = 'Delayed'
  AND (t.actual_departure - t.scheduled_departure) > INTERVAL '15 minutes'
ORDER BY delay_minutes DESC;