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.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE smart_money_profit ( address.text, rank.numeric, profit.numeric, roi.numeric, realized_ratio.numeric, most_profit_token.text, last_trade_time.text, chain.text )
##Table Structure
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.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 )
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
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.in_game_items ( item_id.uuid, game_id.uuid, item_name.text, item_type.text, description.text, rarity.text, cost_currency.text, cost_amount.numeric, attributes.jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] What is the total revenue (sum of total_amount) and total amount_paid for each booking_source?

[Assistant]
SELECT booking_source,
       SUM(total_amount) AS total_revenue,
       SUM(amount_paid) AS total_paid
FROM reservations
GROUP BY booking_source;

[User] Only include sources where total revenue > 10000 and order by total_revenue descending.

[Assistant]
SELECT booking_source,
       SUM(total_amount) AS total_revenue,
       SUM(amount_paid) AS total_paid
FROM reservations
GROUP BY booking_source
HAVING SUM(total_amount) > 10000
ORDER BY total_revenue DESC;

[User] List the top 3 addresses with the highest profit on the Arbitrum chain, including roi and most_profit_token.

[Assistant] SELECT address, profit, roi, most_profit_token FROM smart_money_profit WHERE chain = 'Arbitrum' ORDER BY profit DESC LIMIT 3;

[User] Please add the realized_ratio and last_trade_time for each result.

[Assistant] SELECT address, profit, roi, most_profit_token, realized_ratio, last_trade_time FROM smart_money_profit WHERE chain = 'Arbitrum' ORDER BY profit DESC LIMIT 3;

[User] Show me the count of service orders for each distinct status.

[Assistant] SELECT status, COUNT(order_id) FROM hospitality_technology.service_orders GROUP BY status;

[User] Also, include the total quantity of items ordered for each status.

[Assistant] SELECT status, COUNT(order_id), SUM(quantity) FROM hospitality_technology.service_orders GROUP BY status;

[User] Show all in-game items (name, rarity) that belong to games where the average session score across all sessions for that game is greater than 300.

[Assistant] SELECT ii.item_name, ii.rarity FROM gaming_technology.in_game_items AS ii WHERE ii.game_id IN (SELECT game_id FROM gaming_technology.game_sessions GROUP BY game_id HAVING AVG(score) > 300);

[User] Additionally, include the total number of sessions for each of these items' games.

[Assistant] SELECT ii.item_name, ii.rarity, gs.total_sessions FROM gaming_technology.in_game_items AS ii JOIN (SELECT game_id, COUNT(*) AS total_sessions, AVG(score) AS avg_score FROM gaming_technology.game_sessions GROUP BY game_id) AS gs ON ii.game_id = gs.game_id WHERE gs.avg_score > 300;

[User] List all documents of type 'Pleading' uploaded between '2023-01-01' and '2023-12-31', including their name, case ID, and upload timestamp.

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

[User] List all unique combinations of plan_id and group_number, and show the number of policies for each combination.

[Assistant] SELECT plan_id, group_number, COUNT(*) AS policy_count FROM healthcare.patient_insurance GROUP BY plan_id, group_number;

[User] Only show combinations where the policy_count is greater than 3.

[Assistant] SELECT plan_id, group_number, COUNT(*) AS policy_count FROM healthcare.patient_insurance GROUP BY plan_id, group_number HAVING COUNT(*) > 3;

[User] Show the agency names and the number of active services they currently offer. List only those agencies with more than 2 active services.

[Assistant]
SELECT a.agency_name, COUNT(s.service_id) AS active_service_count
FROM government_services.agencies a
JOIN government_services.services s ON a.agency_id = s.agency_id
WHERE s.is_active = TRUE
GROUP BY a.agency_name
HAVING COUNT(s.service_id) > 2;

[User] Show me the medication_id, medication_name, and manufacturer for all medications where the generic_name contains the word 'azole'.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE generic_name ILIKE '%azole%';

[User] Can you also include the ndc_code and only show medications where the manufacturer field is not null?

[Assistant] SELECT medication_id, medication_name, manufacturer, ndc_code FROM healthcare.medications WHERE generic_name ILIKE '%azole%' AND manufacturer IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
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 character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
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 )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
##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 )
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
##Table Structure
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )

[User] Show me the total count and sum of amounts for spent and unspent UTXOs for each asset, including the asset name and symbol.

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol, u.spent, COUNT(*) AS utxo_count, SUM(u.amount) AS total_amount
FROM trading_platform.assets a
LEFT JOIN trading_platform.utxos u
  ON a.asset_id = u.transaction_id
GROUP BY a.asset_id, a.name, a.symbol, u.spent
ORDER BY a.asset_id, u.spent;

[User] I'd like to see only assets where the sum of amounts for spent UTXOs is at least 100. Also, show only the spent UTXOs.

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol, SUM(u.amount) AS spent_total_amount
FROM trading_platform.assets a
JOIN trading_platform.utxos u ON a.asset_id = u.transaction_id
WHERE u.spent = true
GROUP BY a.asset_id, a.name, a.symbol
HAVING SUM(u.amount) >= 100
ORDER BY spent_total_amount DESC;

