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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )


[User] 能否帮我统计特定车站(station_id 为 'station_xyz')的所有工作人员数量？

[Assistant]
MATCH (s:Station {station_id: 'station_xyz'})<-[:BASED_AT]-(staff:Staff)
RETURN COUNT(staff) AS total_staff

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
// Node Label: :Station
// Properties:
//   station_id: String (Constraint: UNIQUE)
//   station_name: String
//   city: String (Index recommended)
//   state_province: String
//   country_code: String
//   address: String
//   timezone: String
//   number_of_platforms: Integer
//   created_at: DateTime
//   last_updated_at: DateTime
// Example Cypher CREATE:
// CREATE (:Station {station_id: 'station_xyz', station_name: 'Grand Central Terminal', city: 'New York', ...})
// Node Label: :Platform
// Properties:
//   platform_id: String (Constraint: UNIQUE)
//   platform_number: String
//   track_number: String
//   status: String
//   length_meters: Float
//   accessible: Boolean
// Relationship: (:Platform)-[:LOCATED_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (s:Station {station_id: 'station_xyz'})
// CREATE (p:Platform {platform_id: 'plat_123', ...})-[:LOCATED_AT]->(s)
// Node Label: :Train
// Properties:
//   train_id: String (Constraint: UNIQUE)
//   train_number: String (Constraint: UNIQUE)
//   model: String
//   manufacturer: String
//   year_manufactured: Integer
//   capacity: Integer
//   status: String
//   last_maintenance_date: Date
//   next_maintenance_date: Date
// Example Cypher CREATE:
// CREATE (:Train {train_id: 'train_789', train_number: 'Acela 2151', ...})
// Node Label: :TrainCar
// Properties:
//   car_id: String (Constraint: UNIQUE)
//   car_number: String
//   car_type: String
//   class: String
//   capacity: Integer
//   features: String (Or List<String> if driver supports)
// Relationship: (:TrainCar)-[:PART_OF_TRAIN]->(:Train)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'})
// CREATE (c:TrainCar {car_id: 'car_abc', ...})-[:PART_OF_TRAIN]->(t)
// Node Label: :Route
// Properties:
//   route_id: String (Constraint: UNIQUE)
//   route_name: String
//   description: String
//   is_active: Boolean
// Relationships:
//   (:Route)-[:STARTS_AT]->(:Station)
//   (:Route)-[:ENDS_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (origin:Station {station_id: 'station_bos'}), (dest:Station {station_id: 'station_was'})
// CREATE (r:Route {route_id: 'route_ne_corr', ...})-[:STARTS_AT]->(origin), (r)-[:ENDS_AT]->(dest)
// Relationship: (:Route)-[rel:HAS_STOP]->(:Station)
// Relationship Properties on :HAS_STOP:
//   sequence_order: Integer
//   distance_from_previous_km: Float
//   typical_stop_duration_minutes: Integer
// Example Cypher CREATE:
// MATCH (r:Route {route_id: 'route_ne_corr'}), (s:Station {station_id: 'station_pvd'})
// CREATE (r)-[:HAS_STOP {sequence_order: 2, distance_from_previous_km: 70.5, ...}]->(s)
// Node Label: :ScheduledTrip (or just :Trip)
// Properties:
//   schedule_id: String (Constraint: UNIQUE)
//   departure_datetime: DateTime
//   arrival_datetime: DateTime
//   status: String
//   notes: String
// Relationships:
//   (:ScheduledTrip)-[:USES_TRAIN]->(:Train)
//   (:ScheduledTrip)-[:FOLLOWS_ROUTE]->(:Route)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'}), (r:Route {route_id: 'route_ne_corr'})
// CREATE (sched:ScheduledTrip {schedule_id: 'sched_1122', ...})-[:USES_TRAIN]->(t), (sched)-[:FOLLOWS_ROUTE]->(r)
// Relationship: (:ScheduledTrip)-[rel:SCHEDULED_STOP]->(:Station)
// Relationship Properties on :SCHEDULED_STOP:
//   sequence_order: Integer
//   platform_id: String (references Platform node if modeled, or just store ID)
//   scheduled_arrival_time: DateTime
//   scheduled_departure_time: DateTime
//   actual_arrival_time: DateTime
//   actual_departure_time: DateTime
//   status: String
// Example Cypher CREATE:
// MATCH (sched:ScheduledTrip {schedule_id: 'sched_1122'}), (s:Station {station_id: 'station_pvd'})
// CREATE (sched)-[:SCHEDULED_STOP {sequence_order: 2, platform_id: 'plat_pvd_1', ...}]->(s)
// Node Label: :Passenger
// Properties:
//   passenger_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   email: String (Constraint: UNIQUE, if not null)
//   phone_number: String (Constraint: UNIQUE, if not null)
//   date_of_birth: Date
//   loyalty_program_id: String
//   created_at: DateTime
// Example Cypher CREATE:
// CREATE (:Passenger {passenger_id: 'pass_pqr', first_name: 'Alice', ...})
// Node Label: :Booking
// Properties:
//   booking_id: String (Constraint: UNIQUE)
//   booking_datetime: DateTime
//   status: String
//   total_price: Float
//   currency_code: String
//   special_requests: String
// Relationships:
//   (:Passenger)-[:MADE_BOOKING]->(:Booking)
//   (:Booking)-[:FOR_TRIP]->(:ScheduledTrip)
// Example Cypher CREATE:
// MATCH (p:Passenger {passenger_id: 'pass_pqr'}), (sched:ScheduledTrip {schedule_id: 'sched_1122'})
// CREATE (p)-[:MADE_BOOKING]->(b:Booking {booking_id: 'book_zyx', ...})-[:FOR_TRIP]->(sched)
// Node Label: :Ticket
// Properties:
//   ticket_id: String (Constraint: UNIQUE)
//   seat_number: String
//   ticket_type: String
//   price: Float
//   is_checked_in: Boolean
//   qr_code_data: String
// Relationships:
//   (:Ticket)-[:PART_OF_BOOKING]->(:Booking)
//   (:Ticket)-[:ASSIGNED_TO_CAR]->(:TrainCar)
// Example Cypher CREATE:
// MATCH (b:Booking {booking_id: 'book_zyx'}), (c:TrainCar {car_id: 'car_abc'})
// CREATE (t:Ticket {ticket_id: 'tkt_1a2b', ...})-[:PART_OF_BOOKING]->(b), (t)-[:ASSIGNED_TO_CAR]->(c)
// Node Label: :Staff
// Properties:
//   staff_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   role: String
//   employee_number: String (Constraint: UNIQUE)
//   hire_date: Date
//   contact_email: String (Constraint: UNIQUE, if not null)
//   contact_phone: String
//   is_active: Boolean
// Relationship (Optional):
//   (:Staff)-[:BASED_AT]->(:Station)
// Example Cypher CREATE:
// CREATE (:Staff {staff_id: 'staff_mno', first_name: 'Bob', ...})
// OPTIONAL MATCH (s:Station {station_id: 'station_xyz'}) // If primary_station_id exists
// WITH s, staff_mno // Need to get the created staff node reference
// WHERE s IS NOT NULL
// CREATE (staff_mno)-[:BASED_AT]->(s)


