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.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )

[User] Get the total number of logs per user for July 2024.

[Assistant]
SELECT user_id,
       COUNT(*) AS log_count
FROM trading_platform.logs
WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
GROUP BY user_id;

[User] Only include users who have at least 20 logs in that period.

[Assistant]
SELECT user_id,
       COUNT(*) AS log_count
FROM trading_platform.logs
WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
GROUP BY user_id
HAVING COUNT(*) >= 20;

[User] Also include the earliest log date for each of those users.

[Assistant]
SELECT t.user_id,
       t.log_count,
       e.first_log
FROM (
    SELECT user_id,
           COUNT(*) AS log_count
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
    HAVING COUNT(*) >= 20
) t
JOIN (
    SELECT user_id,
           MIN(logged_at) AS first_log
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
) e ON t.user_id = e.user_id;

[User] Sort by log_count descending and limit to top 5 users.

[Assistant]
SELECT t.user_id,
       t.log_count,
       e.first_log
FROM (
    SELECT user_id,
           COUNT(*) AS log_count
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
    HAVING COUNT(*) >= 20
) t
JOIN (
    SELECT user_id,
           MIN(logged_at) AS first_log
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
) e ON t.user_id = e.user_id
ORDER BY t.log_count DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id.text, 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.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] What is the average fare for bookings with status 'Completed'?

[Assistant] SELECT AVG(fare) FROM transportation.bookings WHERE status = 'Completed';

[User] What about the average fare for 'Cancelled' bookings?

[Assistant] SELECT AVG(fare) FROM transportation.bookings WHERE status = 'Cancelled';


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.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )

[User] For each recipient address, count how many token transfers they have received.

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

[User] Only show addresses that have received more than 100 transfers.

[Assistant] SELECT to_address, COUNT(*) AS received_transfer_count FROM web3.token_transfers GROUP BY to_address HAVING COUNT(*) > 100;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
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
)

[User] Which users have commented on posts that include hashtags? Show their user IDs and the hashtag IDs.

[Assistant]
SELECT DISTINCT c.user_id, ph.hashtag_id
FROM social_media.comments c
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id;

[User] Can you also include the comment_id and the post_id in the result?

[Assistant]
SELECT DISTINCT c.comment_id, c.post_id, c.user_id, ph.hashtag_id
FROM social_media.comments c
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_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 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.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
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] Retrieve each vehicle's make and model along with the date and description of its latest maintenance service.

[Assistant]
SELECT v.vehicle_id,
       v.make,
       v.model,
       m.service_date,
       m.description
FROM transportation.vehicles v
JOIN (
  SELECT vehicle_id,
         MAX(service_date) AS max_date
  FROM transportation.maintenance_logs
  GROUP BY vehicle_id
) latest
  ON v.vehicle_id = latest.vehicle_id
JOIN transportation.maintenance_logs m
  ON m.vehicle_id = latest.vehicle_id
 AND m.service_date = latest.max_date;


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.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )

[User] Show me the usernames and emails of all users who have placed at least one 'buy' order for the asset named 'Bitcoin'.

[Assistant] SELECT DISTINCT T1.username, T1.email FROM trading_platform.users AS T1 JOIN trading_platform.orders AS T2 ON T1.user_id = T2.user_id JOIN trading_platform.assets AS T3 ON T2.asset_id = T3.asset_id WHERE T2.order_type = 'buy' AND T3.name = 'Bitcoin'

[User] From that list, only show the users whose KYC status is currently 'pending'.

[Assistant] SELECT DISTINCT T1.username, T1.email FROM trading_platform.users AS T1 JOIN trading_platform.orders AS T2 ON T1.user_id = T2.user_id JOIN trading_platform.assets AS T3 ON T2.asset_id = T3.asset_id JOIN trading_platform.kyc_audit AS T4 ON T1.user_id = T4.user_id WHERE T2.order_type = 'buy' AND T3.name = 'Bitcoin' AND T4.status = 'pending'


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.nodes ( node_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (node_id) )

[User] Retrieve all pairs of nodes where one node was last seen before '2023-06-01' and the other after '2023-06-01', and they share the same IP address.

[Assistant]
SELECT a.node_id AS node_before,
       b.node_id AS node_after,
       a.ip_address
FROM blockchain.nodes a
JOIN blockchain.nodes b
  ON a.ip_address = b.ip_address
WHERE a.last_seen < '2023-06-01'
  AND b.last_seen > '2023-06-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )

[User] How many inventory items are recorded in total?

[Assistant] SELECT COUNT(*) FROM player_inventory;

