[User] Show me all reservations with their guest IDs and room IDs where the total amount is greater than $500 and the status is 'Confirmed', ordered by check-in date.

[Assistant] SELECT reservation_id, guest_id, room_id, check_in_date, total_amount FROM hospitality_technology.reservations WHERE total_amount > 500 AND status = 'Confirmed' ORDER BY check_in_date;

[User] Now, join this with the service_orders table to include the total price of all services ordered for each reservation.

[Assistant] SELECT r.reservation_id, r.guest_id, r.room_id, r.check_in_date, r.total_amount, SUM(so.total_price) AS total_service_price FROM hospitality_technology.reservations r LEFT JOIN hospitality_technology.service_orders so ON r.reservation_id = so.reservation_id WHERE r.total_amount > 500 AND r.status = 'Confirmed' GROUP BY r.reservation_id, r.guest_id, r.room_id, r.check_in_date, r.total_amount ORDER BY r.check_in_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 hospitality_technology.reservations ( reservation_id.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Provide a report of each user with their username and the count of all log entries from the last 30 days.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS log_count
FROM trading_platform.users u
LEFT JOIN trading_platform.logs l
  ON u.user_id = l.user_id
  AND l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY u.user_id, u.username;

[User] Actually, show only logs where the action includes the word 'trade'.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS log_count
FROM trading_platform.users u
JOIN trading_platform.logs l
  ON u.user_id = l.user_id
WHERE l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username;

[User] Also include the earliest log date for each user in that period.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(l.log_id) AS log_count,
       MIN(l.logged_at) AS first_log_date
FROM trading_platform.users u
JOIN trading_platform.logs l
  ON u.user_id = l.user_id
WHERE l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username;

[User] Finally, sort the results by log_count descending and limit to the top 5 users.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(l.log_id) AS log_count,
       MIN(l.logged_at) AS first_log_date
FROM trading_platform.users u
JOIN trading_platform.logs l
  ON u.user_id = l.user_id
WHERE l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username
ORDER BY log_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 trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)


[User] For each citizen who has made at least one payment, show the citizen's full name, number of payments, and total amount paid, grouped by currency.

[Assistant]
SELECT
  c.first_name || ' ' || c.last_name AS full_name,
  p.currency,
  COUNT(*) AS payment_count,
  SUM(p.amount) AS total_amount
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
GROUP BY full_name, p.currency;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )


[User] Find the first name, last name, national ID number, and contact email for all citizens who do not have a contact phone number listed.

[Assistant] SELECT first_name, last_name, national_id_number, contact_email FROM government_services.citizens WHERE contact_phone IS NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- 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] What is the current location of train number Acela 2151?

[Assistant] I'm sorry, but I don't have access to real-time location data for trains. The database only contains static information such as train ID, model, capacity, and maintenance schedules. For current location updates, please check with the train operator or a tracking service.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.trains (
    train_id character varying(64) NOT NULL, -- Unique identifier for the train set
    train_number character varying(32) NOT NULL, -- Operational number of the train (e.g., 'Acela 2151')
    model character varying(128), -- Model of the train (e.g., 'Siemens Velaro')
    manufacturer character varying(128), -- Manufacturer of the train
    year_manufactured integer, -- Year the train was built
    capacity integer NOT NULL, -- Total passenger capacity
    status character varying(32) NOT NULL DEFAULT 'Active', -- e.g., Active, Maintenance, Retired
    last_maintenance_date date, -- Date of last scheduled maintenance
    next_maintenance_date date, -- Date of next scheduled maintenance
    PRIMARY KEY (train_id),
    UNIQUE (train_number)
)


[User] Show the number of active agents in each license state.

[Assistant]
SELECT license_state,
       COUNT(*) AS active_agent_count
FROM insurance.agents
WHERE status = 'active'
GROUP BY license_state;

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.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )


[User] For each fundraising round in 2022 and 2023, list the round name, the year, the total investment_value, and the count of distinct projects. Also include the average market_cap of associated tokens by matching project_name to token_symbol in token_basic_info.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) = LOWER(t.token_symbol)
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4);

[User] The join returns no rows. Please change the join to match when token_symbol is contained within project_name, case-insensitive.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) LIKE '%' || LOWER(t.token_symbol) || '%'
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4);

[User] Now only include rounds where the total investment_value exceeds 5000000.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) LIKE '%' || LOWER(t.token_symbol) || '%'
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4)
HAVING SUM(p.investment_value) > 5000000;