[User] List all employees who are currently active and were hired before 2022. Show employee_id, first_name, last_name, job_title, department, and hire_date.

[Assistant]
SELECT
  employee_id,
  first_name,
  last_name,
  job_title,
  department,
  hire_date
FROM financial_services.employees
WHERE
  status = 'Active' AND hire_date < '2022-01-01';

[User] Also, only include employees from the 'IT' or 'Operations' departments.

[Assistant]
SELECT
  employee_id,
  first_name,
  last_name,
  job_title,
  department,
  hire_date
FROM financial_services.employees
WHERE
  status = 'Active' AND hire_date < '2022-01-01' AND department IN ('IT', 'Operations');

[User] Sort the results by hire date ascending and limit to the first 5.

[Assistant]
SELECT
  employee_id,
  first_name,
  last_name,
  job_title,
  department,
  hire_date
FROM financial_services.employees
WHERE
  status = 'Active' AND hire_date < '2022-01-01' AND department IN ('IT', 'Operations')
ORDER BY
  hire_date ASC
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 financial_services.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    PRIMARY KEY (transaction_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id)
)
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)


[User] List all staff members along with their manager's full name.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
LEFT JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id;

[User] Only include staff who are active and have a manager assigned. Sort the results by manager's last name.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id
WHERE s.is_active = true
ORDER BY m.last_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)


