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.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )

[User] Find pairs of active services from the same agency where one service's average processing time is longer than the other's. Display the agency_id, the slower service name with its processing time, and the faster service name with its processing time.

[Assistant]
SELECT
  s1.agency_id,
  s1.service_name AS slower_service_name,
  s1.average_processing_time_days AS slower_time,
  s2.service_name AS faster_service_name,
  s2.average_processing_time_days AS faster_time
FROM
  government_services.services s1
JOIN
  government_services.services s2
  ON s1.agency_id = s2.agency_id
  AND s1.average_processing_time_days > s2.average_processing_time_days
WHERE
  s1.is_active = true
  AND s2.is_active = 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 government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] How many citizens are marked as not verified?

[Assistant] SELECT COUNT(*) FROM government_services.citizens WHERE is_verified = FALSE;


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.platforms ( platform_id text, station_id text, platform_number text, track_number text, status text, length_meters numeric, accessible boolean )

[User] What is the maintenance schedule for platform 3 at station DEF for the next month?

[Assistant] I'm sorry, but I don't have access to the maintenance schedule for platforms. The data I have only includes static information about platform details such as ID, station, number, track, status, length, and accessibility. For maintenance schedules, you may need to consult the station management or relevant department.


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address.text, city.text, state.text, zip_code.text, country.text, email.text, phone_number.text, created_at.timestamp, status.text, risk_profile.text )
CREATE TABLE financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )
CREATE TABLE financial_services.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
CREATE TABLE financial_services.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] List all employees who were hired in the last two years along with their department and status.

[Assistant] SELECT employee_id, first_name, last_name, department, status FROM financial_services.employees WHERE hire_date >= (CURRENT_DATE - INTERVAL '2 years');

[User] Now also include their manager's full name in the output.

[Assistant] SELECT e.employee_id, e.first_name, e.last_name, e.department, e.status, m.first_name || ' ' || m.last_name AS manager_full_name FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.hire_date >= (CURRENT_DATE - INTERVAL '2 years');

[User] Only include employees whose status is 'Active' and whose manager is also currently 'Active'.

[Assistant] SELECT e.employee_id, e.first_name, e.last_name, e.department, e.status, m.first_name || ' ' || m.last_name AS manager_full_name FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.hire_date >= (CURRENT_DATE - INTERVAL '2 years') AND e.status = 'Active' AND m.status = 'Active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)

[User] Retrieve trip_id and passenger full names for all trips where the passenger record was created before the scheduled departure.

[Assistant]
SELECT t.trip_id, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure;

[User] Filter the results to only include trips with passenger_count greater than 5.

[Assistant]
SELECT t.trip_id, t.passenger_count, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure
WHERE t.passenger_count > 5;

[User] Also sort the output by passenger_count descending and limit to the top 10 records.

[Assistant]
SELECT t.trip_id, t.passenger_count, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure
WHERE t.passenger_count > 5
ORDER BY t.passenger_count 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 healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)

[User] List the medication_id, medication_name, and description for all medications whose generic_name starts with 'A'.

[Assistant]
SELECT medication_id, medication_name, description
FROM healthcare.medications
WHERE generic_name LIKE 'A%';


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.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_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.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] Which hashtags appear on the most posts? Return hashtag_id, tag_name, and the number of posts each hashtag is used in, sorted descending, limited to the top 3.

[Assistant]
SELECT
  h.hashtag_id,
  h.tag_name,
  COUNT(ph.post_id) AS post_count
FROM social_media.hashtags h
JOIN social_media.post_hashtags ph
  ON h.hashtag_id = ph.hashtag_id
GROUP BY h.hashtag_id, h.tag_name
ORDER BY post_count DESC
LIMIT 3;


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
Collection 'assembly_steps'. Document structure: { _id: <ObjectId (or step_id)>, step_id: String, line_id: String (reference), step_number: NumberInt, step_name: String, description: String, standard_duration_hours: Decimal128, required_skill_level: String, workstation: String }. Required: step_id, line_id, step_number, step_name. Index on line_id, step_number.
Collection 'employees'. Document structure: { _id: <ObjectId (or employee_id)>, employee_id: String, first_name: String, last_name: String, job_title: String, skill_certifications: [String], hire_date: ISODate, assigned_line_id: String (reference, optional), employment_status: String, supervisor_employee_id: String (reference, optional) }. Required: employee_id, first_name, last_name, job_title, hire_date, employment_status.

[User] 特定の組み立てラインに関連するすべての手順を取得したいです。ラインIDと手順名、手順番号、必要なスキルレベルを含めてください。

