[User] Show each service's name along with the total number of appointments scheduled and the number of unique locations these appointments are scheduled at.

[Assistant]
SELECT s.service_name, COUNT(a.application_id) AS appointment_count, COUNT(DISTINCT ap.location_id) AS unique_location_count
FROM government_services.services s
JOIN government_services.applications a ON s.service_id = a.service_id
JOIN government_services.appointments ap ON a.application_id = ap.application_id
GROUP BY s.service_name;

[User] I got an error: relation 'appointments' does not exist.

[Assistant]
-- The appointments table is not present in the provided schema. If you want to count by another join, perhaps by documents or payments, please specify.
-- Alternatively, do you want appointment information replaced with application submissions per service and their associated location from service_locations?
SELECT s.service_name, COUNT(a.application_id) AS application_count, COUNT(DISTINCT sl.location_id) AS unique_location_count
FROM government_services.services s
JOIN government_services.applications a ON s.service_id = a.service_id
JOIN government_services.service_locations sl ON s.agency_id = sl.agency_id
GROUP BY s.service_name;

[User] Show only those services where application_count is greater than 50.

[Assistant]
SELECT s.service_name, COUNT(a.application_id) AS application_count, COUNT(DISTINCT sl.location_id) AS unique_location_count
FROM government_services.services s
JOIN government_services.applications a ON s.service_id = a.service_id
JOIN government_services.service_locations sl ON s.agency_id = sl.agency_id
GROUP BY s.service_name
HAVING COUNT(a.application_id) > 50;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.documents ( document_id.text, 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.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    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, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    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] List pairs of citizens who share the same email domain.

[Assistant]
SELECT c1.first_name AS first1,
       c1.last_name AS last1,
       c2.first_name AS first2,
       c2.last_name AS last2,
       SPLIT_PART(c1.contact_email, '@', 2) AS domain
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON SPLIT_PART(c1.contact_email, '@', 2) = SPLIT_PART(c2.contact_email, '@', 2)
 AND c1.citizen_id < c2.citizen_id
WHERE c1.contact_email IS NOT NULL
  AND c2.contact_email IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)


[User] Show me all transactions where the description contains the word 'fee'.

[Assistant] SELECT * FROM financial_services.transactions WHERE description ILIKE '%fee%';

[User] Limit the results to transactions that occurred in the previous month.

[Assistant] SELECT * FROM financial_services.transactions WHERE description ILIKE '%fee%' AND transaction_date >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month') AND transaction_date < date_trunc('month', CURRENT_DATE);

[User] Only include transactions with an amount greater than 20.

[Assistant] SELECT * FROM financial_services.transactions WHERE description ILIKE '%fee%' AND transaction_date >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month') AND transaction_date < date_trunc('month', CURRENT_DATE) AND amount > 20;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.transactions ( transaction_id text, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )


[User] Show me the top 5 NFT collections with the highest token count on Ethereum, along with their names, symbols, and floor prices.

[Assistant] SELECT n.name, n.symbol, n.floor_price, n.token_count FROM nft_collections n WHERE n.blockchain = 'ethereum' ORDER BY n.token_count DESC LIMIT 5;

[User] Now, join this with the nft_metadata table to include the average rarity score for each collection.

[Assistant] SELECT n.name, n.symbol, n.floor_price, n.token_count, AVG(m.rarity_score) as avg_rarity_score FROM nft_collections n JOIN nft_metadata m ON n.contract_address = m.contract_address WHERE n.blockchain = 'ethereum' GROUP BY n.name, n.symbol, n.floor_price, n.token_count ORDER BY n.token_count DESC LIMIT 5;

[User] Can you filter these results to only show collections with an average rarity score greater than 80?