[User] Okay, now show me the total quantity of items for each specific item ID.

[Assistant] SELECT item_id, SUM(quantity) AS total_quantity FROM player_inventory GROUP BY item_id;

[User] Filter that list to only include items where the total quantity across all inventories is more than 1000.

[Assistant] SELECT item_id, SUM(quantity) AS total_quantity FROM player_inventory GROUP BY item_id HAVING SUM(quantity) > 1000;

[User] Order the results by the total quantity in descending order and limit to the top 10 items.

[Assistant] SELECT item_id, SUM(quantity) AS total_quantity FROM player_inventory GROUP BY item_id HAVING SUM(quantity) > 1000 ORDER BY total_quantity DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )

[User] List all guests from California who are loyalty members, including their email and phone number.

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL;

[User] Now, include only guests who have communication consent.

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL AND communication_consent = true;

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

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number, city FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL AND communication_consent = true;

[User] Actually, I only need guests from Los Angeles, and order them by last name in alphabetical order.

[Assistant] SELECT guest_id, first_name, last_name, email, phone_number, city FROM hospitality_technology.guests WHERE state_province = 'California' AND city = 'Los Angeles' AND loyalty_member_id IS NOT NULL AND communication_consent = true ORDER BY last_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 insurance.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)

[User] I need to identify pairs of customers who share the same last name and live in the same city. List customer1_id, customer2_id, last_name, and city.

[Assistant]
SELECT
  c1.customer_id AS customer1_id,
  c2.customer_id AS customer2_id,
  c1.last_name,
  c1.city
FROM insurance.customers c1
JOIN insurance.customers c2
  ON c1.last_name = c2.last_name
  AND c1.city = c2.city
  AND c1.customer_id <> c2.customer_id;

[User] Actually, only include customers whose status is 'Active'.

[Assistant]
SELECT
  c1.customer_id AS customer1_id,
  c2.customer_id AS customer2_id,
  c1.last_name,
  c1.city
FROM insurance.customers c1
JOIN insurance.customers c2
  ON c1.last_name = c2.last_name
  AND c1.city = c2.city
  AND c1.customer_id <> c2.customer_id
WHERE c1.status = 'Active'
  AND c2.status = 'Active';

[User] Also, ensure that customer1_id is always less than customer2_id to avoid duplicate pairs.

[Assistant]
SELECT
  c1.customer_id AS customer1_id,
  c2.customer_id AS customer2_id,
  c1.last_name,
  c1.city
FROM insurance.customers c1
JOIN insurance.customers c2
  ON c1.last_name = c2.last_name
  AND c1.city = c2.city
  AND c1.customer_id <> c2.customer_id
WHERE c1.status = 'Active'
  AND c2.status = 'Active'
  AND c1.customer_id < c2.customer_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 project_fundraising_record ( id character varying(32) NOT NULL, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
 "CREATE TABLE narrative_info (",
    "narrative character varying(512) NOT NULL, -- the id of narrative",
    "top_3_coins text, -- the top 3 tokens in the narrative",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative",
    "price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative",
    "market_cap double precision, -- the market cap of the narrative",
    "volume_24h double precision, -- the trade volume of the narrative",
    "trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative",
    "token_num bigint, -- total token number in the narrative",
    ",PRIMARY KEY (narrative));"

  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )

[User] What are the top 5 tokens by 7-day price change percentage? Show token_symbol, token_name, narrative, and chain, ordered by price_change_percentage_7d descending.

[Assistant]
```sql
SELECT
  token_symbol,
  token_name,
  narrative,
  chain
FROM token_basic_info
ORDER BY price_change_percentage_7d DESC
LIMIT 5;
```


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )

[User] Show user_id and post_id for users who have created posts and have a private profile.

[Assistant] SELECT p.user_id, p.post_id FROM social_media.posts AS p JOIN social_media.user_settings AS us ON p.user_id = us.user_id WHERE us.private_profile = true

[User] Only include posts created in 2024.

[Assistant] SELECT p.user_id, p.post_id FROM social_media.posts AS p JOIN social_media.user_settings AS us ON p.user_id = us.user_id WHERE us.private_profile = true AND p.created_at >= '2024-01-01' AND p.created_at < '2025-01-01'

[User] Also, filter to only show posts with media_type 'image'.

[Assistant] SELECT p.user_id, p.post_id FROM social_media.posts AS p JOIN social_media.user_settings AS us ON p.user_id = us.user_id WHERE us.private_profile = true AND p.created_at >= '2024-01-01' AND p.created_at < '2025-01-01' AND p.media_type = 'image'