[User] Show me the top 5 token balances by amount for wallet '0xabc123abcdef' in the erc20_balances table.

[Assistant]
SELECT contract_address, amount
FROM erc20_balances
WHERE wallet_address = '0xabc123abcdef'
ORDER BY CAST(amount AS numeric) DESC
LIMIT 5;

[User] Include token symbol and decimals from token_prices_latest by joining on contract_address = address.

[Assistant]
SELECT eb.contract_address, eb.amount, tpl.symbol, tpl.decimals
FROM erc20_balances eb
JOIN token_prices_latest tpl ON eb.contract_address = tpl.address
WHERE eb.wallet_address = '0xabc123abcdef'
ORDER BY CAST(eb.amount AS numeric) DESC
LIMIT 5;

[User] Filter to tokens where the latest price is greater than 1.0.

[Assistant]
SELECT eb.contract_address, eb.amount, tpl.symbol, tpl.decimals
FROM erc20_balances eb
JOIN token_prices_latest tpl ON eb.contract_address = tpl.address
WHERE eb.wallet_address = '0xabc123abcdef'
  AND tpl.price > 1.0
ORDER BY CAST(eb.amount AS numeric) DESC
LIMIT 5;

[User] Add a computed column usd_value as amount * price.

[Assistant]
SELECT eb.contract_address,
       eb.amount,
       tpl.symbol,
       tpl.decimals,
       tpl.price,
       CAST(eb.amount AS numeric) * tpl.price AS usd_value
FROM erc20_balances eb
JOIN token_prices_latest tpl ON eb.contract_address = tpl.address
WHERE eb.wallet_address = '0xabc123abcdef'
  AND tpl.price > 1.0
ORDER BY CAST(eb.amount AS numeric) DESC
LIMIT 5;

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


[User] How many policies were canceled in the previous month, grouped by cancellation reason?

[Assistant]
SELECT cancellation_reason,
       COUNT(*) AS canceled_count
FROM insurance.policies
WHERE cancellation_date BETWEEN date_trunc('month', CURRENT_DATE) - INTERVAL '1 month'
                             AND date_trunc('month', CURRENT_DATE) - INTERVAL '1 day'
GROUP BY cancellation_reason;

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


[User] What is the current number of passengers at station with ID 'ST123' right now?

[Assistant] I'm sorry, but I can't provide information on the current number of passengers at a station. The data I have access to only includes static details about stations such as their name, location, and number of platforms, not real-time passenger counts.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.stations (
    station_id character varying(64) NOT NULL,  -- Unique identifier for the station
    station_name character varying(128) NOT NULL, -- Name of the station
    city character varying(100) NOT NULL, -- City where the station is located
    state_province character varying(100), -- State or province
    country_code character varying(3) NOT NULL, -- ISO country code
    address text, -- Full address of the station
    timezone character varying(64) NOT NULL, -- Timezone ID (e.g., 'America/New_York')
    number_of_platforms integer NOT NULL DEFAULT 0, -- Total number of platforms
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When the station record was created
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When the station record was last updated
    PRIMARY KEY (station_id)
)


[User] What is the average ROI and average realized_ratio for each chain?

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

[User] Now filter to only include chains where average ROI is above 0.5.

[Assistant]
WITH stats AS (
  SELECT chain,
         AVG(roi) AS avg_roi,
         AVG(realized_ratio) AS avg_realized_ratio
  FROM smart_money_token_performance
  GROUP BY chain
)
SELECT chain, avg_roi, avg_realized_ratio
FROM stats
WHERE avg_roi > 0.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 smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )


[User] For each city that has a fueling location, show the city name and the total quantity of fuel refueled.

[Assistant] SELECT T2.city ,  SUM(T1.quantity) FROM transportation.fuel_logs AS T1 JOIN transportation.locations AS T2 ON T1.location_id  =  T2.location_id GROUP BY T2.city

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.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )


[User] I’d like to get the count of notifications each user received for their own posts in the last 30 days.