[Assistant] SELECT n.name, n.symbol, n.floor_price, n.token_count, AVG(m.rarity_score) as avg_rarity_score FROM nft_collections n JOIN nft_metadata m ON n.contract_address = m.contract_address WHERE n.blockchain = 'ethereum' GROUP BY n.name, n.symbol, n.floor_price, n.token_count HAVING AVG(m.rarity_score) > 80 ORDER BY n.token_count DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, 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 ( 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, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( 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, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] For all NFT collections on the Ethereum blockchain, show me the collection name and the current floor price. Sort by floor price descending.

[Assistant] SELECT name, floor_price FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Include also the collection symbol and the number of tokens in each collection.

[Assistant] SELECT name, symbol, floor_price, token_count FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Can you also show the owner of each collection in the result?

[Assistant] SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Now only include collections whose floor price is greater than 1 ETH.

[Assistant] SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' AND CAST(floor_price AS FLOAT) > 1 AND floor_price_symbol = 'ETH' ORDER BY CAST(floor_price AS FLOAT) DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) 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, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )


[User] I need to find passengers who have a specific phone number prefix '+1555'. Can you help with that?

[Assistant] db.passengers.find({ phone_number: { $regex: '^\+1555' } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 })

[User] Can you also filter these results to include only passengers born before 1995?

[Assistant] db.passengers.find({ phone_number: { $regex: '^\+1555' }, date_of_birth: { $lt: ISODate('1995-01-01T00:00:00Z') } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 })

[User] Can you limit the results to the first 5 passengers?

[Assistant] db.passengers.find({ phone_number: { $regex: '^\+1555' }, date_of_birth: { $lt: ISODate('1995-01-01T00:00:00Z') } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 }).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
// db.createCollection('passengers')
// Optional: db.passengers.createIndex({ passenger_id: 1 }, { unique: true })
// Optional: db.passengers.createIndex({ email: 1 }, { unique: true, sparse: true })
// Optional: db.passengers.createIndex({ phone_number: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  passenger_id: "pass_pqr", // String (unique)
  first_name: "Alice", // String
  last_name: "Smith", // String
  email: "alice.smith@example.com", // String (unique, sparse)
  phone_number: "+15551234567", // String (unique, sparse)
  date_of_birth: ISODate("1990-03-20"), // Date
  loyalty_program_id: "LOYALTY123", // String
  created_at: ISODate("2023-02-01T11:00:00Z") // Date
}


[User] Provide every combination of medication name and insurance plan name.

[Assistant]
SELECT m.medication_name, p.plan_name
FROM healthcare.medications AS m
CROSS JOIN healthcare.insurance_plans AS p;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )


[User] Could you list each game_id along with the count of hidden achievements and the count of visible achievements?

[Assistant]
SELECT game_id,
       SUM(CASE WHEN hidden THEN 1 ELSE 0 END) AS hidden_count,
       SUM(CASE WHEN NOT hidden THEN 1 ELSE 0 END) AS visible_count
FROM gaming_technology.achievements
GROUP BY game_id;

[User] Actually, please provide pairs of one hidden and one visible achievement name for each game where both types exist.

[Assistant]
SELECT h.game_id,
       h.name AS hidden_name,
       v.name AS visible_name
FROM gaming_technology.achievements h
JOIN gaming_technology.achievements v
  ON h.game_id = v.game_id
 AND h.hidden = TRUE
 AND v.hidden = FALSE
WHERE EXISTS (
  SELECT 1 FROM gaming_technology.achievements x
   WHERE x.game_id = h.game_id
     AND x.hidden = FALSE
)
AND EXISTS (
  SELECT 1 FROM gaming_technology.achievements y
   WHERE y.game_id = h.game_id
     AND y.hidden = TRUE
);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )


[User] List all tokens from the token_dexpool_info table with a liquidity over $10 million and a positive 6-hour price change percentage on the Ethereum chain.