[User] For each relationship type among policy beneficiaries, count how many beneficiaries exist of that type. Provide relationship and count, ordered by count descending.

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

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

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

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

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

[User] For each department, what is the highest priced available service? Please show department, service_name, and price.

[Assistant] SELECT department, service_name, price FROM hospitality_technology.services WHERE is_available = TRUE AND (department, price) IN (SELECT department, MAX(price) FROM hospitality_technology.services WHERE is_available = TRUE GROUP BY department);

[User] The SQL failed due to using a tuple in the IN clause. Can you rewrite it in a way that's compatible with most databases?

[Assistant] SELECT s.department, s.service_name, s.price FROM hospitality_technology.services s JOIN (SELECT department, MAX(price) AS max_price FROM hospitality_technology.services WHERE is_available = TRUE GROUP BY department) sub ON s.department = sub.department AND s.price = sub.max_price WHERE s.is_available = TRUE;

[User] Now, only show departments where the maximum price is over 150.

[Assistant] SELECT s.department, s.service_name, s.price FROM hospitality_technology.services s JOIN (SELECT department, MAX(price) AS max_price FROM hospitality_technology.services WHERE is_available = TRUE GROUP BY department) sub ON s.department = sub.department AND s.price = sub.max_price WHERE s.is_available = TRUE AND sub.max_price > 150;

[User] Find all pairs of developers who share the exact same founded_year but are from different countries. Show both developer names, their countries, and the founded_year.

[Assistant]
SELECT d1.name AS developer1_name, d1.country AS country1, d2.name AS developer2_name, d2.country AS country2, d1.founded_year
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.founded_year = d2.founded_year
 AND d1.developer_id < d2.developer_id
 AND d1.country <> d2.country;

[User] Can you also include the website of each developer in the output?

[Assistant]
SELECT d1.name AS developer1_name, d1.country AS country1, d1.website AS developer1_website,
       d2.name AS developer2_name, d2.country AS country2, d2.website AS developer2_website, d1.founded_year
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.founded_year = d2.founded_year
 AND d1.developer_id < d2.developer_id
 AND d1.country <> d2.country;

[User] List all premium payments that have a status of 'pending'. Show the payment_id, policy_id, customer_id, and amount_paid.

[Assistant] SELECT payment_id, policy_id, customer_id, amount_paid FROM insurance.premium_payments WHERE status = 'pending';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )
CREATE TABLE transportation.bookings (
    booking_id character varying(64) NOT NULL,  -- unique identifier for the booking
    passenger_id character varying(64) NOT NULL, -- identifier of the passenger making the booking
    trip_id character varying(64) NOT NULL, -- identifier of the trip being booked
    seat_number character varying(16), -- assigned seat number (if applicable)
    booking_time timestamp with time zone NOT NULL, -- time when the booking was made
    status character varying(32) NOT NULL, -- e.g., Confirmed, Cancelled, Pending Payment
    fare numeric(10, 2) NOT NULL, -- price paid for the booking
    payment_transaction_id character varying(128), -- reference to the payment transaction
    special_requests text, -- any special requests from the passenger
    PRIMARY KEY (booking_id)
)
##Table Structure
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)
##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.medical_records ( record_id.text, patient_id.text, appointment_id.text, doctor_id.text, record_date.timestamp, chief_complaint.text, present_illness_history.text, past_medical_history.text, physical_examination_notes.text, assessment.text, treatment_plan.text, vitals.json, created_at.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##Table Structure
CREATE TABLE blockchain.blocks (
    block_id character varying(64) NOT NULL,  -- unique identifier for the block
    previous_block_id character varying(64), -- identifier of the previous block
    timestamp timestamp NOT NULL, -- time when the block was mined
    nonce integer NOT NULL, -- nonce value used in the proof of work
    merkle_root character varying(128) NOT NULL, -- root of the Merkle tree for transactions
    difficulty integer NOT NULL, -- difficulty level of the block
    PRIMARY KEY (block_id)
)
##Table Structure
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)

[User] List all completed trips, showing the trip ID, the names of the origin and destination locations for the trip, and the actual arrival time.

[Assistant] SELECT t.trip_id, loc_origin.name AS origin_location_name, loc_dest.name AS destination_location_name, t.actual_arrival FROM transportation.trips t JOIN locations loc_origin ON t.origin_location_id = loc_origin.location_id JOIN locations loc_dest ON t.destination_location_id = loc_dest.location_id WHERE t.status = 'Completed';

[User] Show me all loans with a term longer than 36 months, including their loan_id, account_id, and principal_amount.

[Assistant] SELECT loan_id, account_id, principal_amount FROM financial_services.loans WHERE term_months > 36;

[User] Can you also include their origination_date and current_principal_balance?

[Assistant] SELECT loan_id, account_id, principal_amount, current_principal_balance, origination_date FROM financial_services.loans WHERE term_months > 36;

[User] Filter to only show loans that are not yet matured (maturity_date > CURRENT_DATE).

[Assistant] SELECT loan_id, account_id, principal_amount, current_principal_balance, origination_date FROM financial_services.loans WHERE term_months > 36 AND maturity_date > CURRENT_DATE;

[User] Retrieve all transactions where the total value of token transfers in that transaction exceeds the Ether value of the transaction itself. Include transaction_id, ether_value, and total_token_value.

[Assistant]
SELECT
  t.transaction_id,
  t.value AS ether_value,
  SUM(tt.value) AS total_token_value
FROM web3.transactions t
JOIN web3.token_transfers tt
  ON t.transaction_id = tt.transaction_id
GROUP BY
  t.transaction_id,
  t.value
HAVING
  SUM(tt.value) > t.value;

[User] Show all medical records with the record_id, record_date, the patient's insurance policy_number, and the doctor's ID, for records linked to a currently active insurance policy.

[Assistant]
SELECT mr.record_id, mr.record_date, pi.policy_number, mr.doctor_id
FROM healthcare.medical_records mr
INNER JOIN healthcare.patient_insurance pi ON mr.patient_id = pi.patient_id
WHERE pi.expiration_date IS NULL OR pi.expiration_date >= CURRENT_DATE;

[User] Retrieve the block ID, timestamp, current block's difficulty, and the difficulty of the *previous* block for all blocks where the current block's difficulty is strictly greater than the previous block's difficulty.

[Assistant] SELECT b1.block_id, b1.timestamp, b1.difficulty AS current_difficulty, b2.difficulty AS previous_difficulty FROM blockchain.blocks b1 JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id WHERE b1.difficulty > b2.difficulty;

[User] How many messages currently have a media file attached?

[Assistant] SELECT COUNT(*) FROM social_media.messages WHERE media_url IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
##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.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_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.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) )
##Table Structure
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )

[User] List all documents which have a version greater than 2, along with the case number and name.

[Assistant]
SELECT d.document_id, d.document_name, d.version, c.case_number, c.case_name
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id
WHERE d.version > 2;

[User] Show all cases that are currently open and have a client whose status is prospect. Include the case_number, the case_name, and the client's full name.

[Assistant]
SELECT cs.case_number, cs.case_name, cl.first_name || ' ' || cl.last_name AS client_full_name
FROM legal_services.cases cs
JOIN legal_services.clients cl ON cs.client_id = cl.client_id
WHERE cs.status = 'Open' AND cl.status = 'prospect';

[User] List all trips including the name of the origin location and the name of the destination location.

[Assistant] SELECT t.trip_id, origin.name AS origin_location_name, destination.name AS destination_location_name FROM transportation.trips t JOIN transportation.locations origin ON t.origin_location_id = origin.location_id JOIN transportation.locations destination ON t.destination_location_id = destination.location_id;

[User] Show me all maintenance logs for 'Engine Repair' service type where the cost is greater than 400, including the vehicle ID, service date, cost, and mechanic name.

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Engine Repair' AND cost > 400;

[User] Which bed types are offered in each property and how many different room types are associated with each bed type?

[Assistant] SELECT property_id, bed_type, COUNT(DISTINCT room_type_id) AS room_type_count FROM hospitality_technology.room_types GROUP BY property_id, bed_type;

[User] Now, show only bed types that are available for at least 3 different room types within the same property.

[Assistant] SELECT property_id, bed_type, COUNT(DISTINCT room_type_id) AS room_type_count FROM hospitality_technology.room_types GROUP BY property_id, bed_type HAVING COUNT(DISTINCT room_type_id) >= 3;

[User] How many customers have a non-null phone number in your system?

[Assistant] SELECT COUNT(*) FROM insurance.customers WHERE phone_number IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
##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.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
##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 )
##Table Structure
CREATE TABLE financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
##Table Structure
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
##Table Structure
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
##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] Show all messages that include a media attachment, along with the sender's user ID and the conversation ID.

[Assistant] SELECT message_id, sender_user_id, conversation_id, media_url, media_type, sent_at FROM social_media.messages WHERE media_url IS NOT NULL AND media_url <> '';

[User] Only include messages sent after May 1st, 2024 and show the media_type as well.

[Assistant] SELECT message_id, sender_user_id, conversation_id, media_url, media_type, sent_at FROM social_media.messages WHERE media_url IS NOT NULL AND media_url <> '' AND sent_at > '2024-05-01';

[User] For each appointment scheduled for '2024-08-15', return the patient's full name, the doctor's ID, and the appointment time.

[Assistant]
SELECT p.first_name, p.last_name, a.doctor_id, a.appointment_time
FROM healthcare.appointments a
JOIN healthcare.patients p ON a.patient_id = p.patient_id
WHERE DATE(a.appointment_time) = '2024-08-15' AND a.status = 'scheduled';

[User] Show the full name of each manager and the average commission rate of the agents who report directly to them. Only include managers who have at least one reporting agent.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, AVG(T1.commission_rate) AS average_agent_commission_rate FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id GROUP BY T2.agent_id, T2.first_name, T2.last_name

[User] Filter the results to only show managers whose average agent commission rate is above 0.12.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, AVG(T1.commission_rate) AS average_agent_commission_rate FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id GROUP BY T2.agent_id, T2.first_name, T2.last_name HAVING AVG(T1.commission_rate) > 0.12

[User] Show me the total quantity traded and total amount for each security, identified by its ticker symbol, for trades in the last month.

[Assistant] SELECT T2.ticker_symbol, SUM(T1.quantity), SUM(T1.total_amount) FROM financial_services.trades AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.trade_timestamp >= DATE('now', '-1 month') GROUP BY 1

[User] Can you also show the average price per unit and filter to only include securities where the total quantity traded is greater than 5000?

[Assistant] SELECT T2.ticker_symbol, SUM(T1.quantity), SUM(T1.total_amount), AVG(T1.price_per_unit) FROM financial_services.trades AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.trade_timestamp >= DATE('now', '-1 month') GROUP BY 1 HAVING SUM(T1.quantity) > 5000

[User] For each claim, count the number of documents linked to it. Show claim_id and document_count for claims that have more than 3 documents.

[Assistant]
SELECT claim_id, COUNT(*) AS document_count
FROM insurance.claim_documents
group by claim_id
HAVING COUNT(*) > 3;

[User] Please also show the incident date for those claims.

[Assistant]
SELECT c.claim_id, c.incident_date, COUNT(d.document_id) AS document_count
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
GROUP BY c.claim_id, c.incident_date
HAVING COUNT(d.document_id) > 3;

[User] For each policy, find the latest payment date. Show the policy_id and the maximum payment_date.

[Assistant] SELECT policy_id, MAX(payment_date) AS latest_payment_date FROM insurance.premium_payments GROUP BY policy_id;

[User] Restrict the results to only show policies where the latest payment date was before '2024-01-01'.

[Assistant] SELECT policy_id, MAX(payment_date) AS latest_payment_date FROM insurance.premium_payments GROUP BY policy_id HAVING MAX(payment_date) < '2024-01-01';

[User] List the first name, last name, specialization, and the name of the law firm for all lawyers hired before January 1, 2020.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T1.specialization ,  T2.firm_name FROM legal_services.lawyers AS T1 JOIN legal_services.law_firms AS T2 ON T1.firm_id  =  T2.firm_id WHERE T1.hire_date < '2020-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 web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens (
    token_id 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)
)
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
##Table Structure
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )

[User] For each user, count the number of distinct smart contracts they have called. Return user_id, username, and contract_count, ordered by contract_count descending.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(DISTINCT tx.to_address) AS contract_count
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
JOIN web3.transactions tx ON w.address = tx.from_address
JOIN web3.contracts c ON tx.to_address = c.address
GROUP BY u.user_id, u.username
ORDER BY contract_count DESC;

[User] Count the total number of public posts.

[Assistant] SELECT COUNT(*) FROM social_media.posts WHERE visibility = 'public';

[User] Show me all payments made with a credit card (payment_method = 'credit_card') where the amount is greater than $500, including the reservation ID and payment timestamp.

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp FROM hospitality_technology.payments WHERE payment_method = 'credit_card' AND amount > 500 ORDER BY payment_timestamp DESC;

[User] Now, include only payments that were processed by staff members with ID starting with 'STAFF1' and show the card type used.

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp, card_type FROM hospitality_technology.payments WHERE payment_method = 'credit_card' AND amount > 500 AND staff_id_processed LIKE 'STAFF1%' ORDER BY payment_timestamp DESC;

[User] Show me pairs of wallets that belong to the same user, listing the wallet_id, user_id, address, and created_at for the earlier and later wallet in each pair.

[Assistant]
SELECT w1.user_id,
       w1.wallet_id AS earlier_wallet,
       w1.address AS earlier_address,
       w1.created_at AS earlier_created_at,
       w2.wallet_id AS later_wallet,
       w2.address AS later_address,
       w2.created_at AS later_created_at
FROM trading_platform.wallets w1
JOIN trading_platform.wallets w2
  ON w1.user_id = w2.user_id
 AND w1.created_at < w2.created_at;

[User] Now only include pairs where the later wallet was created more than 30 days after the earlier one.

[Assistant]
SELECT w1.user_id,
       w1.wallet_id AS earlier_wallet,
       w1.address AS earlier_address,
       w1.created_at AS earlier_created_at,
       w2.wallet_id AS later_wallet,
       w2.address AS later_address,
       w2.created_at AS later_created_at
FROM trading_platform.wallets w1
JOIN trading_platform.wallets w2
  ON w1.user_id = w2.user_id
 AND w2.created_at > w1.created_at + INTERVAL '30 days';

[User] Find all pairs of vehicles that have the same make and model but different fuel types. For each pair, display the first vehicle_id, the second vehicle_id, make, model, fuel_type of the first as fuel_type1 and of the second as fuel_type2.

[Assistant] SELECT v1.vehicle_id AS vehicle1_id, v2.vehicle_id AS vehicle2_id, v1.make, v1.model, v1.fuel_type AS fuel_type1, v2.fuel_type AS fuel_type2 FROM transportation.vehicles v1 JOIN transportation.vehicles v2 ON v1.make = v2.make AND v1.model = v2.model AND v1.vehicle_id < v2.vehicle_id AND v1.fuel_type <> v2.fuel_type;

[User] Show a list of all routes including their route number, type, distance in km, and estimated duration in minutes.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes;

[User] Filter this list to only show routes of type 'Express'.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes
WHERE
  type = 'Express';

[User] Sort the results by distance in descending order and limit to the top 5.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes
WHERE
  type = 'Express'
ORDER BY
  distance_km DESC
LIMIT 5;

[User] Add the description and a column 'duration_per_km' showing the duration per kilometer.

[Assistant]
SELECT
  route_number,
  type,
  description,
  distance_km,
  estimated_duration_minutes,
  CAST(estimated_duration_minutes AS NUMERIC) / NULLIF(distance_km, 0) AS duration_per_km
FROM transportation.routes
WHERE
  type = 'Express'
ORDER BY
  distance_km DESC
LIMIT 5;

[User] How many customers were created in 2023?

[Assistant]
SELECT COUNT(*)
FROM insurance.customers
WHERE EXTRACT(YEAR FROM created_at) = 2023;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE gaming_technology.player_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)
)
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text, user_id text, action text, details text, logged_at timestamp )
##Table Structure
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
##Table Structure
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"
##Table Structure
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 )
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )

[User] Calculate for each player the timespan between their earliest and latest achievement unlocks.

[Assistant]
SELECT pa_min.player_id,
       pa_max.max_time - pa_min.min_time AS span
FROM (
  SELECT player_id,
         MIN(unlocked_at) AS min_time
  FROM gaming_technology.player_achievements
  GROUP BY player_id
) pa_min
JOIN (
  SELECT player_id,
         MAX(unlocked_at) AS max_time
  FROM gaming_technology.player_achievements
  GROUP BY player_id
) pa_max
  ON pa_min.player_id = pa_max.player_id;

[User] Exclude players who only have one achievement.

[Assistant]
WITH extremes AS (
  SELECT player_id,
         MIN(unlocked_at) AS min_time,
         MAX(unlocked_at) AS max_time,
         COUNT(*) AS cnt
  FROM gaming_technology.player_achievements
  GROUP BY player_id
  HAVING COUNT(*) > 1
)
SELECT player_id,
       max_time - min_time AS span
FROM extremes;

[User] Also only keep players where the span is greater than 30 days.

[Assistant]
WITH extremes AS (
  SELECT player_id,
         MIN(unlocked_at) AS min_time,
         MAX(unlocked_at) AS max_time,
         COUNT(*) AS cnt
  FROM gaming_technology.player_achievements
  GROUP BY player_id
  HAVING COUNT(*) > 1
)
SELECT player_id,
       max_time - min_time AS span
FROM extremes
WHERE max_time - min_time > INTERVAL '30 days';

[User] List user IDs with approved KYC status and the addresses of their wallets.

[Assistant] SELECT DISTINCT w.user_id, w.address FROM trading_platform.wallets w JOIN trading_platform.kyc_audit k ON w.user_id = k.user_id WHERE k.status = 'approved';

[User] From that list, also show the total number of unspent UTXOs associated with each wallet address.

[Assistant] SELECT w.user_id, w.address, COUNT(u.utxo_id) AS unspent_utxo_count FROM trading_platform.wallets w JOIN trading_platform.kyc_audit k ON w.user_id = k.user_id JOIN trading_platform.utxos u ON w.address = u.address WHERE k.status = 'approved' AND u.spent = FALSE GROUP BY w.user_id, w.address;

[User] Find all service locations in the city of 'Albany' that are accessible. Show their IDs, names, and contact phone numbers along with their address.

[Assistant] SELECT location_id, location_name, contact_phone, address FROM government_services.service_locations WHERE city = 'Albany' AND is_accessible = TRUE;

[User] What is the total USD value of tokens held by CEX addresses on the 'Ethereum' chain for the most recent snapshot time?

[Assistant]
WITH latest_snapshot AS (
  SELECT max(snapshot_time) as max_time
  FROM cex_token_balance
)
SELECT sum(usd_value)
FROM cex_token_balance ctb
JOIN latest_snapshot ls ON ctb.snapshot_time = ls.max_time
WHERE chain = 'Ethereum';

[User] Can you break down this total value by `exchange`, showing the top 3 exchanges by total USD value for that same latest snapshot on Ethereum?

[Assistant]
WITH latest_snapshot AS (
  SELECT max(snapshot_time) as max_time
  FROM cex_token_balance
)
SELECT exchange, sum(usd_value) as total_usd_value
FROM cex_token_balance ctb
JOIN latest_snapshot ls ON ctb.snapshot_time = ls.max_time
WHERE chain = 'Ethereum'
GROUP BY exchange
ORDER BY total_usd_value DESC
LIMIT 3;

[User] What is the average quantity_dispensed per route for prescriptions with start_date in 2024? Return route and avg_quantity.

[Assistant]
SELECT route,
       AVG(quantity_dispensed) AS avg_quantity
FROM healthcare.prescriptions
WHERE start_date >= '2024-01-01'
GROUP BY route;

[User] Refine to only include routes with more than 20 prescriptions and round avg_quantity to two decimal places.

[Assistant]
SELECT route,
       ROUND(AVG(quantity_dispensed), 2) AS avg_quantity
FROM healthcare.prescriptions
WHERE start_date >= '2024-01-01'
GROUP BY route
HAVING COUNT(*) > 20;

[User] Which claim ID has the highest number of documents associated with it?

[Assistant] SELECT claim_id FROM insurance.claim_documents GROUP BY claim_id ORDER BY COUNT(*) DESC LIMIT 1;

[User] Show me the file name, document type, file size, and uploaded time for all documents belonging to that claim ID.

[Assistant] SELECT file_name, document_type, file_size_bytes, uploaded_at FROM insurance.claim_documents WHERE claim_id = (SELECT claim_id FROM insurance.claim_documents GROUP BY claim_id ORDER BY COUNT(*) DESC LIMIT 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 social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )
##Table Structure
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )

[User] Show me all users who have liked both a post and a comment. Please include their user IDs, the post IDs, and the comment IDs.

[Assistant]
SELECT DISTINCT l1.user_id, l1.post_id, l2.comment_id
FROM social_media.likes l1
JOIN social_media.likes l2 ON l1.user_id = l2.user_id
WHERE l1.post_id IS NOT NULL AND l2.comment_id IS NOT NULL;

[User] Add the timestamp when they liked the comment.

[Assistant]
SELECT DISTINCT l1.user_id, l1.post_id, l2.comment_id, l2.created_at AS comment_liked_at
FROM social_media.likes l1
JOIN social_media.likes l2 ON l1.user_id = l2.user_id
WHERE l1.post_id IS NOT NULL AND l2.comment_id IS NOT NULL;

[User] List all booking IDs and their status for bookings that have a special request recorded.

[Assistant]
SELECT booking_id, status
FROM transportation.bookings
WHERE special_requests IS NOT NULL;

[User] Also show passenger_id and the booking_time for these bookings. Only include bookings where the special request contains the word 'meal'.

[Assistant]
SELECT booking_id, passenger_id, status, booking_time
FROM transportation.bookings
WHERE special_requests ILIKE '%meal%';

[User] Order the results by booking_time in descending order and limit the output to the 10 most recent matches.

[Assistant]
SELECT booking_id, passenger_id, status, booking_time
FROM transportation.bookings
WHERE special_requests ILIKE '%meal%'
ORDER BY booking_time DESC
LIMIT 10;

[User] For each client, list their first and last invoice numbers along with the corresponding issue_dates.

[Assistant]
SELECT first_inv.client_id,
       first_inv.invoice_number   AS first_invoice,
       first_inv.issue_date       AS first_date,
       last_inv.invoice_number    AS last_invoice,
       last_inv.issue_date        AS last_date
FROM legal_services.invoices first_inv
JOIN legal_services.invoices last_inv
  ON first_inv.client_id = last_inv.client_id
 AND first_inv.issue_date = (
       SELECT MIN(issue_date)
       FROM legal_services.invoices
       WHERE client_id = first_inv.client_id
     )
 AND last_inv.issue_date = (
       SELECT MAX(issue_date)
       FROM legal_services.invoices
       WHERE client_id = last_inv.client_id
     );

[User] Sort the output by client_id.

[Assistant]
SELECT first_inv.client_id,
       first_inv.invoice_number   AS first_invoice,
       first_inv.issue_date       AS first_date,
       last_inv.invoice_number    AS last_invoice,
       last_inv.issue_date        AS last_date
FROM legal_services.invoices first_inv
JOIN legal_services.invoices last_inv
  ON first_inv.client_id = last_inv.client_id
 AND first_inv.issue_date = (
       SELECT MIN(issue_date)
       FROM legal_services.invoices
       WHERE client_id = first_inv.client_id
     )
 AND last_inv.issue_date = (
       SELECT MAX(issue_date)
       FROM legal_services.invoices
       WHERE client_id = last_inv.client_id
     )
ORDER BY first_inv.client_id;

[User] Find the latest three posts with their content and posting users' full names.

[Assistant]
SELECT p.content, u.full_name, p.created_at
FROM social_media.posts p
JOIN social_media.users u ON p.user_id = u.user_id
ORDER BY p.created_at DESC
LIMIT 3;

[User] What is the average number of game sessions started per hour of the day (0-23), considering all recorded sessions? Show the hour and the average count.

[Assistant] SELECT EXTRACT(HOUR FROM start_time) AS session_hour, COUNT(*)::NUMERIC / COUNT(DISTINCT DATE_TRUNC('day', start_time)) AS average_sessions FROM gaming_technology.game_sessions GROUP BY 1 ORDER BY 1;

[User] Which hour of the day typically sees the most sessions based on this average? Just show the hour.

[Assistant] SELECT EXTRACT(HOUR FROM start_time) AS session_hour FROM gaming_technology.game_sessions GROUP BY 1 ORDER BY COUNT(*)::NUMERIC / COUNT(DISTINCT DATE_TRUNC('day', start_time)) DESC LIMIT 1;

[User] Instead of the average, show the total number of sessions started for each hour of the day (0-23) across *all* recorded sessions.

[Assistant] SELECT EXTRACT(HOUR FROM start_time) AS session_hour, COUNT(*) AS total_sessions FROM gaming_technology.game_sessions GROUP BY 1 ORDER BY 1;

[User] Only show hours with more than 500 total sessions, and order the results by the total count in descending order.

[Assistant] SELECT EXTRACT(HOUR FROM start_time) AS session_hour, COUNT(*) AS total_sessions FROM gaming_technology.game_sessions GROUP BY 1 HAVING COUNT(*) > 500 ORDER BY total_sessions DESC;

[User] List all players who acquired any items in the last 30 days. Show their username, the item name, and the exact date and time of acquisition.

[Assistant] SELECT T1.username, T3.item_name, T2.acquired_at FROM players AS T1 INNER JOIN player_inventory AS T2 ON T1.player_id = T2.player_id INNER JOIN items AS T3 ON T2.item_id = T3.item_id WHERE T2.acquired_at >= CURRENT_TIMESTAMP - INTERVAL '30 days';

[User] Only show items of 'Weapon' type acquired by these players.

[Assistant] SELECT T1.username, T3.item_name, T2.acquired_at FROM players AS T1 INNER JOIN player_inventory AS T2 ON T1.player_id = T2.player_id INNER JOIN items AS T3 ON T2.item_id = T3.item_id WHERE T2.acquired_at >= CURRENT_TIMESTAMP - INTERVAL '30 days' AND T3.item_type = 'Weapon';


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)
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )
##Table Structure
CREATE TABLE blockchain.smart_contracts ( contract_id text, creator_address text, code text, timestamp timestamp )
##Table Structure
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )

[User] Can you retrieve the total number of train cars for each train in the database?

[Assistant]
MATCH (t:Train)<-[:PART_OF_TRAIN]-(tc:TrainCar)
RETURN t.train_id, t.train_number, COUNT(tc) AS total_cars
ORDER BY t.train_id

[User] Find the top 3 staff members who have responded to the most public reviews. Include their staff_id, first_name, last_name, and the count of responses.

[Assistant]
SELECT
  s.staff_id,
  s.first_name,
  s.last_name,
  COUNT(*) AS response_count
FROM hospitality_technology.staff AS s
JOIN hospitality_technology.reviews AS r
  ON s.staff_id = r.response_staff_id
WHERE r.is_public = TRUE
  AND r.response_staff_id IS NOT NULL
GROUP BY s.staff_id, s.first_name, s.last_name
ORDER BY response_count DESC
LIMIT 3;

[User] Show me all smart contracts created by addresses that have created more than 3 contracts, along with the total number of contracts each creator has made.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(*) OVER (PARTITION BY sc.creator_address) AS total_contracts
FROM blockchain.smart_contracts sc
WHERE sc.creator_address IN (
    SELECT creator_address
    FROM blockchain.smart_contracts
    GROUP BY creator_address
    HAVING COUNT(*) > 3
)
ORDER BY total_contracts DESC;

[User] Now filter these results to only show contracts created in the last 6 months.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(*) OVER (PARTITION BY sc.creator_address) AS total_contracts
FROM blockchain.smart_contracts sc
WHERE sc.creator_address IN (
    SELECT creator_address
    FROM blockchain.smart_contracts
    GROUP BY creator_address
    HAVING COUNT(*) > 3
)
AND sc.timestamp >= NOW() - INTERVAL '6 months'
ORDER BY total_contracts DESC;

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)
##Table Structure
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
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.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)
)
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )
##Table Structure
CREATE TABLE insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )

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

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

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

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

[User] For each vehicle, show the first and last fueling events including their timestamps and the quantities refueled.

[Assistant]
WITH first_last AS (
  SELECT
    vehicle_id,
    MIN(log_timestamp) AS first_time,
    MAX(log_timestamp) AS last_time
  FROM transportation.fuel_logs
  GROUP BY vehicle_id
)
SELECT
  f1.vehicle_id,
  f1.log_timestamp AS first_refuel_time,
  f1.quantity AS first_quantity,
  f2.log_timestamp AS last_refuel_time,
  f2.quantity AS last_quantity
FROM first_last fl
JOIN transportation.fuel_logs f1
  ON fl.vehicle_id = f1.vehicle_id
  AND fl.first_time = f1.log_timestamp
JOIN transportation.fuel_logs f2
  ON fl.vehicle_id = f2.vehicle_id
  AND fl.last_time = f2.log_timestamp;

[User] How many UTXOs have the 'spent' flag set to false?

[Assistant]
SELECT COUNT(*) AS unspent_utxo_count
FROM trading_platform.utxos
WHERE spent = false;

[User] Show the vehicle ID and the total number of fuel logs recorded for each vehicle.

[Assistant] SELECT vehicle_id , count(*) FROM transportation.fuel_logs GROUP BY vehicle_id

[User] Filter this list to only show vehicles with more than 5 fuel log entries.

[Assistant] SELECT vehicle_id , count(*) FROM transportation.fuel_logs GROUP BY vehicle_id HAVING count(*) > 5

[User] Show the agent_id and the total number of policies managed by each agent, but only include agents with at least 5 policies.

[Assistant] SELECT agent_id, COUNT(*) AS policy_count FROM insurance.policies GROUP BY agent_id HAVING COUNT(*) >= 5;

[User] For those agents, can you also show the total combined premium_amount across all their policies, labeled as total_premium?

[Assistant] SELECT agent_id, COUNT(*) AS policy_count, SUM(premium_amount) AS total_premium FROM insurance.policies GROUP BY agent_id 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 hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
##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.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
##Table Structure
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
##Table Structure
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
##Table Structure
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )

[User] Find all pairs of overlapping reservations for the same room. Show the two reservation IDs, room_id, and both reservations' check-in and check-out dates.

[Assistant] SELECT r1.reservation_id AS reservation1_id, r2.reservation_id AS reservation2_id, r1.room_id, r1.check_in_date AS reservation1_check_in, r1.check_out_date AS reservation1_check_out, r2.check_in_date AS reservation2_check_in, r2.check_out_date AS reservation2_check_out FROM hospitality_technology.reservations r1 JOIN hospitality_technology.reservations r2 ON r1.room_id = r2.room_id AND r1.reservation_id < r2.reservation_id AND r1.check_in_date < r2.check_out_date AND r2.check_in_date < r1.check_out_date;

[User] List each service_type and the number of maintenance logs performed for that type, only including service_types with more than 10 records.

[Assistant]
SELECT service_type,
       COUNT(*) AS log_count
FROM transportation.maintenance_logs
GROUP BY service_type
HAVING COUNT(*) > 10;

[User] Now include the average cost of each service_type and order the results by average cost descending.

[Assistant]
SELECT service_type,
       COUNT(*)    AS log_count,
       AVG(cost)   AS avg_cost
FROM transportation.maintenance_logs
GROUP BY service_type
HAVING COUNT(*) > 10
ORDER BY avg_cost DESC;

[User] List the full names of patients who have had at least one appointment scheduled with a doctor, along with the medication names they have been prescribed. Please include only patients who have both an appointment and at least one corresponding medication.

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, m.medication_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.medications m ON m.medication_id IN (
    SELECT medication_id FROM healthcare.medications
) -- Placeholder, since no direct prescription table or mapping is given
WHERE a.status = 'scheduled';

[User] Actually, could you also include the appointment time in the results?

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, a.appointment_time, m.medication_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.medications m ON m.medication_id IN (
    SELECT medication_id FROM healthcare.medications
)
WHERE a.status = 'scheduled';

[User] The medication names are not matching with the appointments, I think there is no direct link. Can you just give me, for each patient who has at least one scheduled appointment, all their appointment times and their last names, without including medication info?

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, a.appointment_time
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
WHERE a.status = 'scheduled';

[User] Find claims where the estimated loss is greater than the average estimated loss for claims with a status of 'Closed'. Show the claim ID, incident date, estimated loss, and status.

[Assistant] SELECT claim_id, incident_date, estimated_loss, status FROM insurance.claims WHERE estimated_loss > (SELECT AVG(estimated_loss) FROM insurance.claims WHERE status = 'Closed')

[User] Show me the total payment amount and number of payments for each service.

[Assistant] SELECT service_id, SUM(amount) AS total_amount, COUNT(*) AS payment_count FROM government_services.payments GROUP BY service_id;

[User] Only include services where more than 3 payments have been made.

[Assistant] SELECT service_id, SUM(amount) AS total_amount, COUNT(*) AS payment_count FROM government_services.payments GROUP BY service_id HAVING COUNT(*) > 3;

[User] Show the names, symbols, and types of all assets whose symbol starts with the letter 'B'.

[Assistant]
SELECT name, symbol, type
FROM trading_platform.assets
WHERE symbol LIKE 'B%';

[User] List the tag names and creation dates for all hashtags created on June 12, 2024.

[Assistant] SELECT tag_name, created_at FROM social_media.hashtags WHERE created_at::date = '2024-06-12';

[User] Please also include the hashtag IDs and order by tag name alphabetically.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE created_at::date = '2024-06-12' ORDER BY tag_name ASC;

[User] List all details for medications whose description contains the word 'pain'.

[Assistant] SELECT * FROM healthcare.medications WHERE description LIKE '%pain%';