[User] Order the results by post creation time descending.

[Assistant] SELECT p.user_id, p.post_id FROM social_media.posts AS p JOIN social_media.user_settings AS us ON p.user_id = us.user_id WHERE us.private_profile = true AND p.created_at >= '2024-01-01' AND p.created_at < '2025-01-01' AND p.media_type = 'image' ORDER BY p.created_at 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 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.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.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text )

[User] Show me all securities along with the number of employees per branch that work at a branch matching the security's exchange as their branch_id. Show the ticker symbol, security name, exchange, branch_id, and employee count.

[Assistant]
SELECT s.ticker_symbol, s.security_name, s.exchange, e.branch_id, COUNT(e.employee_id) AS employee_count
FROM financial_services.securities s
JOIN financial_services.employees e
  ON s.exchange = e.branch_id
GROUP BY s.ticker_symbol, s.security_name, s.exchange, e.branch_id;

[User] Only include branches with more than 2 employees and securities in the 'Technology' sector.

[Assistant]
SELECT s.ticker_symbol, s.security_name, s.exchange, e.branch_id, COUNT(e.employee_id) AS employee_count
FROM financial_services.securities s
JOIN financial_services.employees e
  ON s.exchange = e.branch_id
WHERE s.sector = 'Technology'
GROUP BY s.ticker_symbol, s.security_name, s.exchange, e.branch_id
HAVING COUNT(e.employee_id) > 2;

[User] Sort by employee_count descending and then by ticker_symbol ascending.

[Assistant]
SELECT s.ticker_symbol, s.security_name, s.exchange, e.branch_id, COUNT(e.employee_id) AS employee_count
FROM financial_services.securities s
JOIN financial_services.employees e
  ON s.exchange = e.branch_id
WHERE s.sector = 'Technology'
GROUP BY s.ticker_symbol, s.security_name, s.exchange, e.branch_id
HAVING COUNT(e.employee_id) > 2
ORDER BY employee_count DESC, s.ticker_symbol 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 legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)

[User] Show me all pairs of time entries made by the same lawyer on the same date. Include both entry IDs, lawyer_id, and date_worked.

[Assistant]
SELECT t1.lawyer_id, t1.date_worked, t1.entry_id AS entry_id_1, t2.entry_id AS entry_id_2
FROM legal_services.time_entries t1
JOIN legal_services.time_entries t2
  ON t1.lawyer_id = t2.lawyer_id
  AND t1.date_worked = t2.date_worked
WHERE t1.entry_id < t2.entry_id;

[User] Actually, only include pairs where both entries are billable.

[Assistant]
SELECT t1.lawyer_id, t1.date_worked, t1.entry_id AS entry_id_1, t2.entry_id AS entry_id_2
FROM legal_services.time_entries t1
JOIN legal_services.time_entries t2
  ON t1.lawyer_id = t2.lawyer_id
  AND t1.date_worked = t2.date_worked
WHERE t1.entry_id < t2.entry_id
  AND t1.is_billable = true
  AND t2.is_billable = true;

[User] Also, ensure that the two entries have different hours_spent values.

[Assistant]
SELECT t1.lawyer_id, t1.date_worked, t1.entry_id AS entry_id_1, t2.entry_id AS entry_id_2
FROM legal_services.time_entries t1
JOIN legal_services.time_entries t2
  ON t1.lawyer_id = t2.lawyer_id
  AND t1.date_worked = t2.date_worked
WHERE t1.entry_id < t2.entry_id
  AND t1.is_billable = true
  AND t2.is_billable = true
  AND t1.hours_spent <> t2.hours_spent;


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.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] Show me the total quantity and total price for each service ordered by each guest.

[Assistant] SELECT guest_id, service_id, SUM(quantity) AS total_quantity, SUM(total_price) AS total_price FROM hospitality_technology.service_orders GROUP BY guest_id, service_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 web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )

[User] Show each token's symbol, token_name, and the deployer_address and status of the contract where that token was created.

[Assistant]
SELECT t.token_symbol,
       t.token_name,
       c.deployer_address,
       c.status
FROM web3.tokens t
JOIN web3.contracts c ON t.contract_address = c.address;


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 text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
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.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.payments ( payment_id text PRIMARY KEY, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] Show me the count of available rooms for each property.

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

[User] Also, include the average base rate of available room types for each property.

[Assistant] SELECT T1.property_name, count(T2.room_id), avg(T3.base_rate) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.rooms AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T2.room_type_id = T3.room_type_id WHERE T2.status = 'Available' GROUP BY T1.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 gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )

[User] Could you list all pairs of developers in the same country but different companies? Return developer1, developer2, and country.

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

[User] Now restrict pairs to only those in country 'USA' or 'Canada'.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
WHERE d1.country IN ('USA', 'Canada');

[User] Sort the pairs by developer1 name ascending.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
WHERE d1.country IN ('USA', 'Canada')
ORDER BY d1.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 transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )

[User] List all trips along with their trip ID and the number of passengers if the trip is currently in progress.

[Assistant] SELECT trip_id, passenger_count FROM transportation.trips WHERE status = 'In Progress';

[User] Add the vehicle_id and driver_id to the result as well.

[Assistant] SELECT trip_id, passenger_count, vehicle_id, driver_id FROM transportation.trips WHERE status = 'In Progress';

[User] Actually, I also need the scheduled departure time for these trips.

[Assistant] SELECT trip_id, passenger_count, vehicle_id, driver_id, scheduled_departure FROM transportation.trips WHERE status = 'In Progress';

[User] Sort the result by scheduled departure in ascending order.

[Assistant] SELECT trip_id, passenger_count, vehicle_id, driver_id, scheduled_departure FROM transportation.trips WHERE status = 'In Progress' ORDER BY scheduled_departure 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 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.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction 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 )

[User] Which clients have at least one open case, and what are the names and numbers of those cases?

[Assistant]
SELECT c.first_name, c.last_name, cs.case_name, cs.case_number
FROM legal_services.clients c
JOIN legal_services.cases cs ON c.client_id = cs.client_id
WHERE cs.status = 'Open';


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

[User] Can you list each game alongside another game in the same genre but by a different developer?

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id;

[User] Exclude any pairs where either game was released before 2019.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id
WHERE g1.release_date >= '2019-01-01'
  AND g2.release_date >= '2019-01-01';

[User] Limit the output to the first 10 pairs ordered by genre and developer_id.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id
WHERE g1.release_date >= '2019-01-01'
  AND g2.release_date >= '2019-01-01'
ORDER BY g1.genre, g1.developer_id
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 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.hashtags ( hashtag_id text PRIMARY KEY, tag_name text, created_at timestamp )
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text 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] Show the usernames of all users who were created in 2024.

[Assistant]
SELECT username
FROM social_media.users
WHERE EXTRACT(YEAR FROM created_at) = 2024;


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 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, ssn_hash character varying(128), address text NOT NULL, city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, status character varying(32) NOT NULL, risk_profile character varying(50), PRIMARY KEY (customer_id) )
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
CREATE TABLE financial_services.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    PRIMARY KEY (transaction_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id)
)
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )

[User] Show me all trades with their corresponding ticker_symbol and security_name for trades executed in the last 7 days.

[Assistant]
SELECT tr.trade_id, tr.account_id, tr.trade_type, tr.quantity, tr.price_per_unit, tr.total_amount,
       tr.commission, tr.trade_timestamp,
       s.ticker_symbol, s.security_name
FROM financial_services.trades tr
JOIN financial_services.securities s ON tr.security_id = s.security_id
WHERE tr.trade_timestamp >= now() - INTERVAL '7 days';

[User] Only include trades where commission is greater than 50 and status is 'Completed'.

[Assistant]
SELECT tr.trade_id, tr.account_id, tr.trade_type, tr.quantity, tr.price_per_unit, tr.total_amount,
       tr.commission, tr.trade_timestamp,
       s.ticker_symbol, s.security_name
FROM financial_services.trades tr
JOIN financial_services.securities s ON tr.security_id = s.security_id
WHERE tr.trade_timestamp >= now() - INTERVAL '7 days'
  AND tr.commission > 50
  AND tr.status = 'Completed';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// PUT /schedules
{
  "mappings": {
    "properties": {
      "schedule_id": { "type": "keyword" },
      "train_id": { "type": "keyword" }, // References trains index
      "route_id": { "type": "keyword" }, // References routes index
      "departure_datetime": { "type": "date" }, // ISO 8601 format recommended
      "arrival_datetime": { "type": "date" },
      "status": { "type": "keyword" },
      "notes": { "type": "text" }
    }
  }
}
// PUT /passengers
{
  "mappings": {
    "properties": {
      "passenger_id": { "type": "keyword" },
      "first_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 100 } }
      },
      "last_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 100 } }
       },
      "email": { "type": "keyword" }, // Often used for exact matches
      "phone_number": { "type": "keyword" },
      "date_of_birth": { "type": "date", "format": "yyyy-MM-dd" },
      "loyalty_program_id": { "type": "keyword" },
      "created_at": { "type": "date" }
    }
  }
}