[Assistant]
SELECT u.user_id, u.username, COUNT(n.notification_id) AS notification_count
FROM social_media.notifications n
JOIN social_media.posts p ON n.target_entity_type = 'post' AND n.target_entity_id = p.post_id
JOIN social_media.users u ON p.user_id = u.user_id
WHERE n.created_at >= now() - interval '30 days'
GROUP BY u.user_id, u.username;

[User] Now, I only want notifications of type 'like' or 'comment'.

[Assistant]
SELECT u.user_id, u.username, COUNT(n.notification_id) AS notification_count
FROM social_media.notifications n
JOIN social_media.posts p ON n.target_entity_type = 'post' AND n.target_entity_id = p.post_id
JOIN social_media.users u ON p.user_id = u.user_id
WHERE n.created_at >= now() - interval '30 days'
  AND n.notification_type IN ('like', 'comment')
GROUP BY u.user_id, u.username;

[User] Show me only the top 3 users by notification_count.

[Assistant]
SELECT u.user_id, u.username, COUNT(n.notification_id) AS notification_count
FROM social_media.notifications n
JOIN social_media.posts p ON n.target_entity_type = 'post' AND n.target_entity_id = p.post_id
JOIN social_media.users u ON p.user_id = u.user_id
WHERE n.created_at >= now() - interval '30 days'
  AND n.notification_type IN ('like', 'comment')
GROUP BY u.user_id, u.username
ORDER BY notification_count DESC
LIMIT 3;

[User] Also include the email of these top users.

[Assistant]
SELECT u.user_id, u.username, u.email, COUNT(n.notification_id) AS notification_count
FROM social_media.notifications n
JOIN social_media.posts p ON n.target_entity_type = 'post' AND n.target_entity_id = p.post_id
JOIN social_media.users u ON p.user_id = u.user_id
WHERE n.created_at >= now() - interval '30 days'
  AND n.notification_type IN ('like', 'comment')
GROUP BY u.user_id, u.username, u.email
ORDER BY notification_count 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 social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
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] List all active insurance products, including their product name, type, and base premium.

[Assistant] SELECT product_name, product_type, base_premium FROM insurance.insurance_products WHERE is_active = TRUE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )


[User] Show me all time entries from the last 90 days, including the entry description, hours spent, the name of the case, and the name of the client.

[Assistant] SELECT T1.description, T1.hours_spent, T2.case_name, T3.first_name, T3.last_name FROM legal_services.time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id JOIN clients AS T3 ON T2.client_id = T3.client_id WHERE T1.date_worked >= CURRENT_DATE - INTERVAL '90 days';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)


[User] What is the current job satisfaction level or feedback from staff members working at a specific train station?

[Assistant] I'm sorry, but I can't provide information on job satisfaction levels or feedback from staff members as this data is not included in the staff table.

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.staff ( staff_id.text, first_name.text, last_name.text, role.text, primary_station_id.text, employee_number.text, hire_date.date, contact_email.text, contact_phone.text, is_active.boolean )


[User] Show me the total transaction amount by transaction_type for all transactions processed by employees in the 'Trading' department, along with their department name.

[Assistant]
SELECT t.transaction_type, SUM(t.amount) AS total_amount, e.department
FROM financial_services.transactions t
JOIN financial_services.employees e ON t.account_id IN (
    SELECT account_id
    FROM financial_services.accounts
    WHERE branch_id = e.branch_id
)
WHERE e.department = 'Trading'
GROUP BY t.transaction_type, e.department;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    PRIMARY KEY (transaction_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id)
)
CREATE TABLE financial_services.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )


[User] For each patient, find the next appointment after each one. Return patient_id, appointment_id, next_appointment_id, and the waiting time in minutes between them.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   );

[User] Now include only the pairs where the waiting time is less than 30 minutes.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   )
WHERE EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 < 30;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )


[User] List all invoices that were paid within 7 days of their issue date. Show invoice number, issue date, payment date, and total amount.

[Assistant] SELECT invoice_number, issue_date, payment_date, total_amount FROM legal_services.invoices WHERE status = 'Paid' AND payment_date IS NOT NULL AND (payment_date::DATE - issue_date) <= 7;

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 )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )


[User] Show me all insurance plans that have more than 3 patients enrolled as their primary insurance, along with the provider name and count of patients, sorted by patient count in descending order.

