System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )

[User] For each asset, show the total quantity ordered with order status 'completed'.

[Assistant] SELECT asset_id, SUM(quantity) AS total_completed_quantity FROM trading_platform.orders WHERE status = 'completed' GROUP BY asset_id;

[User] Add the count of completed orders for each asset as well.

[Assistant] SELECT asset_id, COUNT(*) AS completed_order_count, SUM(quantity) AS total_completed_quantity FROM trading_platform.orders WHERE status = 'completed' GROUP BY asset_id;

[User] Actually, can you include only those assets that have associated metadata with the key 'category'?

[Assistant] SELECT o.asset_id, COUNT(*) AS completed_order_count, SUM(o.quantity) AS total_completed_quantity FROM trading_platform.orders o INNER JOIN trading_platform.metadata m ON o.asset_id = m.asset_id AND m.key = 'category' WHERE o.status = 'completed' GROUP BY o.asset_id;

[User] Could you also provide the value of the 'category' metadata in the result for each asset?

[Assistant] SELECT o.asset_id, m.value AS category, COUNT(*) AS completed_order_count, SUM(o.quantity) AS total_completed_quantity FROM trading_platform.orders o INNER JOIN trading_platform.metadata m ON o.asset_id = m.asset_id AND m.key = 'category' WHERE o.status = 'completed' GROUP BY o.asset_id, m.value;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )

[User] Show me the total premium amount paid by each customer, grouped by customer_id and payment_method.

[Assistant]
SELECT customer_id, payment_method, SUM(amount_paid) AS total_paid
FROM insurance.premium_payments
GROUP BY customer_id, payment_method;

[User] Can you also include the count of payments each customer made for each payment method?

[Assistant]
SELECT customer_id, payment_method, SUM(amount_paid) AS total_paid, COUNT(payment_id) AS payment_count
FROM insurance.premium_payments
GROUP BY customer_id, payment_method;

[User] Actually, only show the results for payment methods where the total amount paid exceeds 5000.

[Assistant]
SELECT customer_id, payment_method, SUM(amount_paid) AS total_paid, COUNT(payment_id) AS payment_count
FROM insurance.premium_payments
GROUP BY customer_id, payment_method
HAVING SUM(amount_paid) > 5000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] Retrieve the daily total fare collected for bookings with status 'Completed' in March 2024. Display the booking_date and total_fare.

[Assistant]
SELECT
  DATE(booking_time) AS booking_date,
  SUM(fare) AS total_fare
FROM transportation.bookings
WHERE status = 'Completed'
  AND booking_time >= '2024-03-01'
  AND booking_time <  '2024-04-01'
GROUP BY DATE(booking_time);

[User] Now include only days where the total_fare exceeds 1000.

[Assistant]
SELECT
  DATE(booking_time) AS booking_date,
  SUM(fare) AS total_fare
FROM transportation.bookings
WHERE status = 'Completed'
  AND booking_time >= '2024-03-01'
  AND booking_time <  '2024-04-01'
GROUP BY DATE(booking_time)
HAVING SUM(fare) > 1000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )

[User] Can you list the number of citizens registered each month in 2024? Please show the month and the citizen count.

[Assistant] SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;

[User] Now, can you also show the number of verified citizens for each month?

[Assistant] SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;

[User] I see some months with zero verified citizens, but they still show up. Can you exclude months with zero verified citizens from the result?

[Assistant] SELECT registration_month, citizen_count, verified_citizen_count FROM (SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month) sub WHERE verified_citizen_count > 0 ORDER BY registration_month;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )

[User] Find all pairs of drivers who were hired on the same date. For each pair, show the first_name and last_name of both drivers as driver1_first, driver1_last, driver2_first, driver2_last, and their shared hire_date.

[Assistant]
SELECT d1.first_name AS driver1_first,
       d1.last_name  AS driver1_last,
       d2.first_name AS driver2_first,
       d2.last_name  AS driver2_last,
       d1.hire_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d1.hire_date = d2.hire_date
  AND d1.driver_id < d2.driver_id;

[User] Now refine the list to only include pairs where both drivers have status 'Active' and order the results by hire_date DESC.

[Assistant]
SELECT d1.first_name AS driver1_first,
       d1.last_name  AS driver1_last,
       d2.first_name AS driver2_first,
       d2.last_name  AS driver2_last,
       d1.hire_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d1.hire_date = d2.hire_date
  AND d1.driver_id < d2.driver_id
WHERE d1.status = 'Active'
  AND d2.status = 'Active'
ORDER BY d1.hire_date DESC;


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