[User] 能否帮我查询特定列车行程(schedule_id 为 'sched_001')的详细信息，包括列车出发和到达时间，以及该行程所属路线的ID和相关乘客信息？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001';

[User] 能否将结果限制在状态为‘Scheduled’的行程上，并且只显示乘客的姓名和电子邮件？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001' AND s.status = 'Scheduled';

[User] 能否再加入行程的备注信息，并按出发时间降序排列？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, s.notes, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001' AND s.status = 'Scheduled'
ORDER BY s.departure_datetime DESC;

[User] 如果没有关联的乘客信息，能否只显示行程信息？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, s.notes, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001' AND s.status = 'Scheduled'
ORDER BY s.departure_datetime 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 gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.developers (
    developer_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the developer studio
    name character varying(150) NOT NULL UNIQUE, -- name of the development studio
    country character varying(100), -- country where the studio is based
    founded_year integer, -- year the studio was founded
    website character varying(255), -- developer's official website
    created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (developer_id)
)
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)

[User] Can you list all game servers, showing their name, the game title, and the region?

[Assistant]
SELECT
  T1.server_name,
  T2.title,
  T1.region
FROM gaming_technology.servers AS T1
INNER JOIN gaming_technology.games AS T2
  ON T1.game_id = T2.game_id;

[User] Filter the list to only include servers that are currently 'online'.

[Assistant]
SELECT
  T1.server_name,
  T2.title,
  T1.region
FROM gaming_technology.servers AS T1
INNER JOIN gaming_technology.games AS T2
  ON T1.game_id = T2.game_id
WHERE
  T1.status = 'online';

[User] For these online servers, could you also show the number of current players and the maximum player capacity?

[Assistant]
SELECT
  T1.server_name,
  T2.title,
  T1.region,
  T1.current_players,
  T1.max_players
FROM gaming_technology.servers AS T1
INNER JOIN gaming_technology.games AS T2
  ON T1.game_id = T2.game_id
WHERE
  T1.status = 'online';

[User] Finally, could you summarize by game title and region, showing the total number of online servers and the total current players for those servers?

[Assistant]
SELECT
  T2.title,
  T1.region,
  COUNT(T1.server_id) AS online_server_count,
  SUM(T1.current_players) AS total_current_players
FROM gaming_technology.servers AS T1
INNER JOIN gaming_technology.games AS T2
  ON T1.game_id = T2.game_id
WHERE
  T1.status = 'online'
GROUP BY
  T2.title,
  T1.region
ORDER BY
  online_server_count DESC,
  total_current_players 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 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.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id 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.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] Can you show me the count of new doctors added each month in 2023? Return the month and number of doctors.

[Assistant]
SELECT DATE_TRUNC('month', created_at) AS month, COUNT(*) AS doctor_count
FROM healthcare.doctors
WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01'
GROUP BY DATE_TRUNC('month', created_at);

[User] Actually, include the month as the first day of the month and order the results by month in descending order.

[Assistant]
SELECT DATE_TRUNC('month', created_at)::date AS month_start, COUNT(*) AS doctor_count
FROM healthcare.doctors
WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01'
GROUP BY DATE_TRUNC('month', created_at)
ORDER BY month_start 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 gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )

[User] Retrieve pairs of visible achievements from the same game along with their point difference.

[Assistant]
SELECT a.achievement_id AS ach1_id,
       b.achievement_id AS ach2_id,
       a.name           AS ach1_name,
       b.name           AS ach2_name,
       ABS(a.points - b.points) AS point_difference
FROM gaming_technology.achievements a
JOIN gaming_technology.achievements b
  ON a.game_id = b.game_id
  AND a.hidden = false
  AND b.hidden = false
  AND a.achievement_id < b.achievement_id;

[User] Only include pairs where the point_difference exceeds 20.

[Assistant]
SELECT a.achievement_id AS ach1_id,
       b.achievement_id AS ach2_id,
       a.name           AS ach1_name,
       b.name           AS ach2_name,
       ABS(a.points - b.points) AS point_difference
FROM gaming_technology.achievements a
JOIN gaming_technology.achievements b
  ON a.game_id = b.game_id
  AND a.hidden = false
  AND b.hidden = false
  AND a.achievement_id < b.achievement_id
WHERE ABS(a.points - b.points) > 20;

[User] Also display the game_id in the result.