[Assistant] SELECT ip.insurance_provider, COUNT(pi.patient_id) AS patient_count FROM healthcare.insurance_plans ip JOIN healthcare.patient_insurance pi ON ip.plan_id = pi.plan_id WHERE pi.is_primary = true GROUP BY ip.insurance_provider HAVING COUNT(pi.patient_id) > 3 ORDER BY patient_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text PRIMARY KEY, 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 character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, 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.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
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 pairs of citizens who share the same email domain.

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

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


[User] Can you list all SUI coins with 'active' status and their owner addresses and balances?

[Assistant]
SELECT object_id, coin_type, owner, balance
FROM sui_coins
WHERE status = 'active';

[User] Add the coin symbol and name from the sui_coins_metadata table.

[Assistant]
SELECT sc.object_id, sc.coin_type, sc.owner, sc.balance, scm.symbol, scm.name
FROM sui_coins sc
LEFT JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'active';

[User] Only include coins where the description mentions 'utility'.

[Assistant]
SELECT sc.object_id, sc.coin_type, sc.owner, sc.balance, scm.symbol, scm.name
FROM sui_coins sc
LEFT JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'active' AND scm.description ILIKE '%utility%';

[User] Limit the output to the top 10 coins sorted by balance descending.

[Assistant]
SELECT sc.object_id, sc.coin_type, sc.owner, sc.balance, scm.symbol, scm.name
FROM sui_coins sc
LEFT JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'active' AND scm.description ILIKE '%utility%'
ORDER BY CAST(sc.balance AS BIGINT) DESC
LIMIT 10;

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


[User] List all log entries associated with users who have participated in any trade, showing the log details and the trade ID.

[Assistant] SELECT T1.log_id, T1.action, T1.details, T1.logged_at, T2.trade_id, T2.buyer_id, T2.seller_id FROM logs AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id;

[User] Only show logs and trades that occurred in the last week.

[Assistant] SELECT T1.log_id, T1.action, T1.details, T1.logged_at, T2.trade_id, T2.buyer_id, T2.seller_id FROM logs AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id WHERE T1.logged_at >= datetime('now', '-7 days') AND T2.traded_at >= datetime('now', '-7 days');

[User] Can you instead provide a count of such log entries per user who traded, for the last week?

[Assistant] SELECT T1.user_id, COUNT(DISTINCT T1.log_id) AS log_count FROM logs AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id WHERE T1.logged_at >= datetime('now', '-7 days') AND T2.traded_at >= datetime('now', '-7 days') GROUP BY T1.user_id;

[User] Also include the total number of trades for each user in the same period and sort by trade count descending.

[Assistant] SELECT T1.user_id, COUNT(DISTINCT T1.log_id) AS log_count, COUNT(DISTINCT T2.trade_id) AS trade_count FROM logs AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id WHERE T1.logged_at >= datetime('now', '-7 days') AND T2.traded_at >= datetime('now', '-7 days') GROUP BY T1.user_id ORDER BY trade_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 trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.trades ( trade_id.text, order_id.text, buyer_id.text, seller_id.text, asset_id.text, quantity.numeric, price.numeric, traded_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp )


[User] What are the specific tools or equipment used during the maintenance with record_id 'REC456'?

[Assistant] I'm sorry, but I can't provide information about the specific tools or equipment used during a maintenance record. The data in the maintenance_records table does not include details about tools or equipment used.

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 PRIMARY KEY, asset_id text, asset_type text, maintenance_type text, staff_id text, start_datetime timestamp, end_datetime timestamp, description text, cost numeric, status text )


[User] Show the full names and registration dates of citizens who have submitted applications with the status 'Processing'.

[Assistant]
SELECT DISTINCT c.first_name, c.last_name, c.registration_date
FROM government_services.citizens c
JOIN government_services.applications a ON c.citizen_id = a.citizen_id
WHERE a.status = 'Processing';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)


[User] List each appointment with appointment ID, appointment time, doctor's last name, and the patient's primary insurance plan name.

[Assistant]
SELECT a.appointment_id,
       a.appointment_time,
       d.last_name AS doctor_last_name,
       p.plan_name