[User] Finally, order the results by total_investment descending.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) LIKE '%' || LOWER(t.token_symbol) || '%'
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4)
HAVING SUM(p.investment_value) > 5000000
ORDER BY total_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, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
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 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, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )


[User] Calculate the total value of unspent UTXOs for each user whose KYC status has been 'approved'.

[Assistant] SELECT kyc.user_id, SUM(u.amount) FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status = 'approved' AND u.spent = false GROUP BY kyc.user_id;

[User] Refine that to only show users where this total value exceeds 1000.

[Assistant] SELECT kyc.user_id, SUM(u.amount) FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status = 'approved' AND u.spent = false GROUP BY kyc.user_id HAVING SUM(u.amount) > 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 trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )


[User] For each guest, list reservation_id, guest_id, check_in_date, and the next reservation_id and its check_in_date.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     );

[User] Only include guests who have at least two reservations.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     )
WHERE r1.guest_id IN (
  SELECT guest_id
  FROM reservations
  GROUP BY guest_id
  HAVING COUNT(*) >= 2
);

[User] Also, only show next reservations that occur within 30 days of the current reservation.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     )
   AND r2.check_in_date <= r1.check_in_date + INTERVAL '30 days'
WHERE r1.guest_id IN (
  SELECT guest_id
  FROM reservations
  GROUP BY guest_id
  HAVING COUNT(*) >= 2
);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )


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

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

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

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

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

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

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

[Assistant] SELECT department, COUNT(*), STRING_AGG(DISTINCT job_title, ', '), SUM(CASE WHEN EXTRACT(YEAR FROM hire_date) = 2023 THEN 1 ELSE 0 END) AS employees_hired_in_2023 FROM government_services.employees GROUP BY department HAVING COUNT(*) > 5

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )


[User] Find all pairs of contracts deployed by the same deployer on the same day, showing the deployer_address, the deployment date, and both contract IDs.

[Assistant]
SELECT c1.deployer_address,
       DATE(c1.deployed_at) AS deploy_date,
       c1.contract_id AS contract_id_1,
       c2.contract_id AS contract_id_2
FROM web3.contracts c1
JOIN web3.contracts c2
  ON c1.deployer_address = c2.deployer_address
 AND DATE(c1.deployed_at) = DATE(c2.deployed_at)
 AND c1.contract_id < c2.contract_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.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )


[User] What is the total payment amount for each currency recorded in the payments table?

[Assistant] SELECT currency ,  sum(amount) FROM government_services.payments GROUP BY currency

[User] Now, only show currencies where the total amount paid is greater than 10000.

[Assistant] SELECT currency ,  sum(amount) FROM government_services.payments GROUP BY currency HAVING sum(amount)  >  10000

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] What are the personal contact details of the staff member associated with staff_id 'STAFF789' who worked on a specific maintenance record?

[Assistant] I'm sorry, but I can't provide personal contact details of staff members as this information is not stored in the maintenance_records table and is outside the scope of the available data.

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] What is the average commission rate for active agents?

[Assistant] SELECT AVG(commission_rate) FROM insurance.agents WHERE status = 'Active';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.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 )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] For each vehicle, show the first and last fueling events including their timestamps and the quantities refueled.

[Assistant]
WITH first_last AS (
  SELECT
    vehicle_id,
    MIN(log_timestamp) AS first_time,
    MAX(log_timestamp) AS last_time
  FROM transportation.fuel_logs
  GROUP BY vehicle_id
)
SELECT
  f1.vehicle_id,
  f1.log_timestamp AS first_refuel_time,
  f1.quantity AS first_quantity,
  f2.log_timestamp AS last_refuel_time,
  f2.quantity AS last_quantity
FROM first_last fl
JOIN transportation.fuel_logs f1
  ON fl.vehicle_id = f1.vehicle_id
  AND fl.first_time = f1.log_timestamp
JOIN transportation.fuel_logs f2
  ON fl.vehicle_id = f2.vehicle_id
  AND fl.last_time = f2.log_timestamp;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)


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

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

[User] Actually, I only want those overlapping pairs where both policies are currently active.

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

[User] Also include the policy numbers for both policies in the output.

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

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


[User] Find all pairs of different insurance records that share the same group_number, and show group_number, the patient_insurance_id of both records, and their corresponding patient_ids.

[Assistant]
SELECT a.group_number,
       a.patient_insurance_id AS pi_id1,
       a.patient_id            AS patient1_id,
       b.patient_insurance_id AS pi_id2,
       b.patient_id            AS patient2_id