[Assistant] SELECT token_name, token_symbol, liquidity, price_change_percentage_6h FROM token_dexpool_info WHERE liquidity > 10000000 AND price_change_percentage_6h > 0 AND chain = 'Ethereum';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
 "CREATE TABLE narrative_info (",
    "narrative character varying(512) NOT NULL, -- the id of narrative",
    "top_3_coins text, -- the top 3 tokens in the narrative",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative",
    "price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative",
    "market_cap double precision, -- the market cap of the narrative",
    "volume_24h double precision, -- the trade volume of the narrative",
    "trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative",
    "token_num bigint, -- total token number in the narrative",
    ",PRIMARY KEY (narrative));"

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 )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL, chain character varying(128) NOT NULL, address character varying(128) NOT NULL, exchange character varying(512) NOT NULL, token_address character varying(128) NOT NULL, token_symbol character varying(512), balance numeric(38,10), usd_value numeric(38,14), price double precision )
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )
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] What is the detailed repair history of the equipment used by the staff with staff_id 'STAFF123' during maintenance tasks?

[Assistant] I'm sorry, but I can't provide information on the detailed repair history of equipment used by staff members. The data in the maintenance_records table only includes information about maintenance tasks, such as record_id, asset_id, maintenance type, and staff_id, but does not cover equipment repair histories.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id.text, asset_id.text, asset_type.text, maintenance_type.text, staff_id.text, start_datetime.timestamp, end_datetime.timestamp, description.text, cost.numeric, status.text )


[User] Show me all pairs of patients who share the same emergency contact phone, including both patient IDs, their names, and the shared emergency contact phone.

[Assistant]
SELECT p1.patient_id,
       p1.first_name,
       p1.last_name,
       p2.patient_id AS other_patient_id,
       p2.first_name AS other_first_name,
       p2.last_name AS other_last_name,
       p1.emergency_contact_phone
FROM healthcare.patients p1
JOIN healthcare.patients p2
  ON p1.emergency_contact_phone = p2.emergency_contact_phone
 AND p1.patient_id < p2.patient_id;

[User] Only include those pairs where both emergency_contact_name values are not null.

[Assistant]
SELECT p1.patient_id,
       p1.first_name,
       p1.last_name,
       p2.patient_id AS other_patient_id,
       p2.first_name AS other_first_name,
       p2.last_name AS other_last_name,
       p1.emergency_contact_phone
FROM healthcare.patients p1
JOIN healthcare.patients p2
  ON p1.emergency_contact_phone = p2.emergency_contact_phone
 AND p1.patient_id < p2.patient_id
WHERE p1.emergency_contact_name IS NOT NULL
  AND p2.emergency_contact_name IS NOT NULL;

[User] Also exclude any pairs where the shared emergency contact phone matches the patient's own phone_number.

[Assistant]
SELECT p1.patient_id,
       p1.first_name,
       p1.last_name,
       p2.patient_id AS other_patient_id,
       p2.first_name AS other_first_name,
       p2.last_name AS other_last_name,
       p1.emergency_contact_phone
FROM healthcare.patients p1
JOIN healthcare.patients p2
  ON p1.emergency_contact_phone = p2.emergency_contact_phone
 AND p1.patient_id < p2.patient_id
WHERE p1.emergency_contact_name IS NOT NULL
  AND p2.emergency_contact_name IS NOT NULL
  AND p1.emergency_contact_phone <> p1.phone_number
  AND p2.emergency_contact_phone <> p2.phone_number;

[User] Finally, order the results by the shared emergency contact phone ascending and limit to the first 50 pairs.

[Assistant]
SELECT p1.patient_id,
       p1.first_name,
       p1.last_name,
       p2.patient_id AS other_patient_id,
       p2.first_name AS other_first_name,
       p2.last_name AS other_last_name,
       p1.emergency_contact_phone
FROM healthcare.patients p1
JOIN healthcare.patients p2
  ON p1.emergency_contact_phone = p2.emergency_contact_phone
 AND p1.patient_id < p2.patient_id
WHERE p1.emergency_contact_name IS NOT NULL
  AND p2.emergency_contact_name IS NOT NULL
  AND p1.emergency_contact_phone <> p1.phone_number
  AND p2.emergency_contact_phone <> p2.phone_number
ORDER BY p1.emergency_contact_phone ASC
LIMIT 50;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )


[User] Show me the total number of trades and the sum of total_amount for each status in the trades table.

[Assistant]
SELECT
  t.status,
  COUNT(t.trade_id) AS trade_count,
  SUM(t.total_amount) AS total_amount_by_status
FROM financial_services.trades t
GROUP BY t.status;

[User] Now, only include statuses where trade_count is greater than 100, and restrict to trades executed in the last 30 days.

[Assistant]
SELECT
  t.status,
  COUNT(t.trade_id) AS trade_count,
  SUM(t.total_amount) AS total_amount_by_status
FROM financial_services.trades t
WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY t.status
HAVING COUNT(t.trade_id) > 100;

[User] Exclude any statuses where the sum of commission is null or less than 1000.

[Assistant]
SELECT
  t.status,
  COUNT(t.trade_id) AS trade_count,
  SUM(t.total_amount) AS total_amount_by_status,
  SUM(t.commission) AS total_commission
FROM financial_services.trades t
WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY t.status
HAVING COUNT(t.trade_id) > 100
   AND SUM(t.commission) >= 1000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, department character varying(100), branch_id character varying(64), email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, manager_id character varying(64), status character varying(32) NOT NULL, PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )


[User] List all medical records, showing the record ID, record date, and the full name of the doctor who created the record. Include the patient ID as well.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id;

[User] Refine this to only include records where the chief_complaint is not null or empty and the doctor's specialty is 'Cardiology'.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id WHERE (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') AND d.specialty = 'Cardiology';

[User] Also, sort the results by record_date in descending order and limit the output to the top 10 records.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id WHERE (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') AND d.specialty = 'Cardiology' ORDER BY mr.record_date DESC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)


[User] Could you list the trip ID, scheduled and actual arrival times, and the associated vehicle's make and model for all trips where the actual arrival was more than 30 minutes later than scheduled?

[Assistant] SELECT T1.trip_id, T1.scheduled_arrival, T1.actual_arrival, T2.make, T2.model FROM transportation.trips AS T1 JOIN transportation.vehicles AS T2 ON T1.vehicle_id = T2.vehicle_id WHERE T1.actual_arrival IS NOT NULL AND T1.scheduled_arrival IS NOT NULL AND T1.actual_arrival > T1.scheduled_arrival + INTERVAL '30 minutes';

[User] Now, filter this list to only include trips that were completed within the last 6 months.

[Assistant] SELECT T1.trip_id, T1.scheduled_arrival, T1.actual_arrival, T2.make, T2.model FROM transportation.trips AS T1 JOIN transportation.vehicles AS T2 ON T1.vehicle_id = T2.vehicle_id WHERE T1.actual_arrival IS NOT NULL AND T1.scheduled_arrival IS NOT NULL AND T1.actual_arrival > T1.scheduled_arrival + INTERVAL '30 minutes' AND T1.actual_arrival >= NOW() - INTERVAL '6 months';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )


[User] What is the average investment_value and total number of projects for each rounds_name in project_fundraising_record?

[Assistant]
SELECT rounds_name,
       AVG(investment_value) AS avg_investment,
       COUNT(DISTINCT project_id) AS project_count
FROM project_fundraising_record
GROUP BY rounds_name;

[User] Please show only rounds where project_count > 5, and order by avg_investment descending.

[Assistant]
SELECT rounds_name,
       AVG(investment_value) AS avg_investment,
       COUNT(DISTINCT project_id) AS project_count
FROM project_fundraising_record
GROUP BY rounds_name
HAVING COUNT(DISTINCT project_id) > 5
ORDER BY avg_investment DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id 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 smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )


[User] For each route type, show the total number of trips taken and the total distance covered across all trips for that type.

[Assistant] SELECT T1.type, COUNT(T2.trip_id), SUM(T1.distance_km) FROM transportation.routes AS T1 JOIN transportation.trips AS T2 ON T1.route_id = T2.route_id GROUP BY T1.type;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