[User] List consecutive fueling events for each vehicle where the refill quantity increased compared to the previous event. Include vehicle_id, previous timestamp and quantity, current timestamp and quantity.

[Assistant]
SELECT
  prev.vehicle_id,
  prev.log_timestamp AS previous_time,
  prev.quantity AS previous_quantity,
  curr.log_timestamp AS current_time,
  curr.quantity AS current_quantity
FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY log_timestamp) AS rn
  FROM transportation.fuel_logs
) prev
JOIN (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY log_timestamp) AS rn
  FROM transportation.fuel_logs
) curr
  ON prev.vehicle_id = curr.vehicle_id
  AND curr.rn = prev.rn + 1
WHERE curr.quantity > prev.quantity;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )

[User] Show me all active staff members who are managers (position contains 'Manager'), along with their hire dates and the count of staff they supervise, ordered by supervised staff count in descending order.

[Assistant] SELECT s1.staff_id, s1.first_name, s1.last_name, s1.hire_date, COUNT(s2.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s1 LEFT JOIN hospitality_technology.staff s2 ON s1.staff_id = s2.manager_id WHERE s1.position LIKE '%Manager%' AND s1.is_active = true GROUP BY s1.staff_id, s1.first_name, s1.last_name, s1.hire_date ORDER BY supervised_staff_count DESC;

[User] Now, include only managers who supervise at least 3 staff members and show their email addresses as well.

[Assistant] SELECT s1.staff_id, s1.first_name, s1.last_name, s1.work_email, s1.hire_date, COUNT(s2.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s1 LEFT JOIN hospitality_technology.staff s2 ON s1.staff_id = s2.manager_id WHERE s1.position LIKE '%Manager%' AND s1.is_active = true GROUP BY s1.staff_id, s1.first_name, s1.last_name, s1.work_email, s1.hire_date HAVING COUNT(s2.staff_id) >= 3 ORDER BY supervised_staff_count DESC;

[User] The query is missing their property information. Can you include the property name they work at?

[Assistant] SELECT s1.staff_id, s1.first_name, s1.last_name, s1.work_email, s1.hire_date, p.property_name, COUNT(s2.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s1 LEFT JOIN hospitality_technology.staff s2 ON s1.staff_id = s2.manager_id JOIN hospitality_technology.properties p ON s1.property_id = p.property_id WHERE s1.position LIKE '%Manager%' AND s1.is_active = true GROUP BY s1.staff_id, s1.first_name, s1.last_name, s1.work_email, s1.hire_date, p.property_name HAVING COUNT(s2.staff_id) >= 3 ORDER BY supervised_staff_count DESC;

[User] Actually, I need to see only managers from properties in California, and order by hire date from newest to oldest.

[Assistant] SELECT s1.staff_id, s1.first_name, s1.last_name, s1.work_email, s1.hire_date, p.property_name, COUNT(s2.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s1 LEFT JOIN hospitality_technology.staff s2 ON s1.staff_id = s2.manager_id JOIN hospitality_technology.properties p ON s1.property_id = p.property_id WHERE s1.position LIKE '%Manager%' AND s1.is_active = true AND p.state_province = 'California' GROUP BY s1.staff_id, s1.first_name, s1.last_name, s1.work_email, s1.hire_date, p.property_name HAVING COUNT(s2.staff_id) >= 3 ORDER BY s1.hire_date DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)

[User] Which users have sent messages in multiple different conversations? Show the user ID and the count of unique conversations.

[Assistant] SELECT sender_user_id, COUNT(DISTINCT conversation_id) AS unique_conversation_count FROM social_media.messages GROUP BY sender_user_id HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Okay, now filter this list to only show users who have sent messages in more than 5 unique conversations.

[Assistant] SELECT sender_user_id, COUNT(DISTINCT conversation_id) AS unique_conversation_count FROM social_media.messages GROUP BY sender_user_id HAVING COUNT(DISTINCT conversation_id) > 5;

[User] Additionally, show the timestamp of the first message sent by each of these users, and order the results by the unique conversation count descending.

[Assistant] SELECT sender_user_id, COUNT(DISTINCT conversation_id) AS unique_conversation_count, MIN(sent_at) AS first_message_time FROM social_media.messages GROUP BY sender_user_id HAVING COUNT(DISTINCT conversation_id) > 5 ORDER BY unique_conversation_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)

[User] Get me the total number of vehicles for each fuel_type.

[Assistant]
SELECT fuel_type,
       COUNT(*) AS total_vehicles
FROM transportation.vehicles
GROUP BY fuel_type;

[User] Only show fuel types where total_vehicles is at least 5.

[Assistant]
SELECT fuel_type,
       COUNT(*) AS total_vehicles
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 5;

[User] Also include the average capacity for each of those fuel types.

[Assistant]
SELECT fuel_type,
       COUNT(*) AS total_vehicles,
       AVG(capacity) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 5;

[User] Sort the results by avg_capacity in descending order.

[Assistant]
SELECT fuel_type,
       COUNT(*) AS total_vehicles,
       AVG(capacity) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 5
ORDER BY avg_capacity DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )

[User] Find all agents with their managers where the agent's commission rate is above 0.10.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.agent_id AS manager_id,
       m.first_name || ' ' || m.last_name AS manager_name
FROM insurance.agents a
JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.commission_rate > 0.1;

[User] Exclude any pairs where the manager is not currently active.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.agent_id AS manager_id,
       m.first_name || ' ' || m.last_name AS manager_name
FROM insurance.agents a
JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.commission_rate > 0.1
  AND m.status = 'active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.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 all documents of type 'Pleading' uploaded between '2023-01-01' and '2023-12-31', including their name, case ID, and upload timestamp.

[Assistant] SELECT document_name, case_id, upload_timestamp FROM legal_services.documents WHERE document_type = 'Pleading' AND upload_timestamp BETWEEN '2023-01-01' AND '2023-12-31';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )

[User] I need the average close_price per sector for the last month.

[Assistant]
SELECT s.sector, AVG(m.close_price) AS avg_close_price
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
GROUP BY s.sector;

[User] Can you also include the maximum volume per sector?

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
GROUP BY s.sector;

[User] Now I only want data from source 'Reuters'.

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
  AND m.source = 'Reuters'
GROUP BY s.sector;

[User] Finally, only include sectors with total volume over 1000000 and order by avg_close_price descending.

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
  AND m.source = 'Reuters'
GROUP BY s.sector
HAVING SUM(m.volume) > 1000000
ORDER BY avg_close_price DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )

[User] List all likes made by user 'U100' on posts, including the like_id and the post_id.

[Assistant] SELECT like_id, post_id FROM social_media.likes WHERE user_id = 'U100' AND post_id IS NOT NULL;

[User] Now, only include those likes created after '2024-01-01'.

[Assistant] SELECT like_id, post_id FROM social_media.likes WHERE user_id = 'U100' AND post_id IS NOT NULL AND created_at > '2024-01-01';

[User] Instead of listing them, count how many such likes user 'U100' made after '2024-01-01'.

[Assistant] SELECT COUNT(*) FROM social_media.likes WHERE user_id = 'U100' AND post_id IS NOT NULL AND created_at > '2024-01-01';

[User] How many likes did user 'U100' make on comments after '2024-01-01'?

[Assistant] SELECT COUNT(*) FROM social_media.likes WHERE user_id = 'U100' AND comment_id IS NOT NULL AND created_at > '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_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 token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_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_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche (
    block_number bigint 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 all SUI coins that are marked as 'exists' in both sui_coins and sui_coins_metadata, displaying their coin_type, symbol, name, and balance.

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

[User] Can you add the owner address for each coin and include only those with a balance greater than 1000000?

[Assistant] SELECT sc.coin_type, scm.symbol, scm.name, sc.owner, sc.balance FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE sc.status = 'exists' AND scm.status = 'exists' AND CAST(sc.balance AS decimal) > 1000000;

[User] Please also show the coin description, and sort by balance descending.

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

[User] Now limit the result to the top 10 coins.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )

[User] List the usernames and emails of all users who have received notifications of type 'follow', along with the sender's user ID and the notification timestamp.

[Assistant]
SELECT u.username, u.email, n.sender_user_id, n.created_at
FROM social_media.notifications n
JOIN social_media.users u ON n.recipient_user_id = u.user_id
WHERE n.notification_type = 'follow';

[User] Please only include users whose profile is verified.

[Assistant]
SELECT u.username, u.email, n.sender_user_id, n.created_at
FROM social_media.notifications n
JOIN social_media.users u ON n.recipient_user_id = u.user_id
WHERE n.notification_type = 'follow' AND u.is_verified = true;

[User] Instead of sender_user_id, can you show the sender's username?

[Assistant]
SELECT u.username AS recipient_username, u.email, sender.username AS sender_username, n.created_at
FROM social_media.notifications n
JOIN social_media.users u ON n.recipient_user_id = u.user_id
LEFT JOIN social_media.users sender ON n.sender_user_id = sender.user_id
WHERE n.notification_type = 'follow' AND u.is_verified = true;