FROM healthcare.appointments a
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
JOIN healthcare.patient_insurance pi ON a.patient_id = pi.patient_id AND pi.is_primary = true
JOIN healthcare.insurance_plans p ON pi.plan_id = p.plan_id;

[User] Filter to only show appointments with status 'Completed' in the year 2024.

[Assistant]
SELECT a.appointment_id,
       a.appointment_time,
       d.last_name AS doctor_last_name,
       p.plan_name
FROM healthcare.appointments a
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
JOIN healthcare.patient_insurance pi ON a.patient_id = pi.patient_id AND pi.is_primary = true
JOIN healthcare.insurance_plans p ON pi.plan_id = p.plan_id
WHERE a.status = 'Completed'
  AND a.appointment_time >= '2024-01-01'
  AND a.appointment_time < '2025-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text PRIMARY KEY, 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, 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.json, created_at.timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
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] For each agency, how many services are currently inactive? Return the agency_id and the count of inactive services.

[Assistant]
SELECT
  agency_id,
  COUNT(*) AS inactive_service_count
FROM government_services.services
WHERE is_active = FALSE
GROUP BY 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.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )


[User] Show me each product_type along with the count of products for that type, but only include types where the average base_premium exceeds 500. Order the results by the product count in descending order.

[Assistant]
SELECT product_type,
       COUNT(*) AS product_count
FROM insurance.insurance_products
GROUP BY product_type
HAVING AVG(base_premium) > 500
ORDER BY product_count DESC;

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


[User] I need to list the top 5 ERC20 tokens by total supply, including symbol, contract_address, and name.

[Assistant]
SELECT tm.contract_address, tm.symbol, tm.name, CAST(tm.total_supply AS DECIMAL) AS total_supply
FROM token_metas tm
WHERE tm.is_erc20 = 1
ORDER BY CAST(tm.total_supply AS DECIMAL) DESC
LIMIT 5;

[User] Also include the latest USD price for each token from token_prices using the most recent timestamp per token.

[Assistant]
SELECT tm.contract_address, tm.symbol, tm.name, CAST(tm.total_supply AS DECIMAL) AS total_supply, tp.price
FROM token_metas tm
JOIN (
  SELECT address, price FROM token_prices tp1
  WHERE tp1.timestamp = (
    SELECT MAX(tp2.timestamp) FROM token_prices tp2 WHERE tp2.address = tp1.address
  )
) tp ON tp.address = tm.contract_address
WHERE tm.is_erc20 = 1
ORDER BY CAST(tm.total_supply AS DECIMAL) DESC
LIMIT 5;

[User] Filter results to only include tokens where the price is greater than 2.

[Assistant]
SELECT tm.contract_address, tm.symbol, tm.name, CAST(tm.total_supply AS DECIMAL) AS total_supply, tp.price
FROM token_metas tm
JOIN (
  SELECT address, price FROM token_prices tp1
  WHERE tp1.timestamp = (
    SELECT MAX(tp2.timestamp) FROM token_prices tp2 WHERE tp2.address = tp1.address
  )
) tp ON tp.address = tm.contract_address
WHERE tm.is_erc20 = 1
  AND tp.price > 2
ORDER BY CAST(tm.total_supply AS DECIMAL) DESC
LIMIT 5;

[User] Order the results by price descending and limit to 5.

[Assistant]
SELECT tm.contract_address, tm.symbol, tm.name, CAST(tm.total_supply AS DECIMAL) AS total_supply, tp.price
FROM token_metas tm
JOIN (
  SELECT address, price FROM token_prices tp1
  WHERE tp1.timestamp = (
    SELECT MAX(tp2.timestamp) FROM token_prices tp2 WHERE tp2.address = tp1.address
  )
) tp ON tp.address = tm.contract_address
WHERE tm.is_erc20 = 1
  AND tp.price > 2
ORDER BY tp.price DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid.text, blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_balances (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar NOT NULL, -- Token tick
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


[User] Show the total number of customers in each state.

[Assistant]
SELECT
  state,
  COUNT(customer_id)
FROM insurance.customers
GROUP BY
  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.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.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )


[User] What are the environmental impact assessments for the production of the Airbus A350 model?