[Assistant]
db.assembly_steps.find(
    { line_id: '<specific_line_id>' },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] さらに、必要なスキルレベルが「Senior Technician」以上の手順だけを表示できますか？

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician'
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 標準作業時間が3時間以上の手順も条件に追加できますか？

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician',
        standard_duration_hours: { $gte: 3 }
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 最後に、作業場所が「Workstation_B」の手順だけに絞り込んでください。

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician',
        standard_duration_hours: { $gte: 3 },
        workstation: 'Workstation_B'
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    application_id character varying(64), -- FK to applications table (optional)
    message_subject character varying(255),
    message_body text NOT NULL,
    channel character varying(30) NOT NULL, -- e.g., Email, SMS, Portal Message, Mail
    sent_at timestamp NOT NULL,
    status character varying(30) NOT NULL, -- e.g., Queued, Sent, Delivered, Failed, Read
    related_entity_type character varying(50), -- e.g., Application, Appointment, Document Request
    related_entity_id character varying(64), -- ID of the related entity
    PRIMARY KEY (notification_id)
)

[User] List all job titles of employees who work in the 'Finance' department.

[Assistant]
SELECT DISTINCT job_title
FROM government_services.employees
WHERE department = 'Finance';


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,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
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 token_dexpool_info ( pair_address text, token_name text, token_symbol text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_6h numeric, price_change_percentage_24h numeric, makers_24h numeric, volume_24h numeric, liquidity numeric, market_cap numeric, trend_rank numeric )
  "CREATE TABLE 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));"

[User] List all tokens held by CEX addresses, showing the token symbol, name, current price, and the total USD value held by all CEXes for that token.

[Assistant] SELECT T1.token_symbol, T1.token_name, T1.price, SUM(T2.usd_value) AS total_cex_usd_value FROM token_basic_info AS T1 INNER JOIN cex_token_balance AS T2 ON T1.token_symbol = T2.token_symbol GROUP BY T1.token_symbol, T1.token_name, T1.price

[User] Only show results for tokens on the 'Ethereum' chain and order them by the total CEX USD value descending.

[Assistant] SELECT T1.token_symbol, T1.token_name, T1.price, SUM(T2.usd_value) AS total_cex_usd_value FROM token_basic_info AS T1 INNER JOIN cex_token_balance AS T2 ON T1.token_symbol = T2.token_symbol WHERE T1.chain = 'Ethereum' GROUP BY T1.token_symbol, T1.token_name, T1.price ORDER BY total_cex_usd_value DESC

[User] Add a filter to only include tokens where the total CEX USD value is greater than 1,000,000.

[Assistant] SELECT T1.token_symbol, T1.token_name, T1.price, SUM(T2.usd_value) AS total_cex_usd_value FROM token_basic_info AS T1 INNER JOIN cex_token_balance AS T2 ON T1.token_symbol = T2.token_symbol WHERE T1.chain = 'Ethereum' GROUP BY T1.token_symbol, T1.token_name, T1.price HAVING SUM(T2.usd_value) > 1000000 ORDER BY total_cex_usd_value DESC

[User] Limit the results to the top 5 tokens.

[Assistant] SELECT T1.token_symbol, T1.token_name, T1.price, SUM(T2.usd_value) AS total_cex_usd_value FROM token_basic_info AS T1 INNER JOIN cex_token_balance AS T2 ON T1.token_symbol = T2.token_symbol WHERE T1.chain = 'Ethereum' GROUP BY T1.token_symbol, T1.token_name, T1.price HAVING SUM(T2.usd_value) > 1000000 ORDER BY total_cex_usd_value 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 gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )

[User] For each game, which server has hosted the most sessions?

[Assistant] SELECT game_id, server_id, COUNT(*) AS session_count FROM gaming_technology.game_sessions GROUP BY game_id, server_id;

[User] I want the server with the highest session count per game, not all servers.

[Assistant] SELECT t.game_id, t.server_id, t.session_count FROM (SELECT game_id, server_id, COUNT(*) AS session_count, RANK() OVER (PARTITION BY game_id ORDER BY COUNT(*) DESC) AS rnk FROM gaming_technology.game_sessions GROUP BY game_id, server_id) t WHERE t.rnk = 1;

[User] If two servers have the same highest count for a game, will both be shown?

[Assistant] Yes, the RANK() function ensures all servers tied for the highest session count per game are shown. The SQL will return all such tied servers for each game where they share the top session count.

[User] Can you also show the total duration of all sessions for the top server(s) per game?

[Assistant] WITH top_servers AS (SELECT game_id, server_id, COUNT(*) AS session_count, RANK() OVER (PARTITION BY game_id ORDER BY COUNT(*) DESC) AS rnk FROM gaming_technology.game_sessions GROUP BY game_id, server_id) SELECT ts.game_id, ts.server_id, ts.session_count, SUM(gs.duration_seconds) AS total_duration FROM top_servers ts JOIN gaming_technology.game_sessions gs ON ts.game_id = gs.game_id AND ts.server_id = gs.server_id WHERE ts.rnk = 1 GROUP BY ts.game_id, ts.server_id, ts.session_count;


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 PRIMARY KEY, 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 PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )

[User] Which users have commented on posts created by the users they follow? Please show the commenter user_ids and the followed user_ids.

[Assistant] SELECT DISTINCT c.user_id AS commenter_user_id, f.following_user_id AS followed_user_id FROM social_media.comments c JOIN social_media.follows f ON c.user_id = f.follower_user_id AND c.post_id IN (SELECT post_id FROM social_media.comments WHERE user_id = f.following_user_id);

[User] Can you also include the post_id in the results?

[Assistant] SELECT DISTINCT c.user_id AS commenter_user_id, f.following_user_id AS followed_user_id, c.post_id FROM social_media.comments c JOIN social_media.follows f ON c.user_id = f.follower_user_id AND c.post_id IN (SELECT post_id FROM social_media.comments WHERE user_id = f.following_user_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 financial_services.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )
CREATE TABLE financial_services.transactions ( transaction_id text, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )

[User] Can you show me, for each account type, the total transaction amount and the number of transactions, including the customer full name for each account type?

[Assistant]
SELECT a.account_type, c.first_name || ' ' || c.last_name AS customer_name, SUM(t.amount) AS total_transaction_amount, COUNT(t.transaction_id) AS transaction_count
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
JOIN financial_services.transactions t ON a.account_id = t.account_id
GROUP BY a.account_type, customer_name;

[User] Actually, could you only include accounts where the balance is greater than 5000?

[Assistant]
SELECT a.account_type, c.first_name || ' ' || c.last_name AS customer_name, SUM(t.amount) AS total_transaction_amount, COUNT(t.transaction_id) AS transaction_count
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
JOIN financial_services.transactions t ON a.account_id = t.account_id
WHERE a.balance > 5000
GROUP BY a.account_type, customer_name;

[User] Can you also filter transactions to only include those with status 'SUCCESSFUL'?

[Assistant]
SELECT a.account_type, c.first_name || ' ' || c.last_name AS customer_name, SUM(t.amount) AS total_transaction_amount, COUNT(t.transaction_id) AS transaction_count
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
JOIN financial_services.transactions t ON a.account_id = t.account_id
WHERE a.balance > 5000 AND t.status = 'SUCCESSFUL'
GROUP BY a.account_type, customer_name;


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

[User] Show me all patients who have non-primary insurance plans with expiration dates within the next 60 days, along with their policy numbers and subscriber names.

[Assistant] SELECT patient_id, policy_number, subscriber_name FROM healthcare.patient_insurance WHERE is_primary = false AND expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '60 days');


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id.text, policy_id.text, customer_id.text, first_name.text, last_name.text, relationship.text, percentage_share.numeric, contact_info.text, added_at.timestamp )

[User] List the policy number, start date, product name, and base premium for policies where the base premium of the associated product is greater than 1000.

[Assistant] SELECT T1.policy_number, T1.start_date, T2.product_name, T2.base_premium FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T2.base_premium > 1000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )

[User] List each booking with its previous booking time for the same passenger.

[Assistant]
SELECT b.booking_id,
       b.passenger_id,
       b.booking_time,
       LAG(b.booking_time) OVER (PARTITION BY b.passenger_id ORDER BY b.booking_time) AS previous_booking_time
FROM transportation.bookings b;

[User] I only want records where the gap between bookings is more than 7 days.

[Assistant]
SELECT booking_id,
       passenger_id,
       booking_time,
       previous_booking_time
FROM (
  SELECT booking_id,
         passenger_id,
         booking_time,
         LAG(booking_time) OVER (PARTITION BY passenger_id ORDER BY booking_time) AS previous_booking_time
  FROM transportation.bookings
) t
WHERE previous_booking_time IS NOT NULL
  AND booking_time - previous_booking_time > INTERVAL '7 days';

[User] Also include the total number of bookings for each passenger.

[Assistant]
SELECT booking_id,
       passenger_id,
       booking_time,
       previous_booking_time,
       COUNT(*) OVER (PARTITION BY passenger_id) AS total_bookings
FROM (
  SELECT booking_id,
         passenger_id,
         booking_time,
         LAG(booking_time) OVER (PARTITION BY passenger_id ORDER BY booking_time) AS previous_booking_time
  FROM transportation.bookings
) t
WHERE previous_booking_time IS NOT NULL
  AND booking_time - previous_booking_time > INTERVAL '7 days';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
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 PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] I want a list of all users, showing for each user their user_id, username, KYC status, and the date their account was created.

[Assistant]
SELECT u.user_id, u.username, k.status AS kyc_status, u.created_at
FROM trading_platform.users u
LEFT JOIN trading_platform.kyc_audit k ON u.user_id = k.user_id;

[User] Could you only show users whose KYC status is 'approved'?