[User] List NFT collections deployed after block number 10000000 with more than 500 tokens, showing contract_address, name, and token_count.

[Assistant]
SELECT contract_address, name, token_count
FROM nft_collections
WHERE deploy_block_number > 10000000
  AND token_count > 500;

[User] Join with nft_metadata to calculate the average rarity_score per collection.

[Assistant]
SELECT nc.contract_address,
       nc.name,
       nc.token_count,
       AVG(nm.rarity_score) AS avg_rarity
FROM nft_collections nc
LEFT JOIN nft_metadata nm
  ON nc.contract_address = nm.contract_address
WHERE nc.deploy_block_number > 10000000
  AND nc.token_count > 500
GROUP BY nc.contract_address, nc.name, nc.token_count;

[User] Filter collections with average rarity_score above 80 and include floor_price.

[Assistant]
SELECT nc.contract_address,
       nc.name,
       nc.token_count,
       AVG(nm.rarity_score) AS avg_rarity,
       nc.floor_price
FROM nft_collections nc
LEFT JOIN nft_metadata nm
  ON nc.contract_address = nm.contract_address
WHERE nc.deploy_block_number > 10000000
  AND nc.token_count > 500
GROUP BY nc.contract_address, nc.name, nc.token_count, nc.floor_price
HAVING AVG(nm.rarity_score) > 80;

[User] Order the results by floor_price descending and limit to the top 5 collections.

[Assistant]
SELECT nc.contract_address,
       nc.name,
       nc.token_count,
       AVG(nm.rarity_score) AS avg_rarity,
       nc.floor_price
FROM nft_collections nc
LEFT JOIN nft_metadata nm
  ON nc.contract_address = nm.contract_address
WHERE nc.deploy_block_number > 10000000
  AND nc.token_count > 500
GROUP BY nc.contract_address, nc.name, nc.token_count, nc.floor_price
HAVING AVG(nm.rarity_score) > 80
ORDER BY CAST(nc.floor_price AS numeric) DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    name varchar NOT NULL, -- name fields for the functionType  in contract
    symbol varchar NOT NULL, -- symbol fields for the functionType  in contract
    deploy_block_number bigint NOT NULL, -- deploy_block_number fields for the functionType  in contract
    deploy_block_time bigint NOT NULL, -- deploy_block_time fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    description varchar NOT NULL, -- description fields for the functionType  in contract
    slug varchar NOT NULL, -- slug fields for the functionType  in contract
    media_info varchar NOT NULL, -- media_info fields for the functionType  in contract
    image_url varchar NOT NULL, -- image_url fields for the functionType  in contract
    banner_image_url varchar NOT NULL, -- banner_image_url fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    banner varchar NOT NULL, -- banner fields for the functionType  in contract
    token_count bigint NOT NULL, -- token_count fields for the functionType  in contract
    floor_price varchar NOT NULL, -- floor_price fields for the functionType  in contract
    floor_price_symbol varchar NOT NULL, -- floor_price_symbol fields for the functionType  in contract
    floor_price_contract varchar NOT NULL, -- floor_price_contract fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(deploy_block_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE mud_holesky_redstone ( address.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_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( 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, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] List the full name (first name and last name) of all citizens who have uploaded documents whose expiry date is in the past.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name FROM government_services.citizens AS T1 INNER JOIN government_services.documents AS T2 ON T1.citizen_id = T2.citizen_id WHERE T2.expiry_date < CURRENT_DATE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )


[User] Count the total number of comments each user has made.

[Assistant] SELECT user_id, COUNT(*) AS comment_count FROM comments GROUP BY user_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )


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

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

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

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

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


[User] I want to list pairs of developers from the same country. For each pair, show both developers’ names and their country.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
  AND d1.developer_id <> d2.developer_id;

[User] Actually, I want to avoid duplicate pairs; only list each pair once.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
  AND d1.developer_id < d2.developer_id;

[User] Also, only include countries that have more than two developers.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
  AND d1.developer_id < d2.developer_id