[User] Show only notifications from the past 14 days.

[Assistant]
SELECT u.username AS recipient_username, u.email, sender.username AS sender_username, n.created_at
FROM social_media.notifications n
JOIN social_media.users u ON n.recipient_user_id = u.user_id
LEFT JOIN social_media.users sender ON n.sender_user_id = sender.user_id
WHERE n.notification_type = 'follow' AND u.is_verified = true
  AND n.created_at >= NOW() - INTERVAL '14 days';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )

[User] What is the total session duration and total score across all sessions for each server status?

[Assistant]
SELECT
  s.status,
  SUM(gs.duration_seconds) AS total_duration_seconds,
  SUM(gs.score) AS total_score
FROM gaming_technology.game_sessions AS gs
JOIN gaming_technology.servers AS s
  ON gs.server_id = s.server_id
GROUP BY
  s.status;

[User] Only include statuses that have a total session duration greater than 1000000 seconds and handle potential null scores by treating them as 0.

[Assistant]
SELECT
  s.status,
  SUM(gs.duration_seconds) AS total_duration_seconds,
  SUM(COALESCE(gs.score, 0)) AS total_score
FROM gaming_technology.game_sessions AS gs
JOIN gaming_technology.servers AS s
  ON gs.server_id = s.server_id
GROUP BY
  s.status
HAVING
  SUM(gs.duration_seconds) > 1000000;

[User] Order the results by total session duration in descending order.

[Assistant]
SELECT
  s.status,
  SUM(gs.duration_seconds) AS total_duration_seconds,
  SUM(COALESCE(gs.score, 0)) AS total_score
FROM gaming_technology.game_sessions AS gs
JOIN gaming_technology.servers AS s
  ON gs.server_id = s.server_id
GROUP BY
  s.status
HAVING
  SUM(gs.duration_seconds) > 1000000
ORDER BY
  total_duration_seconds DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )

[User] List all citizens who submitted an application within 24 hours of registering. Show the application_id, citizen's full name, registration_date, and submitted_at timestamp.

[Assistant]
SELECT
a.application_id,
(c.first_name || ' ' || c.last_name) AS full_name,
c.registration_date,
a.submitted_at
FROM government_services.applications a
JOIN government_services.citizens c
  ON a.citizen_id = c.citizen_id
WHERE a.submitted_at <= c.registration_date + INTERVAL '24 hours';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)

[User] How many rooms are currently marked as 'OutOfOrder'?

[Assistant] SELECT count(*) FROM hospitality_technology.rooms WHERE status = 'OutOfOrder';

[User] Also, show the count for each property.

[Assistant] SELECT T2.property_name, count(T1.room_id) FROM hospitality_technology.rooms AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.status = 'OutOfOrder' GROUP BY T2.property_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
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, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] For each doctor, how many appointments did they have with female patients in the year 2024? Show doctor ID, first name, last name, and the count.

[Assistant] SELECT d.doctor_id, d.first_name, d.last_name, COUNT(a.appointment_id) AS female_patient_appointment_count FROM healthcare.doctors d JOIN healthcare.appointments a ON d.doctor_id = a.doctor_id JOIN healthcare.patients p ON a.patient_id = p.patient_id WHERE p.gender = 'Female' AND EXTRACT(YEAR FROM a.appointment_time) = 2024 GROUP BY d.doctor_id, d.first_name, d.last_name;

[User] Now, only include doctors specializing in 'Pediatrics'.

[Assistant] SELECT d.doctor_id, d.first_name, d.last_name, COUNT(a.appointment_id) AS female_patient_appointment_count FROM healthcare.doctors d JOIN healthcare.appointments a ON d.doctor_id = a.doctor_id JOIN healthcare.patients p ON a.patient_id = p.patient_id WHERE d.specialty = 'Pediatrics' AND p.gender = 'Female' AND EXTRACT(YEAR FROM a.appointment_time) = 2024 GROUP BY d.doctor_id, d.first_name, d.last_name;

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

[Assistant] SELECT d.doctor_id, d.first_name, d.last_name, COUNT(a.appointment_id) AS female_patient_appointment_count FROM healthcare.doctors d JOIN healthcare.appointments a ON d.doctor_id = a.doctor_id JOIN healthcare.patients p ON a.patient_id = p.patient_id WHERE d.specialty = 'Pediatrics' AND p.gender = 'Female' AND EXTRACT(YEAR FROM a.appointment_time) = 2024 GROUP BY d.doctor_id, d.first_name, d.last_name ORDER BY female_patient_appointment_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id.text, first_name.text, last_name.text, company_name.text, email.text, phone.text, address.text, date_registered.timestamp, status.text )
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
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 )
CREATE TABLE legal_services.time_entries ( entry_id.text, case_id.text, lawyer_id.text, date_worked.date, hours_spent.numeric, billing_rate.numeric, description.text, is_billable.boolean, is_billed.boolean, invoice_id.text, created_at.timestamp )
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 )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )

[User] Show the invoice number, issue date, total amount, and the client's full name for all invoices, including only those invoices that have not been paid fully.

[Assistant] SELECT i.invoice_number, i.issue_date, i.total_amount, c.first_name || ' ' || c.last_name AS client_full_name FROM legal_services.invoices i JOIN legal_services.clients c ON i.client_id = c.client_id WHERE i.amount_paid < i.total_amount;


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

[User] List the claim ID, policy ID, reported date, and settlement date for claims that have been processed by a claim handler.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL;

[User] Actually, only show claims where the settlement date is not null as well.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL;

[User] Now, filter to only include claims settled after January 1, 2024.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL
  AND settlement_date > '2024-01-01';

[User] Also, add a column showing the number of days between the reported date and the settlement date, and sort results by that column in descending order.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date,
       (settlement_date - reported_date::date) AS days_to_settle
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL
  AND settlement_date > '2024-01-01'
ORDER BY days_to_settle DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] I need to calculate the total premium and average deductible for each agent for policies issued this year.

[Assistant]
SELECT agent_id,
       SUM(premium_amount)    AS total_premium,
       AVG(deductible)        AS average_deductible
FROM insurance.policies
WHERE EXTRACT(YEAR FROM issued_at) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY agent_id;

[User] Only include agents who have sold at least 10 policies.

[Assistant]
SELECT agent_id,
       SUM(premium_amount)    AS total_premium,
       AVG(deductible)        AS average_deductible,
       COUNT(policy_id)       AS policy_count
FROM insurance.policies
WHERE EXTRACT(YEAR FROM issued_at) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY agent_id
HAVING COUNT(policy_id) >= 10;

[User] Sort the results by total_premium in descending order.

[Assistant]
SELECT agent_id,
       SUM(premium_amount)    AS total_premium,
       AVG(deductible)        AS average_deductible,
       COUNT(policy_id)       AS policy_count
FROM insurance.policies
WHERE EXTRACT(YEAR FROM issued_at) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY agent_id
HAVING COUNT(policy_id) >= 10
ORDER BY total_premium DESC;

[User] Include only active policies in the calculations.

[Assistant]
SELECT agent_id,
       SUM(premium_amount)    AS total_premium,
       AVG(deductible)        AS average_deductible,
       COUNT(policy_id)       AS policy_count
FROM insurance.policies
WHERE EXTRACT(YEAR FROM issued_at) = EXTRACT(YEAR FROM CURRENT_DATE)
  AND status = 'Active'
GROUP BY agent_id
HAVING COUNT(policy_id) >= 10
ORDER BY total_premium DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )

[User] How many trips used more than 500 units of fuel, and what are their trip IDs and scheduled departure times?

[Assistant]
SELECT t.trip_id, t.scheduled_departure, SUM(f.quantity) AS total_fuel
FROM transportation.trips t
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY t.trip_id, t.scheduled_departure
HAVING SUM(f.quantity) > 500;

[User] Change the query to show the route number for these trips as well.

[Assistant]
SELECT t.trip_id, t.scheduled_departure, r.route_number, SUM(f.quantity) AS total_fuel
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY t.trip_id, t.scheduled_departure, r.route_number
HAVING SUM(f.quantity) > 500;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies (
    agency_id character varying(64) NOT NULL, -- unique identifier for the agency
    agency_name character varying(255) NOT NULL, -- full name of the government agency
    jurisdiction_level character varying(50) NOT NULL, -- e.g., Federal, State, County, City
    primary_contact_email character varying(128),
    main_phone_number character varying(32),
    website_url character varying(255),
    established_date date,
    parent_agency_id character varying(64), -- FK to self for hierarchical structure
    PRIMARY KEY (agency_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.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
CREATE TABLE government_services.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.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
CREATE TABLE government_services.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    application_id character varying(64), -- FK to applications table (optional)
    message_subject character varying(255),
    message_body text NOT NULL,
    channel character varying(30) NOT NULL, -- e.g., Email, SMS, Portal Message, Mail
    sent_at timestamp NOT NULL,
    status character varying(30) NOT NULL, -- e.g., Queued, Sent, Delivered, Failed, Read
    related_entity_type character varying(50), -- e.g., Application, Appointment, Document Request
    related_entity_id character varying(64), -- ID of the related entity
    PRIMARY KEY (notification_id)
)

[User] Provide a breakdown of the total number of applications submitted for each service category.

[Assistant] SELECT T2.category, count(T1.application_id) FROM applications AS T1 JOIN services AS T2 ON T1.service_id = T2.service_id GROUP BY T2.category

[User] Could you filter that list to only include categories with more than 50 applications?

[Assistant] SELECT T2.category, count(T1.application_id) FROM applications AS T1 JOIN services AS T2 ON T1.service_id = T2.service_id GROUP BY T2.category HAVING count(T1.application_id) > 50


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE 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_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
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 token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )

[User] List all NFTs on the blockchain with contract type 'ERC1155' and show their contract address, token id, and total number held by all wallets.

[Assistant]
SELECT contract_address, token_id, SUM(CAST(amount AS INTEGER)) AS total_held
FROM nft_holders
WHERE contract_type = 'ERC1155'
GROUP BY contract_address, token_id;

[User] Include also the number of unique holders for each NFT.

[Assistant]
SELECT contract_address, token_id, SUM(CAST(amount AS INTEGER)) AS total_held, COUNT(DISTINCT wallet_address) AS unique_holders
FROM nft_holders
WHERE contract_type = 'ERC1155'
GROUP BY contract_address, token_id;

[User] Now, show only NFTs with more than 10 unique holders.

[Assistant]
SELECT contract_address, token_id, SUM(CAST(amount AS INTEGER)) AS total_held, COUNT(DISTINCT wallet_address) AS unique_holders
FROM nft_holders
WHERE contract_type = 'ERC1155'
GROUP BY contract_address, token_id
HAVING COUNT(DISTINCT wallet_address) > 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] What is the total net_flow and average realized_ratio for tokens on the Polygon chain?

[Assistant]
SELECT SUM(net_flow) AS total_net_flow, AVG(realized_ratio) AS avg_realized_ratio
FROM smart_money_token_performance
WHERE chain = 'Polygon';

[User] Now, show me the same metrics for the Arbitrum chain.

[Assistant]
SELECT SUM(net_flow) AS total_net_flow, AVG(realized_ratio) AS avg_realized_ratio
FROM smart_money_token_performance
WHERE chain = 'Arbitrum';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)

[User] List usernames and bio information for users who have set a non-empty bio in their profile.

[Assistant]
SELECT username, bio
FROM social_media.users
WHERE bio IS NOT NULL AND TRIM(bio) <> '';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text PRIMARY KEY, previous_block_id text, timestamp timestamp, nonce int, merkle_root text, difficulty int )
CREATE TABLE blockchain.transactions ( transaction_id text PRIMARY KEY, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.addresses ( address_id text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.nodes ( node_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE blockchain.users ( user_id text PRIMARY KEY, username text, email text, password_hash text )
CREATE TABLE blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )

[User] List all smart contracts created by addresses that have a balance greater than 1000.

[Assistant] SELECT sc.* FROM blockchain.smart_contracts sc JOIN blockchain.addresses a ON sc.creator_address = a.address_id WHERE a.balance > 1000;

[User] Now include the username of the user who created these contracts if the creator address is associated with a user.

[Assistant] SELECT sc.*, u.username FROM blockchain.smart_contracts sc JOIN blockchain.addresses a ON sc.creator_address = a.address_id LEFT JOIN blockchain.users u ON a.address_id = u.user_id WHERE a.balance > 1000;

[User] This query isn't working correctly because the join between addresses and users is wrong. The user_id in users table is not the same as address_id.

[Assistant] SELECT sc.*, u.username FROM blockchain.smart_contracts sc JOIN blockchain.addresses a ON sc.creator_address = a.address_id LEFT JOIN blockchain.users u ON a.public_key = u.email WHERE a.balance > 1000;

[User] That still doesn't seem right. Let's just show the contracts and their creators' balances without trying to join with users.

[Assistant] SELECT sc.contract_id, sc.creator_address, a.balance FROM blockchain.smart_contracts sc JOIN blockchain.addresses a ON sc.creator_address = a.address_id WHERE a.balance > 1000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )

[User] List the first and last names of clients whose client_id matches a lawyer_id in the time_entries table, along with the corresponding entry_id.

[Assistant] SELECT c.first_name, c.last_name, te.entry_id FROM legal_services.clients c JOIN legal_services.time_entries te ON c.client_id = te.lawyer_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] List each username with how many users they follow and how many users follow them.