[Assistant]
SELECT u.user_id, u.username, k.status AS kyc_status, u.created_at
FROM trading_platform.users u
LEFT JOIN trading_platform.kyc_audit k ON u.user_id = k.user_id
WHERE k.status = 'approved';

[User] Now, add the number of wallets associated with each of these users.

[Assistant]
SELECT u.user_id, u.username, k.status AS kyc_status, u.created_at, COUNT(w.wallet_id) AS wallet_count
FROM trading_platform.users u
LEFT JOIN trading_platform.kyc_audit k ON u.user_id = k.user_id
LEFT JOIN trading_platform.wallets w ON u.user_id = w.user_id
WHERE k.status = 'approved'
GROUP BY u.user_id, u.username, k.status, u.created_at;

[User] Only show users who have more than one wallet, and order the list by wallet_count descending.

[Assistant]
SELECT u.user_id, u.username, k.status AS kyc_status, u.created_at, COUNT(w.wallet_id) AS wallet_count
FROM trading_platform.users u
LEFT JOIN trading_platform.kyc_audit k ON u.user_id = k.user_id
LEFT JOIN trading_platform.wallets w ON u.user_id = w.user_id
WHERE k.status = 'approved'
GROUP BY u.user_id, u.username, k.status, u.created_at
HAVING COUNT(w.wallet_id) > 1
ORDER BY wallet_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)

[User] Retrieve the product_id, product_name, base_premium, and created_at for all active insurance products with a base_premium greater than 1000, ordered by base_premium descending.

[Assistant]
SELECT
  product_id,
  product_name,
  base_premium,
  created_at
FROM insurance.insurance_products
WHERE is_active = true
  AND base_premium > 1000
ORDER BY base_premium DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )

[User] Which token on the Ethereum chain had the highest realized ratio last quarter? Show the symbol, realized ratio, and ROI.

[Assistant] SELECT token_symbol, realized_ratio, roi FROM smart_money_token_performance WHERE chain = 'Ethereum' AND date_trunc('quarter', CURRENT_DATE) - interval '1 quarter' = date_trunc('quarter', now()) ORDER BY realized_ratio DESC LIMIT 1;

[User] Can you show the top 3 tokens by realized ratio instead of just the top one?

[Assistant] SELECT token_symbol, realized_ratio, roi FROM smart_money_token_performance WHERE chain = 'Ethereum' AND date_trunc('quarter', CURRENT_DATE) - interval '1 quarter' = date_trunc('quarter', now()) ORDER BY realized_ratio DESC LIMIT 3;

[User] Include their average cost in the result.

[Assistant] SELECT token_symbol, realized_ratio, roi, avg_cost FROM smart_money_token_performance WHERE chain = 'Ethereum' AND date_trunc('quarter', CURRENT_DATE) - interval '1 quarter' = date_trunc('quarter', now()) ORDER BY realized_ratio DESC LIMIT 3;

[User] Also show their current price.

[Assistant] SELECT token_symbol, realized_ratio, roi, avg_cost, price FROM smart_money_token_performance WHERE chain = 'Ethereum' AND date_trunc('quarter', CURRENT_DATE) - interval '1 quarter' = date_trunc('quarter', now()) ORDER BY realized_ratio DESC LIMIT 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
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 character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )

[User] Show all cases with at least one billed and billable time entry, including case number, case name, total billed amount, and billed hours.

[Assistant]
SELECT cs.case_number, cs.case_name, SUM(te.hours_spent * te.billing_rate) AS total_billed_amount, SUM(te.hours_spent) AS total_billed_hours
FROM legal_services.cases cs
JOIN legal_services.time_entries te ON cs.case_id = te.case_id
WHERE te.is_billable = TRUE AND te.is_billed = TRUE
GROUP BY cs.case_number, cs.case_name;

[User] Add the lead lawyer's full name to the result.

[Assistant]
SELECT cs.case_number, cs.case_name, l.first_name || ' ' || l.last_name AS lead_lawyer_full_name, SUM(te.hours_spent * te.billing_rate) AS total_billed_amount, SUM(te.hours_spent) AS total_billed_hours
FROM legal_services.cases cs
JOIN legal_services.time_entries te ON cs.case_id = te.case_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
WHERE te.is_billable = TRUE AND te.is_billed = TRUE
GROUP BY cs.case_number, cs.case_name, l.first_name, l.last_name;

[User] Filter for cases where the total billed amount exceeds 8000, and only include those opened after January 1, 2023.

[Assistant]
SELECT cs.case_number, cs.case_name, l.first_name || ' ' || l.last_name AS lead_lawyer_full_name, SUM(te.hours_spent * te.billing_rate) AS total_billed_amount, SUM(te.hours_spent) AS total_billed_hours
FROM legal_services.cases cs
JOIN legal_services.time_entries te ON cs.case_id = te.case_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
WHERE te.is_billable = TRUE AND te.is_billed = TRUE AND cs.date_opened > '2023-01-01'
GROUP BY cs.case_number, cs.case_name, l.first_name, l.last_name
HAVING SUM(te.hours_spent * te.billing_rate) > 8000;