WHERE (
    SELECT COUNT(*)
    FROM gaming_technology.developers d3
    WHERE d3.country = d1.country
) > 2;

[User] Finally, order the results by country ascending and then by developer1’s name ascending.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
  AND d1.developer_id < d2.developer_id
WHERE (
    SELECT COUNT(*)
    FROM gaming_technology.developers d3
    WHERE d3.country = d1.country
) > 2
ORDER BY d1.country ASC, d1.name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )


[User] What is the total number of drivers hired each year? Provide the hire_year and driver_count.

[Assistant]
SELECT EXTRACT(YEAR FROM hire_date) AS hire_year,
       COUNT(*)                  AS driver_count
FROM transportation.drivers
GROUP BY EXTRACT(YEAR FROM hire_date);

[User] Now only include years where driver_count > 3 and order the results by driver_count DESC.

[Assistant]
SELECT hire_year, driver_count
FROM (
  SELECT EXTRACT(YEAR FROM hire_date) AS hire_year,
         COUNT(*)                  AS driver_count
  FROM transportation.drivers
  GROUP BY EXTRACT(YEAR FROM hire_date)
) sub
WHERE driver_count > 3
ORDER BY driver_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )


[User] What is the detailed repair history for train number T5678?

[Assistant] I'm sorry, but I can't provide the detailed repair history for train number T5678 as this information is not available in the current database table. The table only includes basic information such as train ID, model, manufacturer, capacity, status, and maintenance dates. For repair history, you may need to consult a different database or department.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.trains ( train_id text, train_number text, model text, manufacturer text, year_manufactured integer, capacity integer, status text, last_maintenance_date date, next_maintenance_date date )


[User] Retrieve the count of active insurance products for each product_type and order the results by the count descending.

[Assistant]
SELECT product_type,
       COUNT(*) AS active_count
FROM insurance.insurance_products
WHERE is_active = TRUE
GROUP BY product_type
ORDER BY active_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )


[User] List all pairs of token IDs that share the same decimals value, and show the shared decimals.

[Assistant]
SELECT t1.token_id AS token1_id,
       t2.token_id AS token2_id,
       t1.decimals
FROM web3.tokens t1
JOIN web3.tokens t2
  ON t1.decimals = t2.decimals
 AND t1.token_id < t2.token_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)


[User] Count the number of logs for each action type.

[Assistant]
SELECT action,
       COUNT(*) AS count
FROM trading_platform.logs
GROUP BY action;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )


[User] Get the number of direct reports for each manager, showing manager_id and report_count.

[Assistant]
SELECT manager_id,
       COUNT(*) AS report_count
FROM hospitality_technology.staff
WHERE manager_id IS NOT NULL
GROUP BY manager_id;

[User] Exclude managers who have fewer than 2 direct reports.

[Assistant]
SELECT manager_id,
       COUNT(*) AS report_count
FROM hospitality_technology.staff
WHERE manager_id IS NOT NULL
GROUP BY manager_id
HAVING COUNT(*) >= 2;

[User] Also include the manager's full name alongside their ID.

[Assistant]
SELECT m.staff_id AS manager_id,
       m.first_name || ' ' || m.last_name AS manager_full_name,
       COUNT(s.staff_id) AS report_count
FROM hospitality_technology.staff s
JOIN hospitality_technology.staff m
  ON s.manager_id = m.staff_id
GROUP BY m.staff_id, m.first_name, m.last_name
HAVING COUNT(s.staff_id) >= 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Could you provide the total number of game sessions and the number of distinct players for each game genre? Display the genre, session count, and player count.

[Assistant] SELECT g.genre, COUNT(gs.session_id) AS session_count, COUNT(DISTINCT gs.player_id) AS player_count FROM gaming_technology.game_sessions AS gs JOIN gaming_technology.games AS g ON gs.game_id = g.game_id WHERE g.genre IS NOT NULL GROUP BY g.genre ORDER BY g.genre;

[User] Thanks. Can you modify the query to only include games that were released after the year 2020?