FROM healthcare.patient_insurance a
JOIN healthcare.patient_insurance b
  ON a.group_number = b.group_number
 AND a.patient_insurance_id < b.patient_insurance_id
WHERE a.group_number 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 healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] What is the number of guests per country, grouped by country_code?

[Assistant]
SELECT country_code,
       COUNT(*) AS guest_count
FROM hospitality_technology.guests
GROUP BY country_code;

[User] Only include countries that have at least 5 guests.

[Assistant]
SELECT country_code,
       COUNT(*) AS guest_count
FROM hospitality_technology.guests
GROUP BY country_code
HAVING COUNT(*) >= 5;

[User] Also include the most recently registered guest in each of those countries, showing their full name and created_at.

[Assistant]
WITH country_counts AS (
  SELECT country_code,
         COUNT(*) AS guest_count,
         MAX(created_at) AS last_reg
  FROM hospitality_technology.guests
  GROUP BY country_code
  HAVING COUNT(*) >= 5
)
SELECT cc.country_code,
       cc.guest_count,
       g.first_name || ' ' || g.last_name AS last_guest_name,
       g.created_at          AS last_registration
FROM country_counts cc
JOIN hospitality_technology.guests g
  ON g.country_code = cc.country_code
 AND g.created_at = cc.last_reg;

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.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )


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

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

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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )


[User] Provide the count of transfers for each token_id.

[Assistant]
SELECT token_id,
       COUNT(*) AS transfer_count
FROM web3.token_transfers
GROUP BY token_id;

[User] Actually, also include the total transferred value for each token_id.

[Assistant]
SELECT token_id,
       COUNT(*) AS transfer_count,
       SUM(value) AS total_transferred_value
FROM web3.token_transfers
GROUP BY 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.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )


[User] List the plan_id, plan_name, and plan_type for all insurance plans where the insurance_provider is 'Humana'.

[Assistant]
SELECT
  plan_id,
  plan_name,
  plan_type
FROM healthcare.insurance_plans
WHERE
  insurance_provider = 'Humana';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.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.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)


[User] List tokens with trend rank 5 or better and a price below $1. Show symbol, price, and trend rank.

[Assistant] SELECT token_symbol, price, trend_rank FROM token_dexpool_info WHERE trend_rank IS NOT NULL AND trend_rank <= 5 AND price < 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )


[User] Which route numbers connect locations with a distance less than 80 km and more than 5 words in their description? Include the route type in the results.

[Assistant] SELECT route_number, type FROM transportation.routes WHERE distance_km < 80 AND array_length(regexp_split_to_array(description, '\s+'), 1) > 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )


[User] Provide a breakdown of the total number of conversations, showing how many are group chats and how many are not. Also, show the count of conversations that have a recorded last message time.

[Assistant] SELECT COUNT(*) AS total_conversations, COUNT(CASE WHEN is_group_chat = true THEN 1 END) AS group_chat_count, COUNT(CASE WHEN is_group_chat = false THEN 1 END) AS private_chat_count, COUNT(last_message_at) AS conversations_with_messages_count FROM social_media.conversations;

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


[User] For each trip that has bookings, show the trip ID and the total number of bookings associated with it.

[Assistant] SELECT T.trip_id, COUNT(B.booking_id) AS booking_count FROM transportation.trips AS T JOIN transportation.bookings AS B ON T.trip_id = B.trip_id GROUP BY T.trip_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
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.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )


[User] List all pairs of law firms that were founded on the same month and day, showing their names, and the shared founding date. Exclude firms founded on January 1st.

[Assistant] SELECT t1.firm_name AS firm1_name, t2.firm_name AS firm2_name, t1.founded_date FROM legal_services.law_firms AS t1 JOIN legal_services.law_firms AS t2 ON MONTH(t1.founded_date) = MONTH(t2.founded_date) AND DAY(t1.founded_date) = DAY(t2.founded_date) AND t1.firm_id < t2.firm_id WHERE MONTH(t1.founded_date) <> 1 OR DAY(t1.founded_date) <> 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )


[User] Show the plan name and insurance provider for all insurance plans along with the total number of unique patients enrolled in each plan.

[Assistant]
SELECT ip.plan_name, ip.insurance_provider, COUNT(DISTINCT pi.patient_id) AS enrolled_patient_count
FROM healthcare.insurance_plans ip
JOIN healthcare.patients_insurance pi ON ip.plan_id = pi.plan_id
GROUP BY ip.plan_name, ip.insurance_provider;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
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.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )


[User] Show me all lawyers' full names, their bar number, and if they are partners, the full name of another partner from their firm.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1;