[User] Add the invoice numbers linked to these cases in the output.

[Assistant]
SELECT cs.case_number, cs.case_name, l.first_name || ' ' || l.last_name AS lead_lawyer_full_name, SUM(te.hours_spent * te.billing_rate) AS total_billed_amount, SUM(te.hours_spent) AS total_billed_hours, STRING_AGG(DISTINCT inv.invoice_number, ', ') AS invoice_numbers
FROM legal_services.cases cs
JOIN legal_services.time_entries te ON cs.case_id = te.case_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
LEFT JOIN legal_services.invoices inv ON cs.case_id = inv.case_id
WHERE te.is_billable = TRUE AND te.is_billed = TRUE AND cs.date_opened > '2023-01-01'
GROUP BY cs.case_number, cs.case_name, l.first_name, l.last_name
HAVING SUM(te.hours_spent * te.billing_rate) > 8000;


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.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )

[User] List all insurance products along with their type and base premium. Also, show whether each product is active.

[Assistant] SELECT product_id, product_name, product_type, base_premium, is_active FROM insurance.insurance_products;

[User] Can you filter the results to only show insurance products of type 'auto'?

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

[User] Also, sort these results by the base premium in ascending order.

[Assistant] SELECT product_id, product_name, product_type, base_premium, is_active FROM insurance.insurance_products WHERE product_type = 'auto' ORDER BY base_premium 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.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )

[User] How many beneficiaries are there for each relationship type?

[Assistant]
SELECT relationship,
       COUNT(*) AS beneficiary_count
FROM insurance.policy_beneficiaries
GROUP BY relationship;


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.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)

[User] For every game, can you provide the count of unique item types and the average item cost?

[Assistant] SELECT game_id, COUNT(DISTINCT item_type) AS num_unique_types, AVG(cost_amount) AS avg_item_cost FROM gaming_technology.in_game_items GROUP BY game_id;

[User] Could you also add the lowest item cost for each game?

[Assistant] SELECT game_id, COUNT(DISTINCT item_type) AS num_unique_types, AVG(cost_amount) AS avg_item_cost, MIN(cost_amount) AS min_item_cost FROM gaming_technology.in_game_items GROUP BY game_id;

[User] Now, please only show games with at least 2 different item types.

[Assistant] SELECT game_id, COUNT(DISTINCT item_type) AS num_unique_types, AVG(cost_amount) AS avg_item_cost, MIN(cost_amount) AS min_item_cost FROM gaming_technology.in_game_items GROUP BY game_id HAVING COUNT(DISTINCT item_type) >= 2;


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 manufacturing.aircraft_models (
    model_id character varying(64) NOT NULL,  -- unique identifier for the aircraft model
    model_name character varying(128) NOT NULL, -- commercial name of the model (e.g., 737 MAX, A320neo)
    manufacturer character varying(128) NOT NULL, -- manufacturer name (e.g., Boeing, Airbus)
    passenger_capacity integer, -- typical passenger capacity
    max_range_km integer, -- maximum flight range in kilometers
    engine_type character varying(100), -- type of engines used
    wingspan_m numeric(6,2), -- wingspan in meters
    status character varying(50) NOT NULL, -- e.g., 'In Production', 'Development', 'Discontinued'
    first_flight_date date, -- date of the model's first flight
    PRIMARY KEY (model_id)
)

[User] What is the current market price of a Boeing 737 MAX aircraft?

[Assistant] I'm sorry, but I don't have access to the current market price of aircraft models. The data I have is limited to technical specifications and general information about aircraft models such as passenger capacity, range, and status. For pricing information, you may need to consult with manufacturers or industry reports.


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] Find documents that have the same document_name but are associated with different cases. Show the document name and the two different case IDs.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id;

[User] Actually, only show pairs where at least one of the documents is of document_type 'Contract'.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract');

[User] Also, only include pairs where both documents were uploaded in the year 2024.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract') AND YEAR(d1.upload_timestamp) = 2024 AND YEAR(d2.upload_timestamp) = 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 hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )

[User] Show me each department in each property, along with the total number of available services and their combined price.

[Assistant] SELECT property_id, department, COUNT(*) AS service_count, SUM(price) AS total_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, department;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text )
CREATE TABLE erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE erc20_balances_historical ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.integer )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins ( object_id.text, status.text, coin_type.text, balance.text, owner.text )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_metadata ( blockchain.text, contract_address.text, token_id.text, contract_name.text, erc_type.text, amount.bigint, minter.text, owner.text, mint_block_number.bigint, mint_time.bigint, mint_transaction_hash.text, mint_price.text, token_uri.text, metadata.text, name.text, image_uri.text, traits.text, updated_at.bigint, status.text, rarity_score.real, rarity_rank.integer, unique_attribute_count.integer, pk.integer )
CREATE TABLE nft_collections ( blockchain.text, contract_address.text, name.text, symbol.text, deploy_block_number.bigint, deploy_block_time.bigint, erc_type.text, owner.text, traits.text, description.text, slug.text, media_info.text, image_url.text, banner_image_url.text, updated_at.bigint, banner.text, token_count.bigint, floor_price.text, floor_price_symbol.text, floor_price_contract.text, pk.integer )
CREATE TABLE token_prices ( uuid.text, blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address.text, table_id.text, key_bytes.text, key0.text, key1.text, static_data.text, encoded_lengths.text, dynamic_data.text, is_deleted.boolean, block_number.bigint, log_index.bigint )
CREATE TABLE token_balances_bitcoin ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.text, amount.text )
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_activities_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_avalanche ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text, minted.decimal, holders.decimal, txs.decimal, updated_timestamp.timestamp, completed_timestamp.timestamp, id.text )

[User] For each ERC1155 NFT contract on Ethereum, show the contract address, token_id, and the total amount held across all wallets.

[Assistant] SELECT nh.contract_address, nh.token_id, SUM(CAST(nh.amount AS NUMERIC)) AS total_amount FROM nft_holder_historical nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_type = 'ERC1155' AND nm.blockchain = 'Ethereum' GROUP BY nh.contract_address, nh.token_id;

[User] Include the name of each NFT from the nft_metadata table as well.

[Assistant] SELECT nh.contract_address, nh.token_id, nm.name, SUM(CAST(nh.amount AS NUMERIC)) AS total_amount FROM nft_holder_historical nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_type = 'ERC1155' AND nm.blockchain = 'Ethereum' GROUP BY nh.contract_address, nh.token_id, nm.name;

[User] Only include NFTs where the total amount held exceeds 500, and order the results by total_amount descending.

[Assistant] SELECT nh.contract_address, nh.token_id, nm.name, SUM(CAST(nh.amount AS NUMERIC)) AS total_amount FROM nft_holder_historical nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_type = 'ERC1155' AND nm.blockchain = 'Ethereum' GROUP BY nh.contract_address, nh.token_id, nm.name HAVING SUM(CAST(nh.amount AS NUMERIC)) > 500 ORDER BY total_amount 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 hospitality_technology.service_orders ( order_id text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] How many service orders were placed by each staff member (staff_id_ordered)? Show the staff ID and the count.

[Assistant] SELECT staff_id_ordered, COUNT(*) FROM hospitality_technology.service_orders GROUP BY staff_id_ordered;

[User] Only show staff members who placed more than 10 orders.

[Assistant] SELECT staff_id_ordered, COUNT(*) FROM hospitality_technology.service_orders GROUP BY staff_id_ordered HAVING COUNT(*) > 10;

[User] And exclude orders that were cancelled.

[Assistant] SELECT staff_id_ordered, COUNT(*) FROM hospitality_technology.service_orders WHERE status != 'Cancelled' GROUP BY staff_id_ordered HAVING COUNT(*) > 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 healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] List patient_id, full name, policy_number, plan_type, and insurance_provider for all active primary insurance policies.

[Assistant]
SELECT pi.patient_id,
       p.first_name,
       p.last_name,
       pi.policy_number,
       ip.plan_type,
       ip.insurance_provider
FROM healthcare.patient_insurance pi
JOIN healthcare.patients p
  ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip
  ON ip.plan_id = pi.plan_id
WHERE pi.is_primary = TRUE
  AND pi.effective_date <= CURRENT_DATE
  AND pi.expiration_date >= CURRENT_DATE;

[User] Now also restrict to policies expiring within the next 30 days.

[Assistant]
SELECT pi.patient_id,
       p.first_name,
       p.last_name,
       pi.policy_number,
       ip.plan_type,
       ip.insurance_provider
FROM healthcare.patient_insurance pi
JOIN healthcare.patients p
  ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip
  ON ip.plan_id = pi.plan_id
WHERE pi.is_primary = TRUE
  AND pi.effective_date <= CURRENT_DATE
  AND pi.expiration_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )

[User] How many service locations are there for each agency? List the agency ID and the count of locations.

[Assistant] SELECT agency_id ,  count(*) FROM government_services.service_locations GROUP BY 1


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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] Show all fuel logs for vehicle_id 'VH123', including the timestamp, fuel type, quantity, and the location_id. Sort the list by timestamp descending.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
ORDER BY log_timestamp DESC;

[User] Can you also include the odometer reading and total cost for each fuel log in the result?

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
ORDER BY log_timestamp DESC;