[Assistant] SELECT g.genre, COUNT(gs.session_id) AS session_count, COUNT(DISTINCT gs.player_id) AS player_count FROM gaming_technology.game_sessions AS gs JOIN gaming_technology.games AS g ON gs.game_id = g.game_id WHERE g.genre IS NOT NULL AND g.release_date >= '2021-01-01' GROUP BY g.genre ORDER BY g.genre;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)


[User] Show the total hours spent by each lawyer across all their time entries. Display the lawyer's first name, last name, and the total hours.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_hours FROM legal_services.time_entries te JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id GROUP BY l.lawyer_id, l.first_name, l.last_name ORDER BY total_hours DESC;

[User] Modify the previous query to only include time entries that are marked as billable.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_billable_hours FROM legal_services.time_entries te JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id WHERE te.is_billable = true GROUP BY l.lawyer_id, l.first_name, l.last_name ORDER BY total_billable_hours DESC;

[User] Now, filter the results to only show lawyers who are partners and have logged more than 100 billable hours in total.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_billable_hours FROM legal_services.time_entries te JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id WHERE te.is_billable = true AND l.is_partner = true GROUP BY l.lawyer_id, l.first_name, l.last_name HAVING SUM(te.hours_spent) > 100 ORDER BY total_billable_hours DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)


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

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

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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)


[User] How many lawyers who are partners were hired in each year? Show the hire year and the count.

[Assistant] SELECT strftime('%Y', hire_date) AS hire_year ,  count(lawyer_id) FROM legal_services.lawyers WHERE is_partner  =  true GROUP BY hire_year

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


[User] For each chain, find the token with the highest net USD inflow (buys minus sells). Show token_symbol, chain, and net_inflow.

[Assistant]
WITH inflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_in
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY token_symbol, chain
),
outflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_out
  FROM smart_money_token_inflow
  WHERE type = 2
  GROUP BY token_symbol, chain
),
net AS (
  SELECT
    COALESCE(i.token_symbol, o.token_symbol) AS token_symbol,
    COALESCE(i.chain, o.chain) AS chain,
    COALESCE(i.usd_in, 0) - COALESCE(o.usd_out, 0) AS net_inflow
  FROM inflow i
  FULL JOIN outflow o
    ON i.token_symbol = o.token_symbol
   AND i.chain = o.chain
)
SELECT token_symbol, chain, net_inflow
FROM (
  SELECT
    token_symbol,
    chain,
    net_inflow,
    ROW_NUMBER() OVER (PARTITION BY chain ORDER BY net_inflow DESC) AS rn
  FROM net
) sub
WHERE rn = 1;

[User] Only include tokens that were involved in at least 10 distinct addresses for buy transactions.

[Assistant]
WITH inflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_in, SUM(address_amount) AS addr_count
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY token_symbol, chain
),
outflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_out
  FROM smart_money_token_inflow
  WHERE type = 2
  GROUP BY token_symbol, chain
),
net AS (
  SELECT
    i.token_symbol,
    i.chain,
    i.usd_in - COALESCE(o.usd_out, 0) AS net_inflow,
    i.addr_count
  FROM inflow i
  LEFT JOIN outflow o
    ON i.token_symbol = o.token_symbol
   AND i.chain = o.chain
)
SELECT token_symbol, chain, net_inflow
FROM (
  SELECT
    token_symbol,
    chain,
    net_inflow,
    addr_count,
    ROW_NUMBER() OVER (PARTITION BY chain ORDER BY net_inflow DESC) AS rn
  FROM net
) sub
WHERE rn = 1
  AND addr_count >= 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address.text, token_symbol.text, token_amount.numeric, usd_value.numeric, avg_price.numeric, type.numeric, address_amount.numeric, narrative.text, chain.text )


[User] Show me all invoice numbers and due dates where the amount paid is exactly zero.

[Assistant] SELECT invoice_number, due_date FROM legal_services.invoices WHERE amount_paid = 0;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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 the top 5 users who have interacted with DApps, along with the count of distinct DApps they interacted with and their wallet addresses.