[User] Only include lawyers who have an email address specified.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1
WHERE l1.email IS NOT NULL AND l1.email <> '';

[User] Actually, restrict it to lawyers hired in or after 2023.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1
WHERE l1.email IS NOT NULL AND l1.email <> '' AND l1.hire_date >= '2023-01-01';

[User] Sort the results by the lawyer's last name in descending order.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1
WHERE l1.email IS NOT NULL AND l1.email <> '' AND l1.hire_date >= '2023-01-01'
ORDER BY l1.last_name 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.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )


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

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

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


[User] List the first and last name of each citizen along with the city and state of the service location for their agency.

[Assistant]
SELECT c.first_name, c.last_name, sl.city, sl.state
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.employees e ON p.application_id IS NOT NULL AND e.agency_id IS NOT NULL
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, 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.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )


[User] 特定の職種の従業員情報を取得したいです。従業員ID、名前、職種、雇用日を表示してください。

[Assistant]
db.employees.find(
    { job_title: '<specific_job_title>' },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用日が2020年1月1日以降の従業員だけに絞り込むことはできますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') }
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用ステータスが「Active」の従業員だけをさらに条件に加えられますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] スキル認定情報も結果に含めてください。

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, skill_certifications: 1, _id: 0 }
).sort({ hire_date: -1 })

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Collection 'assembly_steps'. Document structure: { _id: <ObjectId (or step_id)>, step_id: String, line_id: String (reference), step_number: NumberInt, step_name: String, description: String, standard_duration_hours: Decimal128, required_skill_level: String, workstation: String }. Required: step_id, line_id, step_number, step_name. Index on line_id, step_number.
Collection 'employees'. Document structure: { _id: <ObjectId (or employee_id)>, employee_id: String, first_name: String, last_name: String, job_title: String, skill_certifications: [String], hire_date: ISODate, assigned_line_id: String (reference, optional), employment_status: String, supervisor_employee_id: String (reference, optional) }. Required: employee_id, first_name, last_name, job_title, hire_date, employment_status.


[User] I need to get the most recent message each verified user has sent in any group chat, showing username, group_name, message_id, and sent_at.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
WHERE ur.rn = 1
  AND u.is_verified = true;

[User] Actually, I only want messages sent in the past 30 days.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
    AND m.sent_at >= NOW() - INTERVAL '30 days'
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
WHERE ur.rn = 1
  AND u.is_verified = true;

[User] Also, exclude any users who have disabled push notifications.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
    AND m.sent_at >= NOW() - INTERVAL '30 days'
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
JOIN social_media.user_settings s ON s.user_id = u.user_id
WHERE ur.rn = 1
  AND u.is_verified = true
  AND s.push_notifications_enabled = true;

[User] And order the results by sent_at descending.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
    AND m.sent_at >= NOW() - INTERVAL '30 days'
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
JOIN social_media.user_settings s ON s.user_id = u.user_id
WHERE ur.rn = 1
  AND u.is_verified = true
  AND s.push_notifications_enabled = true
ORDER BY ur.sent_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, 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.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )


[User] Give me the total billed amount for each invoice in 2024.

[Assistant] SELECT invoice_id, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE AND EXTRACT(YEAR FROM date_worked) = 2024 GROUP BY invoice_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.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )


[User] What are the maintenance costs for a specific aircraft model like the Airbus A320?

[Assistant] I'm sorry, but I don't have access to data regarding maintenance costs for specific aircraft models such as the Airbus A320. The information in the database is limited to details like model name, manufacturer, passenger capacity, and technical specifications. For maintenance cost information, you may need to consult with the manufacturer or a maintenance service provider.

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


[User] Show the total balance for each SUI coin across all owners. Group by coin_type.

[Assistant]
SELECT coin_type,
       SUM(CAST(balance AS DECIMAL)) AS total_balance
FROM sui_coins
GROUP BY coin_type;

[User] Also include symbol, name, decimals and description from the metadata table by joining on coin_type.