[Assistant]
SELECT a.game_id,
       a.achievement_id AS ach1_id,
       b.achievement_id AS ach2_id,
       a.name           AS ach1_name,
       b.name           AS ach2_name,
       ABS(a.points - b.points) AS point_difference
FROM gaming_technology.achievements a
JOIN gaming_technology.achievements b
  ON a.game_id = b.game_id
  AND a.hidden = false
  AND b.hidden = false
  AND a.achievement_id < b.achievement_id
WHERE ABS(a.points - b.points) > 20;

[User] Order by point_difference descending, then by ach1_name ascending.

[Assistant]
SELECT a.game_id,
       a.achievement_id AS ach1_id,
       b.achievement_id AS ach2_id,
       a.name           AS ach1_name,
       b.name           AS ach2_name,
       ABS(a.points - b.points) AS point_difference
FROM gaming_technology.achievements a
JOIN gaming_technology.achievements b
  ON a.game_id = b.game_id
  AND a.hidden = false
  AND b.hidden = false
  AND a.achievement_id < b.achievement_id
WHERE ABS(a.points - b.points) > 20
ORDER BY point_difference DESC, ach1_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 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.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )

[User] Retrieve the policy_number, start_date, end_date, premium_amount, and corresponding product_name for policies with a coverage_limit greater than 500000.

[Assistant]
SELECT p.policy_number, p.start_date, p.end_date, p.premium_amount, ip.product_name
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.coverage_limit > 500000;


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.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )

[User] For each passenger, show their passenger_id, first_name, last_name, and the count of other passengers in the same loyalty_program_id.

[Assistant]
SELECT p1.passenger_id, p1.first_name, p1.last_name, COUNT(p2.passenger_id) AS peer_count
FROM transportation.passengers p1
LEFT JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
GROUP BY p1.passenger_id, p1.first_name, p1.last_name;

[User] Only include passengers who have more than 3 peers in their loyalty program.

[Assistant]
SELECT p1.passenger_id, p1.first_name, p1.last_name, COUNT(p2.passenger_id) AS peer_count
FROM transportation.passengers p1
LEFT JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
GROUP BY p1.passenger_id, p1.first_name, p1.last_name
HAVING COUNT(p2.passenger_id) > 3;

[User] Also include the loyalty_program_id in the results.

[Assistant]
SELECT p1.passenger_id, p1.first_name, p1.last_name, p1.loyalty_program_id, COUNT(p2.passenger_id) AS peer_count
FROM transportation.passengers p1
LEFT JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
GROUP BY p1.passenger_id, p1.first_name, p1.last_name, p1.loyalty_program_id
HAVING COUNT(p2.passenger_id) > 3;


[User] Get the total_quantity and total_revenue (sum of total_price) for each staff member who placed orders (staff_id_ordered).

[Assistant]
SELECT staff_id_ordered,
       SUM(quantity) AS total_quantity,
       SUM(total_price) AS total_revenue
FROM hospitality_technology.service_orders
GROUP BY staff_id_ordered;

[User] Filter to staff who have delivered at least one order (staff_id_delivered is not null).

[Assistant]
SELECT staff_id_ordered,
       SUM(quantity) AS total_quantity,
       SUM(total_price) AS total_revenue
FROM hospitality_technology.service_orders
WHERE staff_id_delivered IS NOT NULL
GROUP BY staff_id_ordered;

[User] For these staff members, list each order along with the previous order they placed, including first_order_timestamp and second_order_timestamp, and the time difference in hours.

[Assistant]
SELECT t1.staff_id_ordered,
       t1.order_id AS first_order_id,
       t2.order_id AS second_order_id,
       t1.order_timestamp AS first_order_timestamp,
       t2.order_timestamp AS second_order_timestamp,
       EXTRACT(EPOCH FROM (t2.order_timestamp - t1.order_timestamp)) / 3600 AS hours_diff
FROM hospitality_technology.service_orders t1
JOIN hospitality_technology.service_orders t2
  ON t1.staff_id_ordered = t2.staff_id_ordered
 AND t2.order_timestamp > t1.order_timestamp
 AND NOT EXISTS (
       SELECT 1 FROM hospitality_technology.service_orders t3
       WHERE t3.staff_id_ordered = t1.staff_id_ordered
         AND t3.order_timestamp > t1.order_timestamp
         AND t3.order_timestamp < t2.order_timestamp
   )
WHERE t1.staff_id_delivered IS NOT NULL
  AND t2.staff_id_delivered IS NOT NULL
ORDER BY t1.staff_id_ordered, t1.order_timestamp;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )

[User] List all tokens along with the contract addresses for symbols that appear more than once.