[Assistant] SELECT w.user_id, COUNT(DISTINCT d.dapp_id) AS dapp_count, w.address FROM trading_platform.wallets w JOIN trading_platform.dapps d ON 1=1 GROUP BY w.user_id, w.address ORDER BY dapp_count DESC LIMIT 5;

[User] This query doesn't properly show DApp interactions. Please modify it to correctly join with a table that records user-DApp interactions.

[Assistant] I notice there's no interaction table in the provided schema. Without a table recording user-DApp interactions, I cannot generate this query accurately. Would you like to see users who have wallets and DApps separately instead?

[User] You're right. Instead, show me users who have wallets but have never interacted with any DApps, along with their wallet addresses.

[Assistant] SELECT w.user_id, w.address FROM trading_platform.wallets w WHERE NOT EXISTS (SELECT 1 FROM trading_platform.dapps d WHERE 1=1) GROUP BY w.user_id, w.address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.assets ( asset_id.text, name.text, symbol.text, type.text )
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )


[User] Count the total number of chronic diagnoses for each code_type.

[Assistant]
SELECT
  code_type,
  COUNT(*) AS chronic_diagnosis_count
FROM healthcare.diagnoses
WHERE is_chronic = TRUE
GROUP BY code_type;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )


[User] What is the total revenue generated by ticket sales at the station with ID 'ST101' for the past month?

[Assistant] I'm sorry, but I can't provide information on the revenue generated by ticket sales as this data is not available in the current database table. The table only contains details about station information such as name, location, and platform count. If you have another question or need assistance with something else related to the station data, I'm happy to help.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.stations ( station_id.text, station_name.text, city.text, state_province.text, country_code.text, address.text, timezone.text, number_of_platforms.integer, created_at.timestamp, last_updated_at.timestamp )


[User] How many likes were given to comments in June 2024?

[Assistant]
SELECT COUNT(*) AS comment_likes_count
FROM social_media.likes
WHERE comment_id IS NOT NULL
  AND DATE_TRUNC('month', created_at) = '2024-06-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.comments ( comment_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, parent_comment_id character varying(64), content text NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (comment_id) )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )


[User] List all pairs of clients who registered on the same day, showing each client's first_name, last_name, and the registration date.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, DATE(c1.date_registered) AS registration_date FROM legal_services.clients c1 JOIN legal_services.clients c2 ON DATE(c1.date_registered) = DATE(c2.date_registered) AND c1.client_id < c2.client_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )


[User] Provide a count of how many peers were last seen on each distinct day recorded in the system.

[Assistant] SELECT DATE(last_seen), COUNT(*) FROM trading_platform.peers GROUP BY DATE(last_seen) ORDER BY DATE(last_seen);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.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.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] For projects that have completed more than one fundraising round, calculate the average investment value across all their recorded rounds. Display the project name and this average value.

[Assistant] SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1;

[User] Can you modify this to only show projects where the average investment value is greater than 10 million USD and order the results by average investment value descending?

[Assistant] SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1 AND AVG(investment_value) > 10000000 ORDER BY average_investment DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )


[User] List each patient's first and last name along with their total number of appointments in 2024.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients p
LEFT JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
  AND a.appointment_time BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY p.first_name, p.last_name;

[User] Now exclude all 'Cancelled' appointments from the count.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients p
LEFT JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
  AND a.appointment_time BETWEEN '2024-01-01' AND '2024-12-31'
  AND a.status <> 'Cancelled'
GROUP BY p.first_name, p.last_name;

[User] Also, only show patients who have more than 2 appointments and sort the result by appointment_count in descending order.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients p
LEFT JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
  AND a.appointment_time BETWEEN '2024-01-01' AND '2024-12-31'
  AND a.status <> 'Cancelled'
GROUP BY p.first_name, p.last_name
HAVING COUNT(a.appointment_id) > 2
ORDER BY appointment_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)