[User] I only want to see records where the total_cost is above 100.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
  AND total_cost > 100
ORDER BY log_timestamp DESC;

[User] Actually, please limit the results to just the 5 most recent logs.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
  AND total_cost > 100
ORDER BY log_timestamp 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 insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )

[User] List policy pairs for the same customer where one policy was cancelled and another active policy started within 30 days after the cancellation. Show customer_id, cancelled policy_number, cancellation_date, active policy_number, start_date.

[Assistant]
SELECT p1.customer_id,
       p1.policy_number AS cancelled_policy_number,
       p1.cancellation_date,
       p2.policy_number AS active_policy_number,
       p2.start_date
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.status = 'cancelled'
 AND p2.status = 'active'
 AND p2.start_date BETWEEN p1.cancellation_date AND p1.cancellation_date + INTERVAL '30 days';

[User] Also include the number of days between cancellation and new policy start as days_to_new.

[Assistant]
SELECT p1.customer_id,
       p1.policy_number AS cancelled_policy_number,
       p1.cancellation_date,
       p2.policy_number AS active_policy_number,
       p2.start_date,
       EXTRACT(DAY FROM (p2.start_date - p1.cancellation_date)) AS days_to_new
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.status = 'cancelled'
 AND p2.status = 'active'
 AND p2.start_date BETWEEN p1.cancellation_date AND p1.cancellation_date + INTERVAL '30 days';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// PUT /stations
{
  "mappings": {
    "properties": {
      "station_id": { "type": "keyword" },
      "station_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } }
      },
      "city": { "type": "keyword" },
      "state_province": { "type": "keyword" },
      "country_code": { "type": "keyword" },
      "address": { "type": "text" },
      "timezone": { "type": "keyword" },
      "number_of_platforms": { "type": "integer" },
      "created_at": { "type": "date" },
      "last_updated_at": { "type": "date" }
    }
  }
}
// PUT /platforms
{
  "mappings": {
    "properties": {
      "platform_id": { "type": "keyword" },
      "station_id": { "type": "keyword" }, // References stations index
      "platform_number": { "type": "keyword" },
      "track_number": { "type": "keyword" },
      "status": { "type": "keyword" },
      "length_meters": { "type": "scaled_float", "scaling_factor": 100 }, // Or float/double
      "accessible": { "type": "boolean" }
    }
  }
}
// PUT /train_cars
{
  "mappings": {
    "properties": {
      "car_id": { "type": "keyword" },
      "train_id": { "type": "keyword" }, // References trains index
      "car_number": { "type": "keyword" },
      "car_type": { "type": "keyword" },
      "class": { "type": "keyword" },
      "capacity": { "type": "integer" },
      "features": { "type": "keyword" } // Array of keywords
    }
  }
}
// PUT /routes
{
  "mappings": {
    "properties": {
      "route_id": { "type": "keyword" },
      "route_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } }
      },
      "description": { "type": "text" },
      "origin_station_id": { "type": "keyword" }, // References stations index
      "destination_station_id": { "type": "keyword" }, // References stations index
      "is_active": { "type": "boolean" }
    }
  }
}
// PUT /route_stations
{
  "mappings": {
    "properties": {
      "route_station_id": { "type": "keyword" },
      "route_id": { "type": "keyword" }, // References routes index
      "station_id": { "type": "keyword" }, // References stations index
      "sequence_order": { "type": "integer" },
      "distance_from_previous_km": { "type": "scaled_float", "scaling_factor": 100 },
      "typical_stop_duration_minutes": { "type": "integer" }
    }
  }
}
// --- OR --- Use a 'nested' type within the 'routes' index mapping:
// "stations": {
//   "type": "nested",
//   "properties": {
//     "station_id": { "type": "keyword" },
//     "sequence_order": { "type": "integer" },
//     ...
//    }
// }
// 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 /schedule_stops
{
  "mappings": {
    "properties": {
      "stop_id": { "type": "keyword" },
      "schedule_id": { "type": "keyword" }, // References schedules index
      "station_id": { "type": "keyword" }, // References stations index
      "platform_id": { "type": "keyword" }, // References platforms index
      "sequence_order": { "type": "integer" },
      "scheduled_arrival_time": { "type": "date" },
      "scheduled_departure_time": { "type": "date" },
      "actual_arrival_time": { "type": "date" },
      "actual_departure_time": { "type": "date" },
      "status": { "type": "keyword" }
    }
  }
}
// --- OR --- Use a 'nested' type within the 'schedules' index mapping:
// "stops": {
//   "type": "nested",
//   "properties": { ... }
// }
// PUT /bookings
{
  "mappings": {
    "properties": {
      "booking_id": { "type": "keyword" },
      "passenger_id": { "type": "keyword" }, // References passengers index
      "schedule_id": { "type": "keyword" }, // References schedules index
      "booking_datetime": { "type": "date" },
      "status": { "type": "keyword" },
      "total_price": { "type": "scaled_float", "scaling_factor": 100 }, // Or float/double
      "currency_code": { "type": "keyword" },
      "special_requests": { "type": "text" }
    }
  }
}
// PUT /tickets
{
  "mappings": {
    "properties": {
      "ticket_id": { "type": "keyword" },
      "booking_id": { "type": "keyword" }, // References bookings index
      "car_id": { "type": "keyword" }, // References train_cars index
      "seat_number": { "type": "keyword" },
      "ticket_type": { "type": "keyword" },
      "price": { "type": "scaled_float", "scaling_factor": 100 },
      "is_checked_in": { "type": "boolean" },
      "qr_code_data": { "type": "keyword", "index": false } // Often not searched on
    }
  }
}
// --- OR --- Use a 'nested' type within the 'bookings' index mapping.
// PUT /maintenance_records
{
  "mappings": {
    "properties": {
      "record_id": { "type": "keyword" },
      "asset_id": { "type": "keyword" }, // ID of the asset
      "asset_type": { "type": "keyword" }, // Type ('Train', 'Car', etc.)
      "maintenance_type": { "type": "keyword" },
      "staff_id": { "type": "keyword" }, // References staff index
      "start_datetime": { "type": "date" },
      "end_datetime": { "type": "date" },
      "description": { "type": "text" },
      "cost": { "type": "scaled_float", "scaling_factor": 100 },
      "status": { "type": "keyword" }
    }
  }
}