[Assistant]
SELECT t.token_id, t.token_symbol, t.contract_address
FROM web3.tokens t
JOIN (
  SELECT token_symbol
  FROM web3.tokens
  GROUP BY token_symbol
  HAVING COUNT(*) > 1
) dup ON t.token_symbol = dup.token_symbol;


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. 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 train_station_management.staff ( staff_id.text, first_name.text, last_name.text, role.text, primary_station_id.text, employee_number.text, hire_date.date, contact_email.text, contact_phone.text, is_active.boolean )

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

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


System:
You are an 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.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )

[User] Which guests have used services that are currently unavailable? Show guest full names, the service name, and the order status.

[Assistant]
SELECT g.first_name, g.last_name, s.service_name, so.status
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so ON g.guest_id = so.guest_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id
WHERE s.is_available = FALSE;

[User] Please only show those orders where the status is 'Completed' or 'Delivered', and sort the results by service name.

[Assistant]
SELECT g.first_name, g.last_name, s.service_name, so.status
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so ON g.guest_id = so.guest_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id
WHERE s.is_available = FALSE
  AND so.status IN ('Completed', 'Delivered')
ORDER BY s.service_name ASC;

[User] Also, add the date and time when the service was delivered, and only include records where delivery_timestamp is not null.

[Assistant]
SELECT g.first_name, g.last_name, s.service_name, so.status, so.delivery_timestamp
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so ON g.guest_id = so.guest_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id
WHERE s.is_available = FALSE
  AND so.status IN ('Completed', 'Delivered')
  AND so.delivery_timestamp IS NOT NULL
ORDER BY s.service_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 healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] Can you show me the details of all medical records for patients that had their vitals recorded with a temperature above 38 degrees Celsius, along with any medication descriptions that mention 'antipyretic'?

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.record_date, mr.chief_complaint, mr.treatment_plan, m.medication_name, m.description
FROM healthcare.medical_records mr
JOIN healthcare.medications m ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE (mr.vitals->>'Temp')::numeric > 38 AND m.description ILIKE '%antipyretic%';

[User] Refine the query to only include records created after January 1st, 2024.

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.record_date, mr.chief_complaint, mr.treatment_plan, m.medication_name, m.description
FROM healthcare.medical_records mr
JOIN healthcare.medications m ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE (mr.vitals->>'Temp')::numeric > 38
  AND m.description ILIKE '%antipyretic%'
  AND mr.record_date >= '2024-01-01';

[User] Actually, could you also include the doctor's ID who created each medical record?

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.doctor_id, mr.record_date, mr.chief_complaint, mr.treatment_plan, m.medication_name, m.description
FROM healthcare.medical_records mr
JOIN healthcare.medications m ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE (mr.vitals->>'Temp')::numeric > 38
  AND m.description ILIKE '%antipyretic%'
  AND mr.record_date >= '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 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.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )

[User] Can you list all securities that have had at least one trade in the past 30 days? Please include the ticker_symbol, security_name, exchange, and the total number of trades for each security.

[Assistant]
SELECT s.ticker_symbol, s.security_name, s.exchange, COUNT(t.trade_id) AS trade_count
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY s.ticker_symbol, s.security_name, s.exchange;

[User] I want to see the average trade quantity as well for each security in the same result.

[Assistant]
SELECT s.ticker_symbol, s.security_name, s.exchange, COUNT(t.trade_id) AS trade_count, AVG(t.quantity) AS avg_quantity
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY s.ticker_symbol, s.security_name, s.exchange;

[User] I need only those securities where the average trade quantity is above 100. Please order by avg_quantity descending.

[Assistant]
SELECT s.ticker_symbol, s.security_name, s.exchange, COUNT(t.trade_id) AS trade_count, AVG(t.quantity) AS avg_quantity
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY s.ticker_symbol, s.security_name, s.exchange
HAVING AVG(t.quantity) > 100
ORDER BY avg_quantity DESC;

[User] Instead, show only securities traded on the 'NASDAQ' or 'NYSE' exchanges.

[Assistant]
SELECT s.ticker_symbol, s.security_name, s.exchange, COUNT(t.trade_id) AS trade_count, AVG(t.quantity) AS avg_quantity
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days'
  AND s.exchange IN ('NASDAQ', 'NYSE')
GROUP BY s.ticker_symbol, s.security_name, s.exchange
HAVING AVG(t.quantity) > 100
ORDER BY avg_quantity DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )

[User] How many group conversations are there?

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE is_group_chat = TRUE;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id.text, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.messages ( message_id.text, conversation_id.text, sender_user_id.text, content.text, media_url.text, media_type.text, sent_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )

[User] List all posts that contain the word 'festival' in their content, showing the post_id, the author's username, and the post creation time.

[Assistant]
SELECT p.post_id, u.username, p.created_at
FROM social_media.posts p
JOIN social_media.users u ON p.user_id = u.user_id
WHERE p.content ILIKE '%festival%';


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.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] For each notification, list its notification_id, message_subject, and the message_subject of the notification it relates to (assuming related_entity_type = 'notification').

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id;

[User] Only include notifications with status = 'Sent'.

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id
WHERE n.status = 'Sent';


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 text PRIMARY KEY, 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 )

[User] Show me the total paid amount and the number of premium payments per customer for policies that have at least one payment over $5000.

[Assistant] SELECT customer_id, SUM(amount_paid) AS total_paid, COUNT(*) AS payment_count FROM insurance.premium_payments WHERE policy_id IN (SELECT policy_id FROM insurance.premium_payments WHERE amount_paid > 5000) GROUP BY customer_id;

[User] Can you also include the earliest payment date for each customer in the result?

[Assistant] SELECT customer_id, SUM(amount_paid) AS total_paid, COUNT(*) AS payment_count, MIN(payment_date) AS earliest_payment_date FROM insurance.premium_payments WHERE policy_id IN (SELECT policy_id FROM insurance.premium_payments WHERE amount_paid > 5000) GROUP BY customer_id;

[User] Now restrict this to only show customers who have made payments using the 'bank transfer' method.

[Assistant] SELECT customer_id, SUM(amount_paid) AS total_paid, COUNT(*) AS payment_count, MIN(payment_date) AS earliest_payment_date FROM insurance.premium_payments WHERE policy_id IN (SELECT policy_id FROM insurance.premium_payments WHERE amount_paid > 5000) AND payment_method = 'bank transfer' GROUP BY customer_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 web3.token_transfers ( transfer_id.text, token_id.text, from_address.text, to_address.text, value.numeric, transaction_id.text, log_index.integer )

[User] List all token transfers where the value is an even number, showing transfer ID, token ID, value, and transaction ID.

[Assistant]
SELECT transfer_id, token_id, value, transaction_id
FROM web3.token_transfers
WHERE MOD(value, 2) = 0;

[User] Could you also include the from_address and to_address, and order the result by value descending?

[Assistant]
SELECT transfer_id, token_id, value, transaction_id, from_address, to_address
FROM web3.token_transfers
WHERE MOD(value, 2) = 0
ORDER BY value 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 trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp )

[User] List the names and URLs of all decentralized applications where the description includes the word 'exchange'.

[Assistant]
SELECT d.name, d.url
FROM trading_platform.dapps d
WHERE d.description ILIKE '%exchange%';


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 pairs of documents uploaded by the same lawyer but for different cases, showing both document names, their case IDs, and the lawyer ID.

[Assistant] SELECT t1.document_name AS document1_name, t1.case_id AS document1_case_id, t2.document_name AS document2_name, t2.case_id AS document2_case_id, t1.uploaded_by_lawyer_id FROM legal_services.documents AS t1 JOIN legal_services.documents AS t2 ON t1.uploaded_by_lawyer_id = t2.uploaded_by_lawyer_id AND t1.case_id <> t2.case_id AND t1.document_id < t2.document_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, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )

[User] Show me a list of all notifications that are related to comments. Include the notification ID, the recipient user ID, and the target entity ID, which corresponds to the comment ID.

[Assistant] SELECT notification_id, recipient_user_id, target_entity_id FROM social_media.notifications WHERE target_entity_type = 'comment';

[User] Please expand that list to include the username of the notification recipient and the content of the comment that the notification is about.

[Assistant] SELECT n.notification_id, u.username, c.content FROM social_media.notifications n JOIN social_media.users u ON n.recipient_user_id = u.user_id JOIN social_media.comments c ON n.target_entity_id = c.comment_id WHERE n.target_entity_type = 'comment';

[User] Okay, filter this down to only show notifications where the comment content is not empty, and the notification type is either 'like' or 'comment'.

[Assistant] SELECT n.notification_id, u.username, c.content FROM social_media.notifications n JOIN social_media.users u ON n.recipient_user_id = u.user_id JOIN social_media.comments c ON n.target_entity_id = c.comment_id WHERE n.target_entity_type = 'comment' AND (c.content IS NOT NULL AND c.content != '') AND n.notification_type IN ('like', 'comment');