[Assistant]
SELECT u.username,
       COALESCE(following.following_count, 0) AS following_count,
       COALESCE(followers.followers_count, 0) AS followers_count
FROM social_media.users u
LEFT JOIN (
  SELECT follower_user_id, COUNT(*) AS following_count
  FROM social_media.follows
  GROUP BY follower_user_id
) AS following
  ON u.user_id = following.follower_user_id
LEFT JOIN (
  SELECT following_user_id, COUNT(*) AS followers_count
  FROM social_media.follows
  GROUP BY following_user_id
) AS followers
  ON u.user_id = followers.following_user_id;

[User] Also include only those users who follow more people than follow them.

[Assistant]
SELECT u.username,
       COALESCE(following.following_count, 0) AS following_count,
       COALESCE(followers.followers_count, 0) AS followers_count
FROM social_media.users u
LEFT JOIN (
  SELECT follower_user_id, COUNT(*) AS following_count
  FROM social_media.follows
  GROUP BY follower_user_id
) AS following
  ON u.user_id = following.follower_user_id
LEFT JOIN (
  SELECT following_user_id, COUNT(*) AS followers_count
  FROM social_media.follows
  GROUP BY following_user_id
) AS followers
  ON u.user_id = followers.following_user_id
WHERE COALESCE(following.following_count, 0) > COALESCE(followers.followers_count, 0);

[User] Sort the results by the difference between following_count and followers_count in descending order, and alias this difference as difference_count.

[Assistant]
SELECT u.username,
       COALESCE(following.following_count, 0) AS following_count,
       COALESCE(followers.followers_count, 0) AS followers_count,
       (COALESCE(following.following_count, 0) - COALESCE(followers.followers_count, 0)) AS difference_count
FROM social_media.users u
LEFT JOIN (
  SELECT follower_user_id, COUNT(*) AS following_count
  FROM social_media.follows
  GROUP BY follower_user_id
) AS following
  ON u.user_id = following.follower_user_id
LEFT JOIN (
  SELECT following_user_id, COUNT(*) AS followers_count
  FROM social_media.follows
  GROUP BY following_user_id
) AS followers
  ON u.user_id = followers.following_user_id
WHERE (COALESCE(following.following_count, 0) - COALESCE(followers.followers_count, 0)) > 0
ORDER BY difference_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] For each notification sent through the 'SMS' channel, list the notification ID, message subject, and the full name of the citizen who received it.

[Assistant]
SELECT n.notification_id, n.message_subject, c.first_name || ' ' || c.last_name AS full_name
FROM government_services.notifications n
JOIN government_services.citizens c ON n.citizen_id = c.citizen_id
WHERE n.channel = 'SMS';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )

[User] Show all DApps whose name starts with the letter 'C'.

[Assistant] SELECT * FROM trading_platform.dapps WHERE name ILIKE 'C%';

[User] Could you instead make it case-sensitive so only names that start with an uppercase 'C' are included?

[Assistant] SELECT * FROM trading_platform.dapps WHERE name LIKE 'C%';

[User] Actually, just show their names and descriptions.

[Assistant] SELECT name, description FROM trading_platform.dapps WHERE name LIKE 'C%';

[User] Add the URL in the result too, and order by name alphabetically.

[Assistant] SELECT name, description, url FROM trading_platform.dapps WHERE name LIKE 'C%' ORDER BY name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
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, 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.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )

[User] Show me the total number of trades and the total traded value for each customer, including their first and last names.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, COUNT(t.trade_id) AS trade_count, SUM(t.total_amount) AS total_traded_value
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.trades t ON a.account_id = t.account_id
GROUP BY c.customer_id, c.first_name, c.last_name;

[User] Actually, only include customers who have executed more than 5 trades.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, COUNT(t.trade_id) AS trade_count, SUM(t.total_amount) AS total_traded_value
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.trades t ON a.account_id = t.account_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(t.trade_id) > 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )

[User] Which projects raised funds in January 2022?

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-02-01';

[User] Please also show their introductions.

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date, introduction FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-02-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)

[User] List all tokens with a total supply greater than 1,000,000.

[Assistant]
SELECT token_id, token_name, token_symbol, contract_address, total_supply
FROM web3.tokens
WHERE total_supply > 1000000;

[User] Can you also include the decimals for each token in the result?

[Assistant]
SELECT token_id, token_name, token_symbol, contract_address, total_supply, decimals
FROM web3.tokens
WHERE total_supply > 1000000;


[User] Which citizens have submitted applications for services that belong to the 'Education' category? List the citizen's full name, the service name, and the application ID.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, s.service_name, a.application_id
FROM government_services.applications a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE s.category = 'Education';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )

[User] List all services provided by the property named 'Grand Plaza Hotel' and include their category and price.

[Assistant] SELECT T1.service_name, T1.category, T1.price FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T2.property_name = 'Grand Plaza Hotel';

[User] Only show available services from the 'Spa' department at 'Grand Plaza Hotel'.

[Assistant] SELECT T1.service_name, T1.category, T1.price FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T2.property_name = 'Grand Plaza Hotel' AND T1.is_available = TRUE AND T1.department = 'Spa';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.invoices ( invoice_id character varying(64) NOT NULL, invoice_number character varying(100) UNIQUE NOT NULL, client_id character varying(64) NOT NULL, case_id character varying(64), issue_date date NOT NULL, due_date date NOT NULL, total_amount numeric(12, 2) NOT NULL, amount_paid numeric(12, 2) DEFAULT 0.00, status character varying(50) NOT NULL, payment_date timestamp, notes text, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (invoice_id) )

[User] Which clients have had at least one case led by a lawyer who is a partner? Show the client name, the case name, and the name of the lead lawyer.

[Assistant]
SELECT cl.first_name || ' ' || cl.last_name AS client_name, ca.case_name, l.first_name || ' ' || l.last_name AS lead_lawyer_name
FROM legal_services.cases ca
JOIN legal_services.clients cl ON ca.client_id = cl.client_id
JOIN legal_services.lawyers l ON ca.lead_lawyer_id = l.lawyer_id
WHERE l.is_partner = TRUE;

[User] Actually, can you only show results for cases where the client's status is 'active'?

[Assistant]
SELECT cl.first_name || ' ' || cl.last_name AS client_name, ca.case_name, l.first_name || ' ' || l.last_name AS lead_lawyer_name
FROM legal_services.cases ca
JOIN legal_services.clients cl ON ca.client_id = cl.client_id
JOIN legal_services.lawyers l ON ca.lead_lawyer_id = l.lawyer_id
WHERE l.is_partner = TRUE AND cl.status = 'active';

[User] Add the case_number to the output and sort the results by the client's last name.

[Assistant]
SELECT cl.first_name || ' ' || cl.last_name AS client_name, ca.case_name, ca.case_number, l.first_name || ' ' || l.last_name AS lead_lawyer_name
FROM legal_services.cases ca
JOIN legal_services.clients cl ON ca.client_id = cl.client_id
JOIN legal_services.lawyers l ON ca.lead_lawyer_id = l.lawyer_id
WHERE l.is_partner = TRUE AND cl.status = 'active'
ORDER BY cl.last_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.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)
)
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] List the service_id, service_name, and agency_id for all active services that have an online application URL provided.

[Assistant]
SELECT service_id,
       service_name,
       agency_id
FROM government_services.services
WHERE is_active = TRUE
  AND online_application_url IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text, 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, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Show me policies that have at least one overdue premium payment, including policy_number, customer full name, agent_id, due_date, and days overdue.

[Assistant]
SELECT p.policy_number,
       c.first_name || ' ' || c.last_name AS customer_name,
       p.agent_id,
       pp.due_date,
       EXTRACT(day FROM CURRENT_DATE - pp.due_date) AS days_overdue
FROM insurance.policies p
JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id
JOIN insurance.customers c ON p.customer_id = c.customer_id
WHERE pp.status = 'overdue';

[User] Actually, only consider overdue payments by more than 7 days and only active policies.

[Assistant]
SELECT p.policy_number,
       c.first_name || ' ' || c.last_name AS customer_name,
       p.agent_id,
       pp.due_date,
       EXTRACT(day FROM CURRENT_DATE - pp.due_date) AS days_overdue
FROM insurance.policies p
JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id
JOIN insurance.customers c ON p.customer_id = c.customer_id
WHERE pp.status = 'overdue'
  AND p.status = 'active'
  AND EXTRACT(day FROM CURRENT_DATE - pp.due_date) > 7;

[User] Also include the payment_method and label the overdue days column as overdue_days.

[Assistant]
SELECT p.policy_number,
       c.first_name || ' ' || c.last_name AS customer_name,
       p.agent_id,
       pp.payment_method,
       pp.due_date,
       EXTRACT(day FROM CURRENT_DATE - pp.due_date) AS overdue_days
FROM insurance.policies p
JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id
JOIN insurance.customers c ON p.customer_id = c.customer_id
WHERE pp.status = 'overdue'
  AND p.status = 'active'
  AND EXTRACT(day FROM CURRENT_DATE - pp.due_date) > 7;