[Assistant]
SELECT sc.coin_type,
       scm.symbol,
       scm.name,
       scm.decimals,
       scm.description,
       SUM(CAST(sc.balance AS DECIMAL)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata scm
  ON sc.coin_type = scm.coin_type
GROUP BY sc.coin_type, scm.symbol, scm.name, scm.decimals, scm.description;

[User] Only include metadata entries where status = 'exists' and description contains the word 'staking'.

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

[User] Sort the results by total_balance descending and limit to the top 3 coins.

[Assistant]
SELECT sc.coin_type,
       scm.symbol,
       scm.name,
       scm.decimals,
       scm.description,
       SUM(CAST(sc.balance AS DECIMAL)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata scm
  ON sc.coin_type = scm.coin_type
WHERE scm.status = 'exists'
  AND scm.description ILIKE '%staking%'
GROUP BY sc.coin_type, scm.symbol, scm.name, scm.decimals, scm.description
ORDER BY total_balance DESC
LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
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 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_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_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 all staff members, showing their full name, position, and the name of the property where they work.

[Assistant] SELECT T1.first_name, T1.last_name, T1.position, T2.property_name FROM hospitality_technology.staff AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id;

[User] Only include staff who are currently active and add their manager's full name if they have one.

[Assistant] SELECT T1.first_name AS staff_first_name, T1.last_name AS staff_last_name, T1.position, T2.property_name, T3.first_name AS manager_first_name, T3.last_name AS manager_last_name FROM hospitality_technology.staff AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id LEFT JOIN hospitality_technology.staff AS T3 ON T1.manager_id = T3.staff_id WHERE T1.is_active = TRUE;

[User] Filter further to only include staff working at properties in the 'California' state and sort by property name, then staff last name.

[Assistant] SELECT T1.first_name AS staff_first_name, T1.last_name AS staff_last_name, T1.position, T2.property_name, T3.first_name AS manager_first_name, T3.last_name AS manager_last_name FROM hospitality_technology.staff AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id LEFT JOIN hospitality_technology.staff AS T3 ON T1.manager_id = T3.staff_id WHERE T1.is_active = TRUE AND T2.state_province = 'California' ORDER BY T2.property_name, T1.last_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, type_name character varying(100) NOT NULL, description text, base_rate numeric(10, 2) NOT NULL, max_occupancy integer NOT NULL, bed_type character varying(50), area_sqft numeric(8,2), amenities text, PRIMARY KEY (room_type_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
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) )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )


[User] Find all pairs of overlapping payment periods for the same customer. Return customer_id, first payment_id as payment1_id, second payment_id as payment2_id, and both periods' start and end dates.

[Assistant]
SELECT p1.customer_id,
       p1.payment_id AS payment1_id,
       p2.payment_id AS payment2_id,
       p1.payment_period_start AS start1,
       p1.payment_period_end   AS end1,
       p2.payment_period_start AS start2,
       p2.payment_period_end   AS end2
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.customer_id = p2.customer_id
 AND p1.payment_id < p2.payment_id
 -- periods overlap
 AND p1.payment_period_start <= p2.payment_period_end
 AND p2.payment_period_start <= p1.payment_period_end;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)


[User] Count how many insurance policies do not have a group number specified.

[Assistant] SELECT COUNT(*) FROM healthcare.patient_insurance WHERE group_number IS NULL;

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


[User] List service orders placed in the last 7 days, showing order_id, service_name, guest full name, and order_timestamp.

[Assistant]
SELECT so.order_id, s.service_name, g.first_name || ' ' || g.last_name AS guest_name, so.order_timestamp
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id
WHERE so.order_timestamp >= current_date - INTERVAL '7 days';

[User] Filter to only those orders with status 'Delivered' and sort by delivery_timestamp ascending.

[Assistant]
SELECT so.order_id, s.service_name, g.first_name || ' ' || g.last_name AS guest_name, so.order_timestamp, so.delivery_timestamp
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id
WHERE so.order_timestamp >= current_date - INTERVAL '7 days'
  AND so.status = 'Delivered'
ORDER BY so.delivery_timestamp ASC;

[User] Also include the staff member who delivered the service as delivered_by (full name) and limit to 10 records.

[Assistant]
SELECT so.order_id, s.service_name, g.first_name || ' ' || g.last_name AS guest_name, so.order_timestamp, so.delivery_timestamp, st.first_name || ' ' || st.last_name AS delivered_by
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id
JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id
WHERE so.order_timestamp >= current_date - INTERVAL '7 days'
  AND so.status = 'Delivered'
ORDER BY so.delivery_timestamp ASC
LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )


[User] 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] Find all pairs of distinct routes that share the same origin location ID. List the route IDs and route numbers for both routes in each pair, along with the shared origin location ID.

[Assistant] SELECT r1.route_id AS route1_id, r1.route_number AS route1_number, r2.route_id AS route2_id, r2.route_number AS route2_number, r1.origin_location_id FROM transportation.routes AS r1 JOIN transportation.routes AS r2 ON r1.origin_location_id = r2.origin_location_id WHERE r1.route_id < r2.route_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )