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 erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE sui_coins ( object_id 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_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_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE 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_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] List all ERC20 tokens from the `token_metas` table that have a total supply greater than 1 followed by 21 zeros. Show their contract address, symbol, name, and total supply.

[Assistant] SELECT contract_address, symbol, name, total_supply FROM token_metas WHERE is_erc20 = 1 AND CAST(total_supply AS DECIMAL) > 1000000000000000000000;

[User] Okay, for those tokens, can you also include the number of unique wallet addresses that hold each token? Only show tokens with more than 500 unique holders.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, COUNT(DISTINCT eb.wallet_address) AS unique_holder_count FROM token_metas tm JOIN erc20_balances eb ON tm.contract_address = eb.contract_address WHERE tm.is_erc20 = 1 AND CAST(tm.total_supply AS DECIMAL) > 1000000000000000000000 GROUP BY tm.contract_address, tm.symbol, tm.name, tm.total_supply HAVING COUNT(DISTINCT eb.wallet_address) > 500;

[User] Great, now add the latest USD price and decimals for these tokens by joining with the `token_prices_latest` table.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tpl.usd_price, tm.decimals, COUNT(DISTINCT eb.wallet_address) AS unique_holder_count FROM token_metas tm JOIN erc20_balances eb ON tm.contract_address = eb.contract_address JOIN token_prices_latest tpl ON tm.contract_address = tpl.contract_address WHERE tm.is_erc20 = 1 AND CAST(tm.total_supply AS DECIMAL) > 1000000000000000000000 GROUP BY tm.contract_address, tm.symbol, tm.name, tm.total_supply, tpl.usd_price, tm.decimals HAVING COUNT(DISTINCT eb.wallet_address) > 500;

[User] Please filter the results to only include tokens where the latest price is greater than 0.1 USD, order by the number of unique holders descending, and limit the output to the top 10 tokens.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tpl.usd_price, tm.decimals, COUNT(DISTINCT eb.wallet_address) AS unique_holder_count FROM token_metas tm JOIN erc20_balances eb ON tm.contract_address = eb.contract_address JOIN token_prices_latest tpl ON tm.contract_address = tpl.contract_address WHERE tm.is_erc20 = 1 AND CAST(tm.total_supply AS DECIMAL) > 1000000000000000000000 AND tpl.usd_price > 0.1 GROUP BY tm.contract_address, tm.symbol, tm.name, tm.total_supply, tpl.usd_price, tm.decimals HAVING COUNT(DISTINCT eb.wallet_address) > 500 ORDER BY unique_holder_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 hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )

[User] List staff members who were hired in the last calendar year, showing their full name, position, and hire date.

[Assistant] SELECT first_name, last_name, position, hire_date FROM hospitality_technology.staff WHERE hire_date >= date_trunc('year', current_date - interval '1' year) AND hire_date < date_trunc('year', current_date);

[User] Now, only include those staff members who are not managers and have an access level greater than 3.

[Assistant] SELECT first_name, last_name, position, hire_date FROM hospitality_technology.staff WHERE hire_date >= date_trunc('year', current_date - interval '1' year) AND hire_date < date_trunc('year', current_date) AND position != 'Manager' AND access_level > 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 insurance.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)
CREATE TABLE insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
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] I need to find, for each active agent, the number of active policies they have sold and the average premium_amount of those active policies.

[Assistant]
SELECT a.agent_id, a.first_name || ' ' || a.last_name AS agent_name, COUNT(p.policy_id) AS policy_count, AVG(p.premium_amount) AS avg_premium_amount
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE a.status = 'Active'
  AND p.status = 'Active'
GROUP BY a.agent_id, agent_name
ORDER BY policy_count DESC;

[User] Actually, restrict this to agents licensed in state 'CA'.

[Assistant]
SELECT a.agent_id, a.first_name || ' ' || a.last_name AS agent_name, COUNT(p.policy_id) AS policy_count, AVG(p.premium_amount) AS avg_premium_amount
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE a.status = 'Active'
  AND p.status = 'Active'
  AND a.license_state = 'CA'
GROUP BY a.agent_id, agent_name
ORDER BY policy_count DESC;

[User] Also include the average coverage_limit of those policies as avg_coverage_limit.

[Assistant]
SELECT a.agent_id, a.first_name || ' ' || a.last_name AS agent_name, COUNT(p.policy_id) AS policy_count, AVG(p.premium_amount) AS avg_premium_amount, AVG(p.coverage_limit) AS avg_coverage_limit
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE a.status = 'Active'
  AND p.status = 'Active'
  AND a.license_state = 'CA'
GROUP BY a.agent_id, agent_name
ORDER BY policy_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )

[User] Find all cases that were closed in the year 2022, showing their case name, case number, and date closed.

[Assistant] SELECT case_name, case_number, date_closed FROM legal_services.cases WHERE date_closed >= '2022-01-01' AND date_closed < '2023-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 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.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )

[User] Show me all premium payments made by customer with ID 'CUST789'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789';

[User] From those payments, only include the ones with status 'Completed'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed';

[User] Also, filter the results to only show payments made between '2023-01-01' and '2023-12-31'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed' AND payment_date BETWEEN '2023-01-01' AND '2023-12-31';

[User] Okay, instead of all columns, just show the policy ID, payment date, and amount paid, ordered by payment date descending.

[Assistant] SELECT policy_id, payment_date, amount_paid FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed' AND payment_date BETWEEN '2023-01-01' AND '2023-12-31' ORDER BY payment_date DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )

[User] Find all applications that were submitted in 2023 but received a decision ('Approved' or 'Rejected') in 2024. List the application ID, submitted date, decision date, and status.

[Assistant] SELECT application_id, submitted_at, decision_date, status FROM government_services.applications WHERE submitted_at BETWEEN '2023-01-01 00:00:00' AND '2023-12-31 23:59:59' AND status IN ('Approved', 'Rejected') AND decision_date BETWEEN '2024-01-01' AND '2024-12-31';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Show me all policy beneficiaries who were added in the last 6 months, along with their full names and relationship to the policyholder.

[Assistant] SELECT beneficiary_id, policy_id, first_name, last_name, relationship, percentage_share FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months';

[User] Now filter these results to only show beneficiaries who have a percentage share greater than 30% and include their contact information.

[Assistant] SELECT beneficiary_id, policy_id, first_name, last_name, relationship, percentage_share, contact_info FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months' AND percentage_share > 30;

[User] I also want to see the customer_id for these policies and filter to only show beneficiaries who are listed as 'spouse' or 'child'.

[Assistant] SELECT beneficiary_id, policy_id, customer_id, first_name, last_name, relationship, percentage_share, contact_info FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months' AND percentage_share > 30 AND relationship IN ('spouse', 'child');

[User] Finally, show me the count of such beneficiaries per policy_id.

[Assistant] SELECT policy_id, COUNT(*) AS beneficiary_count FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months' AND percentage_share > 30 AND relationship IN ('spouse', 'child') GROUP BY policy_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 legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )

[User] List all law firms that do not have a website registered, including their firm name and phone.

[Assistant]
SELECT firm_name, phone
FROM legal_services.law_firms
WHERE website IS NULL OR website = '';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )

[User] List all game titles and corresponding server names for servers that are located in the same region as 'us-central-1'.

[Assistant]
SELECT g.title, s.server_name
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.region = 'us-central-1';

[User] Additionally, include the username of every player who has had a session on each of those servers.

[Assistant]
SELECT g.title, s.server_name, p.username
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
JOIN gaming_technology.game_sessions gs ON gs.server_id = s.server_id
JOIN gaming_technology.players p ON gs.player_id = p.player_id
WHERE s.region = 'us-central-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.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.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.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.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
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] Show each employee's first and last name along with the number of appointments they have scheduled in March 2024.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(ap.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments ap ON e.employee_id = ap.employee_id
WHERE ap.scheduled_start_time >= '2024-03-01'
  AND ap.scheduled_start_time < '2024-04-01'
GROUP BY e.first_name, e.last_name;

[User] Only include appointments that are currently in the 'Scheduled' status.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(ap.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments ap ON e.employee_id = ap.employee_id
WHERE ap.scheduled_start_time >= '2024-03-01'
  AND ap.scheduled_start_time < '2024-04-01'
  AND ap.status = 'Scheduled'
GROUP BY e.first_name, e.last_name;

[User] Also include the location name for where those appointments are scheduled.

[Assistant]
SELECT e.first_name, e.last_name, sl.location_name, COUNT(ap.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments ap ON e.employee_id = ap.employee_id
LEFT JOIN government_services.service_locations sl ON ap.location_id = sl.location_id
WHERE ap.scheduled_start_time >= '2024-03-01'
  AND ap.scheduled_start_time < '2024-04-01'
  AND ap.status = 'Scheduled'
GROUP BY e.first_name, e.last_name, sl.location_name;

[User] Sort the result by appointment_count in descending order and limit to the top 5 employees.

[Assistant]
SELECT e.first_name, e.last_name, sl.location_name, COUNT(ap.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments ap ON e.employee_id = ap.employee_id
LEFT JOIN government_services.service_locations sl ON ap.location_id = sl.location_id
WHERE ap.scheduled_start_time >= '2024-03-01'
  AND ap.scheduled_start_time < '2024-04-01'
  AND ap.status = 'Scheduled'
GROUP BY e.first_name, e.last_name, sl.location_name
ORDER BY appointment_count DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.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.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] Find appointments and prescriptions associated with the same patient and doctor. Show the appointment ID, prescription ID, patient ID, and doctor ID.

[Assistant] SELECT T1.appointment_id ,  T2.prescription_id ,  T1.patient_id ,  T1.doctor_id FROM healthcare.appointments AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id  =  T2.patient_id AND T1.doctor_id  =  T2.doctor_id

[User] Refine the list to only include cases where the prescription start date is before the appointment time. Add the start date and appointment time to the results.

[Assistant] SELECT T1.appointment_id ,  T2.prescription_id ,  T1.patient_id ,  T1.doctor_id ,  T2.start_date ,  T1.appointment_time FROM healthcare.appointments AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id  =  T2.patient_id AND T1.doctor_id  =  T2.doctor_id WHERE T2.start_date  <  DATE(T1.appointment_time)


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

[User] List the top 5 tokens by price_change_percentage_7d, showing token_symbol, narrative, and price_change_percentage_7d.

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


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

[User] List pairs of securities that belong to the same sector but have different currencies.

[Assistant] SELECT a.sector, a.ticker_symbol AS symbol_a, a.currency AS currency_a, b.ticker_symbol AS symbol_b, b.currency AS currency_b FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND a.currency <> b.currency;

[User] Filter the pairs to only include sector = 'Healthcare'.

[Assistant] SELECT a.sector, a.ticker_symbol AS symbol_a, a.currency AS currency_a, b.ticker_symbol AS symbol_b, b.currency AS currency_b FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND a.currency <> b.currency WHERE a.sector = 'Healthcare';

[User] Ensure uniqueness by only showing symbol_a < symbol_b.

[Assistant] SELECT a.sector, a.ticker_symbol AS symbol_a, a.currency AS currency_a, b.ticker_symbol AS symbol_b, b.currency AS currency_b FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND a.currency <> b.currency AND a.ticker_symbol < b.ticker_symbol WHERE a.sector = 'Healthcare';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )

[User] Retrieve the title and release_date of all games on the 'PC' platform.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC';

[User] Now exclude any games released before 2018.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC'
  AND release_date >= '2018-01-01';

[User] Also sort the results by release_date in ascending order.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC'
  AND release_date >= '2018-01-01'
ORDER BY release_date 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 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 legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.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.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)

[User] Show me all time entries, including the case name they are associated with.

[Assistant] SELECT T1.*, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id

[User] Only show me time entries for lawyer with ID 'lawyer_789'.

[Assistant] SELECT T1.*, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.lawyer_id = 'lawyer_789'

[User] Actually, I only want entries for the date '2024-07-30', and just show the entry description, hours spent, and case name.

[Assistant] SELECT T1.description, T1.hours_spent, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.lawyer_id = 'lawyer_789' AND T1.date_worked = '2024-07-30'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )

[User] Which addresses have both sent and received tokens? List them.

[Assistant] SELECT DISTINCT t1.from_address FROM web3.token_transfers t1 INNER JOIN web3.token_transfers t2 ON t1.from_address = t2.to_address;

[User] Can you also include how many tokens each of these addresses have sent and received?

[Assistant] SELECT addr, SUM(sent) AS total_sent, SUM(received) AS total_received FROM (SELECT from_address AS addr, SUM(value) AS sent, 0 AS received FROM web3.token_transfers GROUP BY from_address UNION ALL SELECT to_address AS addr, 0 AS sent, SUM(value) AS received FROM web3.token_transfers GROUP BY to_address) AS combined GROUP BY addr HAVING SUM(sent) > 0 AND SUM(received) > 0;


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

[User] Show me the full names of all patients who have received a diagnosis for 'hypertension', along with the appointment time and the doctor's full name for each related appointment.

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, d2.first_name AS doctor_first_name, d2.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.patients d2 ON diag.doctor_id = d2.patient_id
WHERE diag.diagnosis_code = 'hypertension';

[User] Actually, can you update the query to only include those appointments that are currently marked as 'scheduled'?

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, d2.first_name AS doctor_first_name, d2.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.patients d2 ON diag.doctor_id = d2.patient_id
WHERE diag.diagnosis_code = 'hypertension' AND a.status = 'scheduled';

[User] I got an error: doctor information seems to be incorrect, since doctors shouldn’t be retrieved from the patients table. Can you fix the join so the doctor information comes from the correct table?

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, doc.first_name AS doctor_first_name, doc.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.doctors doc ON diag.doctor_id = doc.doctor_id
WHERE diag.diagnosis_code = 'hypertension' AND a.status = 'scheduled';


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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.fuel_logs ( fuel_log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, trip_id character varying(64), log_timestamp timestamp with time zone NOT NULL, fuel_type character varying(32) NOT NULL, quantity numeric(10, 3) NOT NULL, unit character varying(16) NOT NULL, cost_per_unit numeric(8, 4), total_cost numeric(10, 2) NOT NULL, odometer_reading integer, location_id character varying(64), PRIMARY KEY (fuel_log_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )

[User] Which vehicles have a total maintenance cost exceeding 10000 across all their maintenance logs?

[Assistant] SELECT vehicle_id, SUM(cost) AS total_maintenance_cost FROM transportation.maintenance_logs GROUP BY vehicle_id HAVING SUM(cost) > 10000;

[User] For these vehicles, also show the count of maintenance logs and the average cost per log.

[Assistant] SELECT vehicle_id, COUNT(log_id) AS maintenance_log_count, AVG(cost) AS average_maintenance_cost FROM transportation.maintenance_logs GROUP BY vehicle_id HAVING SUM(cost) > 10000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
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) )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] List each property along with the total revenue generated from all delivered service orders, including the property name and total revenue.

[Assistant]
SELECT p.property_id, p.property_name, SUM(so.total_price) AS total_revenue
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON s.property_id = p.property_id
JOIN hospitality_technology.service_orders so ON so.service_id = s.service_id
WHERE so.status = 'delivered'
GROUP BY p.property_id, p.property_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)
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)
)
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] Can you provide a list of all players who have acquired at least one item, along with the item name, its type, and the title of the game that item belongs to?

[Assistant]
SELECT pi.player_id, items.item_name, items.item_type, g.title AS game_title
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
JOIN gaming_technology.games g ON items.game_id = g.game_id
GROUP BY pi.player_id, items.item_name, items.item_type, g.title;

[User] Actually, I'd like to only see cases where a player has acquired more than 2 different types of items. Can you adjust the query?

[Assistant]
SELECT pi.player_id, items.item_name, items.item_type, g.title AS game_title
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
JOIN gaming_technology.games g ON items.game_id = g.game_id
WHERE pi.player_id IN (
    SELECT pi2.player_id
    FROM gaming_technology.player_inventory pi2
    JOIN gaming_technology.in_game_items items2 ON pi2.item_id = items2.item_id
    GROUP BY pi2.player_id
    HAVING COUNT(DISTINCT items2.item_type) > 2
)
GROUP BY pi.player_id, items.item_name, items.item_type, g.title;

[User] I'd also like to know the total quantity of items each qualifying player has acquired. Can you add that to the results?

[Assistant]
SELECT pi.player_id, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
WHERE pi.player_id IN (
    SELECT pi2.player_id
    FROM gaming_technology.player_inventory pi2
    JOIN gaming_technology.in_game_items items2 ON pi2.item_id = items2.item_id
    GROUP BY pi2.player_id
    HAVING COUNT(DISTINCT items2.item_type) > 2
)
GROUP BY pi.player_id;

[User] Can you also display the country of each player if I had such a 'country_code' column in a 'players' table? Show it in the result along with the player_id and total_quantity.

[Assistant]
SELECT pi.player_id, p.country_code, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
JOIN gaming_technology.players p ON pi.player_id = p.player_id
WHERE pi.player_id IN (
    SELECT pi2.player_id
    FROM gaming_technology.player_inventory pi2
    JOIN gaming_technology.in_game_items items2 ON pi2.item_id = items2.item_id
    GROUP BY pi2.player_id
    HAVING COUNT(DISTINCT items2.item_type) > 2
)
GROUP BY pi.player_id, p.country_code;


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.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] Show the top 5 largest documents by file size, including document_id, claim_id, file_name, and file_size_bytes.

[Assistant]
SELECT document_id,
       claim_id,
       file_name,
       file_size_bytes
FROM insurance.claim_documents
ORDER BY file_size_bytes 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 hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)

[User] List all room numbers with their room type name and property name for rooms that have a Jacuzzi feature.

[Assistant]
SELECT r.room_number, rt.type_name, p.property_name
FROM hospitality_technology.rooms r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.features ILIKE '%Jacuzzi%';


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 )

[User] Find all agents hired after '2021-01-01', including their first_name, last_name, hire_date, and their manager's full name.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2021-01-01';

[User] Actually, include only those whose manager is in the same license_state as the agent.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01';

[User] I need only those with commission_rate above 0.05 and status 'Active'.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       a.commission_rate,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01'
  AND a.commission_rate > 0.05
  AND a.status = 'Active';

[User] Sort the results by commission_rate descending and limit to the top 10.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       a.commission_rate,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01'
  AND a.commission_rate > 0.05
  AND a.status = 'Active'
ORDER BY a.commission_rate 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
// 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 project_fundraising_record ( id character varying(32) NOT NULL, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )

[User] I want to see pairs of fundraising rounds for projects that have at least two rounds. Please list project_name, earlier_round, earlier_investment, later_round, and later_investment.

[Assistant]
SELECT
  earlier.project_name,
  earlier.rounds_name AS earlier_round,
  earlier.investment_value AS earlier_investment,
  later.rounds_name AS later_round,
  later.investment_value AS later_investment
FROM project_fundraising_record AS earlier
JOIN project_fundraising_record AS later
  ON earlier.project_id = later.project_id
  AND earlier.investment_date < later.investment_date;

[User] Only include pairs where later_investment is greater than earlier_investment.

[Assistant]
SELECT
  earlier.project_name,
  earlier.rounds_name AS earlier_round,
  earlier.investment_value AS earlier_investment,
  later.rounds_name AS later_round,
  later.investment_value AS later_investment
FROM project_fundraising_record AS earlier
JOIN project_fundraising_record AS later
  ON earlier.project_id = later.project_id
  AND earlier.investment_date < later.investment_date
WHERE later.investment_value > earlier.investment_value;

[User] Also calculate the valuation change between the two rounds as valuation_diff.

[Assistant]
SELECT
  earlier.project_name,
  earlier.rounds_name AS earlier_round,
  earlier.investment_value AS earlier_investment,
  later.rounds_name AS later_round,
  later.investment_value AS later_investment,
  (later.valuation - earlier.valuation) AS valuation_diff
FROM project_fundraising_record AS earlier
JOIN project_fundraising_record AS later
  ON earlier.project_id = later.project_id
  AND earlier.investment_date < later.investment_date
WHERE later.investment_value > earlier.investment_value;

[User] Order by the investment increase descending and limit to top 5.

[Assistant]
SELECT
  earlier.project_name,
  earlier.rounds_name AS earlier_round,
  earlier.investment_value AS earlier_investment,
  later.rounds_name AS later_round,
  later.investment_value AS later_investment,
  (later.valuation - earlier.valuation) AS valuation_diff
FROM project_fundraising_record AS earlier
JOIN project_fundraising_record AS later
  ON earlier.project_id = later.project_id
  AND earlier.investment_date < later.investment_date
WHERE later.investment_value > earlier.investment_value
ORDER BY (later.investment_value - earlier.investment_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 insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )

[User] Retrieve the average base premium of insurance products for each product_type, including only types that have more than 5 products.

[Assistant]
SELECT product_type, AVG(base_premium) AS avg_premium
FROM insurance.insurance_products
GROUP BY product_type
HAVING COUNT(*) > 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE project_fundraising_record ( id text, project_id text, project_name text, rounds_name text, investment_value numeric, investment_date text, introduction text, valuation numeric )
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE 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 smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )

[User] For each narrative in token_basic_info, calculate the total net_flow and average ROI from smart_money_token_performance. List narrative, total_net_flow, avg_roi, ordered by total_net_flow descending.

[Assistant]
SELECT tbi.narrative,
       SUM(smtp.net_flow) AS total_net_flow,
       AVG(smtp.roi) AS avg_roi
FROM token_basic_info tbi
JOIN smart_money_token_performance smtp
  ON tbi.token_address = smtp.token_address
GROUP BY tbi.narrative
ORDER BY total_net_flow DESC;

[User] Now only show narratives with avg_roi greater than 0.10 and total_net_flow positive.

[Assistant]
SELECT tbi.narrative,
       SUM(smtp.net_flow) AS total_net_flow,
       AVG(smtp.roi) AS avg_roi
FROM token_basic_info tbi
JOIN smart_money_token_performance smtp
  ON tbi.token_address = smtp.token_address
GROUP BY tbi.narrative
HAVING SUM(smtp.net_flow) > 0
   AND AVG(smtp.roi) > 0.10
ORDER BY total_net_flow DESC;

[User] Also include the number of unique tokens contributing to each narrative as token_count.

[Assistant]
SELECT tbi.narrative,
       SUM(smtp.net_flow) AS total_net_flow,
       AVG(smtp.roi) AS avg_roi,
       COUNT(DISTINCT tbi.token_address) AS token_count
FROM token_basic_info tbi
JOIN smart_money_token_performance smtp
  ON tbi.token_address = smtp.token_address
GROUP BY tbi.narrative
HAVING SUM(smtp.net_flow) > 0
   AND AVG(smtp.roi) > 0.10
ORDER BY total_net_flow DESC;

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

[Assistant]
SELECT tbi.narrative,
       SUM(smtp.net_flow) AS total_net_flow,
       AVG(smtp.roi) AS avg_roi,
       COUNT(DISTINCT tbi.token_address) AS token_count
FROM token_basic_info tbi
JOIN smart_money_token_performance smtp
  ON tbi.token_address = smtp.token_address
GROUP BY tbi.narrative
HAVING SUM(smtp.net_flow) > 0
   AND AVG(smtp.roi) > 0.10
ORDER BY total_net_flow 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 legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)

[User] List all partners who have provided a phone number, showing their full name and email.

[Assistant] SELECT first_name, last_name, email FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL;

[User] Okay, now only include those partners hired between 2020-01-01 and 2022-12-31.

[Assistant] SELECT first_name, last_name, email FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL AND hire_date BETWEEN '2020-01-01' AND '2022-12-31';

[User] Can you also add their specialization to the output?

[Assistant] SELECT first_name, last_name, email, specialization FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL AND hire_date BETWEEN '2020-01-01' AND '2022-12-31';

[User] Finally, order the results by specialization in ascending order, then by last name.

[Assistant] SELECT first_name, last_name, email, specialization FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL AND hire_date BETWEEN '2020-01-01' AND '2022-12-31' ORDER BY specialization ASC, last_name ASC;


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

[User] List all pairs of patients who registered on the same day. Show patient1_id, patient1_name, patient2_id, patient2_name, and the shared registration date.

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name || ' ' || p1.last_name AS patient1_name, p2.patient_id AS patient2_id, p2.first_name || ' ' || p2.last_name AS patient2_name, p1.created_at::date AS registration_date FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.created_at::date = p2.created_at::date AND p1.patient_id < p2.patient_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 healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )

[User] List all insurance providers along with the total number of plans they offer.

[Assistant]
SELECT insurance_provider, COUNT(*) AS plan_count
FROM healthcare.insurance_plans
GROUP BY insurance_provider;

[User] Only show providers with more than 2 plans.

[Assistant]
SELECT insurance_provider, COUNT(*) AS plan_count
FROM healthcare.insurance_plans
GROUP BY insurance_provider
HAVING COUNT(*) > 2;


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 government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )

[User] List the reference number and status for all applications, including the registration date of the citizen who submitted it.