[User] Can you provide the total capacity of all train cars for a specific train with train_id 'TR789'?

[Assistant]
SELECT SUM(capacity) AS total_capacity
FROM train_cars
WHERE train_id = 'TR789';


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.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )

[User] Show me all participants who joined any conversation before January 1st, 2024. Return participant_id, user_id, conversation_id and the joined_at timestamp.

[Assistant] SELECT participant_id, user_id, conversation_id, joined_at FROM social_media.conversation_participants WHERE joined_at < '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE nft_collections ( blockchain.text, contract_address.text, name.text, symbol.text, deploy_block_number.bigint, deploy_block_time.bigint, erc_type.text, owner.text, traits.text, description.text, slug.text, media_info.text, image_url.text, banner_image_url.text, updated_at.bigint, banner.text, token_count.bigint, floor_price.text, floor_price_symbol.text, floor_price_contract.text, pk.integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(255) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(62) NOT NULL, -- Address sending the inscription
    to_address varchar(62) NOT NULL  -- Address receiving the inscription
)
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )

[User] List all ERC721 collections with their names, symbols, and floor prices where the floor price is greater than 0.1 ETH.

[Assistant] SELECT name, symbol, floor_price FROM nft_collections WHERE erc_type = 'ERC721' AND CAST(floor_price AS decimal) > 0.1;

[User] I think there's an error in your query - it should be CAST(floor_price AS decimal) not CAST(floor_price AS decimal). Also, can you include the banner image URL for these collections?

[Assistant] SELECT name, symbol, floor_price, banner_image_url FROM nft_collections WHERE erc_type = 'ERC721' AND CAST(floor_price AS decimal) > 0.1;

[User] Now sort these results by floor price in descending order and limit to the top 10.

[Assistant] SELECT name, symbol, floor_price, banner_image_url FROM nft_collections WHERE erc_type = 'ERC721' AND CAST(floor_price AS decimal) > 0.1 ORDER BY CAST(floor_price AS decimal) DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )

[User] What is the total estimated_loss and average settlement_amount for all claims with status 'Approved'?

[Assistant]
SELECT SUM(estimated_loss) AS total_estimated_loss,
       AVG(settlement_amount) AS average_settlement
FROM insurance.claims
WHERE status = 'Approved';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )

[User] List all appointments showing the scheduled time, the name of the service, and the name of the location.

[Assistant] SELECT T1.scheduled_start_time, T2.service_name, T3.location_name FROM government_services.appointments AS T1 JOIN government_services.services AS T2 ON T1.service_id = T2.service_id JOIN government_services.service_locations AS T3 ON T1.location_id = T3.location_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 insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )

[User] Can you retrieve the document_id, file_name, file_size_bytes, uploaded_at, and the full name of the agent (first and last name concatenated) for all documents uploaded in 2024 by active agents licensed in CA?

[Assistant] SELECT cd.document_id, cd.file_name, cd.file_size_bytes, cd.uploaded_at, a.first_name || ' ' || a.last_name AS agent_full_name FROM insurance.claim_documents cd JOIN insurance.agents a ON cd.uploaded_by = a.agent_id WHERE a.license_state = 'CA' AND a.status = 'Active' AND cd.uploaded_at BETWEEN '2024-01-01' AND '2024-12-31';