[Assistant] I'm sorry, but I don't have access to data regarding the environmental impact assessments for the production of specific aircraft models like the Airbus A350. My information is limited to the technical specifications and basic details stored in the database, such as model name, manufacturer, and capacity. If you have a question related to the available data, I'd be happy to assist.

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 text PRIMARY KEY, model_name text, manufacturer text, passenger_capacity int, max_range_km int, engine_type text, wingspan_m numeric, status text, first_flight_date date )


[User] What are the safety ratings or crash statistics for the Boeing 787 Dreamliner?

[Assistant] I'm sorry, but I don't have access to safety ratings or crash statistics for specific aircraft models like the Boeing 787 Dreamliner. My data is limited to the information in the aircraft_models table, which includes details such as model name, manufacturer, passenger capacity, and technical specifications. For safety-related information, I recommend consulting official aviation authorities or safety reports.

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 text, model_name text, manufacturer text, passenger_capacity integer, max_range_km integer, engine_type text, wingspan_m numeric, status text, first_flight_date date )


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

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

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


[User] I want a list of each department's top 3 longest-tenured active employees, showing their full names, hire_date, and their manager’s full names.

[Assistant]
WITH ranked AS (
  SELECT
    e.department,
    e.employee_id,
    e.first_name || ' ' || e.last_name AS employee_full_name,
    e.hire_date,
    e.manager_id,
    ROW_NUMBER() OVER (PARTITION BY e.department ORDER BY e.hire_date ASC) AS rn
  FROM financial_services.employees e
  WHERE e.status = 'Active'
)
SELECT
  r.department,
  r.employee_full_name,
  r.hire_date,
  m.first_name || ' ' || m.last_name AS manager_full_name
FROM ranked r
LEFT JOIN financial_services.employees m ON r.manager_id = m.employee_id
WHERE r.rn <= 3;

[User] Actually, only include employees hired before '2018-01-01'.

[Assistant]
WITH ranked AS (
  SELECT
    e.department,
    e.employee_id,
    e.first_name || ' ' || e.last_name AS employee_full_name,
    e.hire_date,
    e.manager_id,
    ROW_NUMBER() OVER (PARTITION BY e.department ORDER BY e.hire_date ASC) AS rn
  FROM financial_services.employees e
  WHERE e.status = 'Active'
    AND e.hire_date < '2018-01-01'
)
SELECT
  r.department,
  r.employee_full_name,
  r.hire_date,
  m.first_name || ' ' || m.last_name AS manager_full_name
FROM ranked r
LEFT JOIN financial_services.employees m ON r.manager_id = m.employee_id
WHERE r.rn <= 3;

[User] Also, only consider departments that have at least 5 active employees in total before applying the top 3 filter.

[Assistant]
WITH dept_counts AS (
  SELECT department
  FROM financial_services.employees
  WHERE status = 'Active'
  GROUP BY department
  HAVING COUNT(*) >= 5
),
ranked AS (
  SELECT
    e.department,
    e.employee_id,
    e.first_name || ' ' || e.last_name AS employee_full_name,
    e.hire_date,
    e.manager_id,
    ROW_NUMBER() OVER (PARTITION BY e.department ORDER BY e.hire_date ASC) AS rn
  FROM financial_services.employees e
  JOIN dept_counts d ON e.department = d.department
  WHERE e.status = 'Active'
    AND e.hire_date < '2018-01-01'
)
SELECT
  r.department,
  r.employee_full_name,
  r.hire_date,
  m.first_name || ' ' || m.last_name AS manager_full_name
FROM ranked r
LEFT JOIN financial_services.employees m ON r.manager_id = m.employee_id
WHERE r.rn <= 3;

[User] Finally, sort the result by department ascending and hire_date ascending.

[Assistant]
WITH dept_counts AS (
  SELECT department
  FROM financial_services.employees
  WHERE status = 'Active'
  GROUP BY department
  HAVING COUNT(*) >= 5
),
ranked AS (
  SELECT
    e.department,
    e.employee_id,
    e.first_name || ' ' || e.last_name AS employee_full_name,
    e.hire_date,
    e.manager_id,
    ROW_NUMBER() OVER (PARTITION BY e.department ORDER BY e.hire_date ASC) AS rn
  FROM financial_services.employees e
  JOIN dept_counts d ON e.department = d.department
  WHERE e.status = 'Active'
    AND e.hire_date < '2018-01-01'
)
SELECT
  r.department,
  r.employee_full_name,
  r.hire_date,
  m.first_name || ' ' || m.last_name AS manager_full_name