[Assistant] SELECT a.reference_number, a.status, c.registration_date FROM government_services.applications AS a JOIN citizens AS c ON a.citizen_id = c.citizen_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
// Node Label: :Station
// Properties:
//   station_id: String (Constraint: UNIQUE)
//   station_name: String
//   city: String (Index recommended)
//   state_province: String
//   country_code: String
//   address: String
//   timezone: String
//   number_of_platforms: Integer
//   created_at: DateTime
//   last_updated_at: DateTime
// Example Cypher CREATE:
// CREATE (:Station {station_id: 'station_xyz', station_name: 'Grand Central Terminal', city: 'New York', ...})
// Node Label: :Platform
// Properties:
//   platform_id: String (Constraint: UNIQUE)
//   platform_number: String
//   track_number: String
//   status: String
//   length_meters: Float
//   accessible: Boolean
// Relationship: (:Platform)-[:LOCATED_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (s:Station {station_id: 'station_xyz'})
// CREATE (p:Platform {platform_id: 'plat_123', ...})-[:LOCATED_AT]->(s)
// Node Label: :Train
// Properties:
//   train_id: String (Constraint: UNIQUE)
//   train_number: String (Constraint: UNIQUE)
//   model: String
//   manufacturer: String
//   year_manufactured: Integer
//   capacity: Integer
//   status: String
//   last_maintenance_date: Date
//   next_maintenance_date: Date
// Example Cypher CREATE:
// CREATE (:Train {train_id: 'train_789', train_number: 'Acela 2151', ...})
// Node Label: :TrainCar
// Properties:
//   car_id: String (Constraint: UNIQUE)
//   car_number: String
//   car_type: String
//   class: String
//   capacity: Integer
//   features: String (Or List<String> if driver supports)
// Relationship: (:TrainCar)-[:PART_OF_TRAIN]->(:Train)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'})
// CREATE (c:TrainCar {car_id: 'car_abc', ...})-[:PART_OF_TRAIN]->(t)
// Relationship: (:Route)-[rel:HAS_STOP]->(:Station)
// Relationship Properties on :HAS_STOP:
//   sequence_order: Integer
//   distance_from_previous_km: Float
//   typical_stop_duration_minutes: Integer
// Example Cypher CREATE:
// MATCH (r:Route {route_id: 'route_ne_corr'}), (s:Station {station_id: 'station_pvd'})
// CREATE (r)-[:HAS_STOP {sequence_order: 2, distance_from_previous_km: 70.5, ...}]->(s)
// Node Label: :Passenger
// Properties:
//   passenger_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   email: String (Constraint: UNIQUE, if not null)
//   phone_number: String (Constraint: UNIQUE, if not null)
//   date_of_birth: Date
//   loyalty_program_id: String
//   created_at: DateTime
// Example Cypher CREATE:
// CREATE (:Passenger {passenger_id: 'pass_pqr', first_name: 'Alice', ...})
// Node Label: :Booking
// Properties:
//   booking_id: String (Constraint: UNIQUE)
//   booking_datetime: DateTime
//   status: String
//   total_price: Float
//   currency_code: String
//   special_requests: String
// Relationships:
//   (:Passenger)-[:MADE_BOOKING]->(:Booking)
//   (:Booking)-[:FOR_TRIP]->(:ScheduledTrip)
// Example Cypher CREATE:
// MATCH (p:Passenger {passenger_id: 'pass_pqr'}), (sched:ScheduledTrip {schedule_id: 'sched_1122'})
// CREATE (p)-[:MADE_BOOKING]->(b:Booking {booking_id: 'book_zyx', ...})-[:FOR_TRIP]->(sched)
// Node Label: :Staff
// Properties:
//   staff_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   role: String
//   employee_number: String (Constraint: UNIQUE)
//   hire_date: Date
//   contact_email: String (Constraint: UNIQUE, if not null)
//   contact_phone: String
//   is_active: Boolean
// Relationship (Optional):
//   (:Staff)-[:BASED_AT]->(:Station)
// Example Cypher CREATE:
// CREATE (:Staff {staff_id: 'staff_mno', first_name: 'Bob', ...})
// OPTIONAL MATCH (s:Station {station_id: 'station_xyz'}) // If primary_station_id exists
// WITH s, staff_mno // Need to get the created staff node reference
// WHERE s IS NOT NULL
// CREATE (staff_mno)-[:BASED_AT]->(s)

[User] Can you help me find all staff members based at a specific station with station_id 'station_xyz', including the station details and platform information they are associated with?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status

[User] Can you filter the results to include only staff with the role of 'Manager' and platforms with status 'Operational'?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
WHERE stf.role = 'Manager' AND (p.status = 'Operational' OR p IS NULL)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status

[User] Can you sort the results by staff last name and platform number?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
WHERE stf.role = 'Manager' AND (p.status = 'Operational' OR p IS NULL)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status
ORDER BY stf.last_name, p.platform_number


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.maintenance_records ( record_id.text, asset_id.text, asset_type.text, maintenance_type.text, staff_id.text, start_datetime.timestamp, end_datetime.timestamp, description.text, cost.numeric, status.text )

[User] What is the detailed repair history of the equipment used by the staff with staff_id 'STAFF123' during maintenance tasks?

[Assistant] I'm sorry, but I can't provide information on the detailed repair history of equipment used by staff members. The data in the maintenance_records table only includes information about maintenance tasks, such as record_id, asset_id, maintenance type, and staff_id, but does not cover equipment repair histories.


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.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)

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

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


System:
You are an 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.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_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 character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)

[User] Find all invoices with status 'Paid' where the total amount is between 2000 and 5000. Show invoice number, total amount, issue date, and due date. Sort the results by issue date descending.

[Assistant] SELECT invoice_number, total_amount, issue_date, due_date FROM legal_services.invoices WHERE status = 'Paid' AND total_amount BETWEEN 2000 AND 5000 ORDER BY issue_date DESC;