FROM ranked r
LEFT JOIN financial_services.employees m ON r.manager_id = m.employee_id
WHERE r.rn <= 3
ORDER BY r.department ASC, r.hire_date ASC;

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


[User] List each patient and the number of different insurance plans they have had. Include patient_id and plan_count.

[Assistant]
SELECT patient_id, COUNT(DISTINCT plan_id) AS plan_count
FROM healthcare.patient_insurance
GROUP BY patient_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 healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.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] For each event recorded, list its ID, name, and the status and value of the transaction in which it occurred.

[Assistant] SELECT E.event_id, E.event_name, E.transaction_id, T.status, T.value FROM web3.events AS E JOIN web3.transactions AS T ON E.transaction_id = T.transaction_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.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] How many documents are there for each document_type? Show document_type and count ordered by the count in descending order.

[Assistant]
SELECT document_type,
       COUNT(*) AS count
FROM legal_services.documents
GROUP BY document_type
ORDER BY count DESC;

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


[User] List the name and symbol for all assets that do not have a corresponding entry with the key 'website' in the metadata table.

[Assistant] SELECT T1.name , T1.symbol FROM trading_platform.assets AS T1 LEFT JOIN trading_platform.metadata AS T2 ON T1.asset_id  =  T2.asset_id AND T2.key  =  'website' WHERE T2.metadata_id IS NULL

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)


[User] Find the names of service locations where services categorized as 'Licensing' have had appointments scheduled.

[Assistant] SELECT DISTINCT T1.location_name FROM service_locations AS T1 JOIN appointments AS T2 ON T1.location_id = T2.location_id JOIN services AS T3 ON T2.service_id = T3.service_id WHERE T3.category = 'Licensing';

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.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.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
CREATE TABLE government_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)


[User] Show me the top 5 addresses with the highest balances, along with their public keys.

[Assistant] SELECT address_id, public_key, balance FROM blockchain.addresses ORDER BY balance DESC LIMIT 5;

[User] Now, join this with another query to show the difference between each address's balance and the average balance of all addresses.

[Assistant] SELECT a.address_id, a.public_key, a.balance, (a.balance - (SELECT AVG(balance) FROM blockchain.addresses)) as balance_diff FROM blockchain.addresses a ORDER BY a.balance DESC LIMIT 5;

[User] Can you modify this to show the percentage difference instead of absolute difference?

[Assistant] SELECT a.address_id, a.public_key, a.balance, ((a.balance - (SELECT AVG(balance) FROM blockchain.addresses))/(SELECT AVG(balance) FROM blockchain.addresses)*100 as balance_pct_diff FROM blockchain.addresses a ORDER BY a.balance DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.addresses ( address_id.text, public_key.text, balance.numeric )


[User] List all customers who have two policies with overlapping coverage periods and show both policy numbers along with the overlap start and end dates.

[Assistant] SELECT p1.customer_id, p1.policy_number AS policy_number1, p2.policy_number AS policy_number2, 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 WHERE p1.start_date <= p2.end_date AND p2.start_date <= p1.end_date;

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

[Assistant] SELECT p1.customer_id, p1.policy_number AS policy_number1, p2.policy_number AS policy_number2, 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 WHERE p1.status = 'active' AND p2.status = 'active' AND p1.start_date <= p2.end_date AND p2.start_date <= p1.end_date;

[User] Also include the number of days of overlap as overlap_days.

[Assistant] SELECT p1.customer_id, p1.policy_number AS policy_number1, p2.policy_number AS policy_number2, GREATEST(p1.start_date, p2.start_date) AS overlap_start, LEAST(p1.end_date, p2.end_date) AS overlap_end, (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date)) AS overlap_days FROM insurance.policies p1 JOIN insurance.policies p2 ON p1.customer_id = p2.customer_id AND p1.policy_id < p2.policy_id WHERE p1.status = 'active' AND p2.status = 'active' AND p1.start_date <= p2.end_date AND p2.start_date <= p1.end_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 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 )