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
// Use Hashes for platform details. Key format: platform:<platform_id>
// HSET platform:plat_123 platform_id "plat_123" station_id "station_xyz" platform_number "1A" track_number "T1" status "Operational" length_meters 250.50 accessible 1

// To link platforms to stations (optional):
// SADD station:station_xyz:platforms platform:plat_123 platform:plat_456
// Use Hashes for train details. Key format: train:<train_id>
// HSET train:train_789 train_id "train_789" train_number "Acela 2151" model "Siemens Velaro" ... status "Active" ...

// To find train by train_number (optional index):
// SET train_number:"Acela 2151" train:train_789
// Use Hashes for car details. Key format: car:<car_id>
// HSET car:car_abc car_id "car_abc" train_id "train_789" car_number "C3" car_type "Passenger" class "Business" capacity 60 features "WiFi,Power Outlet"

// To link cars to trains (optional):
// SADD train:train_789:cars car:car_abc car:car_def
// Use Hashes for details. Key format: route_station:<route_station_id>
// HSET route_station:rs_ne_1 route_station_id "rs_ne_1" route_id "route_ne_corr" station_id "station_bos" sequence_order 1 ...

// To find stops for a route, use a Sorted Set (score by sequence_order):
// ZADD route:route_ne_corr:stops 1 route_station:rs_ne_1
// ZADD route:route_ne_corr:stops 2 route_station:rs_ne_2
// Use Hashes for schedule details. Key format: schedule:<schedule_id>
// HSET schedule:sched_1122 schedule_id "sched_1122" train_id "train_789" route_id "route_ne_corr" departure_datetime "2024-05-10T08:00:00-04:00" ... status "Scheduled"
// Use Hashes for details. Key format: schedule_stop:<stop_id>
// HSET schedule_stop:stop_sched1122_1 stop_id "stop_sched1122_1" schedule_id "sched_1122" station_id "station_bos" ...

// To find stops for a schedule, use a Sorted Set (score by sequence_order):
// ZADD schedule:sched_1122:stops 1 schedule_stop:stop_sched1122_1
// ZADD schedule:sched_1122:stops 2 schedule_stop:stop_sched1122_2
// Use Hashes for passenger details. Key format: passenger:<passenger_id>
// HSET passenger:pass_pqr passenger_id "pass_pqr" first_name "Alice" last_name "Smith" email "alice.smith@example.com" ...

// To find passenger by email (optional index):
// SET passenger_email:"alice.smith@example.com" passenger:pass_pqr
// Use Hashes for booking details. Key format: booking:<booking_id>
// HSET booking:book_zyx booking_id "book_zyx" passenger_id "pass_pqr" schedule_id "sched_1122" ... status "Confirmed" ...

// To link bookings to passengers/schedules (optional):
// SADD passenger:pass_pqr:bookings booking:book_zyx
// SADD schedule:sched_1122:bookings booking:book_zyx
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...

// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
// Use Hashes for staff details. Key format: staff:<staff_id>
// HSET staff:staff_mno staff_id "staff_mno" first_name "Bob" ... employee_number "E12345" ... is_active 1

// To find staff by employee number (optional index):
// SET staff_employee_number:"E12345" staff:staff_mno
// Use Hashes for maintenance record details. Key format: maintenance_record:<record_id>
// HSET maintenance_record:maint_rec_001 record_id "maint_rec_001" asset_id "train_789" asset_type "Train" ... status "Completed"

// To link records to assets (optional):
// SADD train:train_789:maintenance maintenance_record:maint_rec_001
// SADD platform:plat_123:maintenance maintenance_record:maint_rec_002
##Table Structure
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )
##Table Structure
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )

[User] Can you provide the total number of cars associated with a specific train with train_id 'train_789'?

[Assistant] SCARD train:train_789:cars

[User] Report the number of employees for each department, broken down by their employment status.

[Assistant] SELECT department, status, COUNT(*) AS employee_count FROM financial_services.employees GROUP BY department, status

[User] List all staff members along with their direct manager's first and last names.

[Assistant]
SELECT s.staff_id,
       s.first_name AS staff_first_name,
       s.last_name AS staff_last_name,
       m.first_name AS manager_first_name,
       m.last_name AS manager_last_name
FROM hospitality_technology.staff s
LEFT JOIN hospitality_technology.staff m
  ON s.manager_id = m.staff_id;

[User] Could you retrieve pairs of accessible service locations in the same city but with different postal codes?

[Assistant]
SELECT sl1.location_id AS location1_id,
       sl2.location_id AS location2_id,
       sl1.city
FROM government_services.service_locations sl1
JOIN government_services.service_locations sl2
  ON sl1.city = sl2.city
 AND sl1.location_id < sl2.location_id
WHERE sl1.is_accessible = TRUE
  AND sl2.is_accessible = TRUE;

[User] Now restrict these pairs to those in the state of 'California'.

[Assistant]
SELECT sl1.location_id AS location1_id,
       sl2.location_id AS location2_id,
       sl1.city
FROM government_services.service_locations sl1
JOIN government_services.service_locations sl2
  ON sl1.city = sl2.city
 AND sl1.location_id < sl2.location_id
WHERE sl1.is_accessible = TRUE
  AND sl2.is_accessible = TRUE
  AND sl1.state = 'California'
  AND sl2.state = 'California';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE manufacturing.aircraft_models (
    model_id character varying(64) NOT NULL,  -- unique identifier for the aircraft model
    model_name character varying(128) NOT NULL, -- commercial name of the model (e.g., 737 MAX, A320neo)
    manufacturer character varying(128) NOT NULL, -- manufacturer name (e.g., Boeing, Airbus)
    passenger_capacity integer, -- typical passenger capacity
    max_range_km integer, -- maximum flight range in kilometers
    engine_type character varying(100), -- type of engines used
    wingspan_m numeric(6,2), -- wingspan in meters
    status character varying(50) NOT NULL, -- e.g., 'In Production', 'Development', 'Discontinued'
    first_flight_date date, -- date of the model's first flight
    PRIMARY KEY (model_id)
)
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
##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 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 )
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
##Table Structure
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
##Table Structure
CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )
##Table Structure
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )

[User] Provide a breakdown of the total number of conversations, showing how many are group chats and how many are not. Also, show the count of conversations that have a recorded last message time.

[Assistant] SELECT COUNT(*) AS total_conversations, COUNT(CASE WHEN is_group_chat = true THEN 1 END) AS group_chat_count, COUNT(CASE WHEN is_group_chat = false THEN 1 END) AS private_chat_count, COUNT(last_message_at) AS conversations_with_messages_count FROM social_media.conversations;

[User] Find all pairs of token transfers where one transfer's sender and recipient are swapped with another transfer's sender and recipient, showing both transfer IDs.

[Assistant]
SELECT t1.from_address AS sender,
       t1.to_address   AS recipient,
       t1.transfer_id  AS transfer1_id,
       t2.transfer_id  AS transfer2_id
FROM web3.token_transfers t1
JOIN web3.token_transfers t2
  ON t1.from_address = t2.to_address
 AND t1.to_address   = t2.from_address
 AND t1.transfer_id < t2.transfer_id;

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

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

[User] Give me the count of policies grouped by their status.

[Assistant]
SELECT status,
       COUNT(*) AS policy_count
FROM insurance.policies
GROUP BY status;

[User] Which routes have their origin and destination in the same city? Show the route number, description, and the origin and destination location IDs.

[Assistant]
SELECT r.route_number, r.description, r.origin_location_id, r.destination_location_id
FROM transportation.routes r
JOIN transportation.routes r2 ON r.origin_location_id = r2.destination_location_id AND r.route_id = r2.route_id;

[User] How many unique patient records are there for each gender?

[Assistant] SELECT gender, COUNT(DISTINCT patient_id) AS patient_count FROM healthcare.patients GROUP BY gender;

[User] For each contract, can you show the number of different types of events it has emitted along with the contract ID?

[Assistant] SELECT contract_id, COUNT(DISTINCT event_name) AS distinct_event_types FROM web3.events GROUP BY contract_id;

[User] List the top 10 narratives based on their market cap. Display the narrative name, market_cap, and token_num.

[Assistant] SELECT narrative, market_cap, token_num FROM narrative_info ORDER BY market_cap DESC LIMIT 10

[User] List all medications with a description that includes the word 'antibiotic'.

[Assistant] SELECT * FROM healthcare.medications WHERE description ILIKE '%antibiotic%';

[User] How many documents of each type currently have a verification_status of 'Pending'?

[Assistant]
SELECT
  document_type,
  COUNT(*) AS pending_count
FROM government_services.documents
WHERE verification_status = 'Pending'
GROUP BY document_type;

[User] List each user along with the wallet_id of their first created wallet.

[Assistant]
SELECT
  m.user_id,
  w.wallet_id AS first_wallet_id
FROM (
  SELECT user_id, MIN(created_at) AS first_created_at
  FROM web3.wallets
  GROUP BY user_id
) AS m
JOIN web3.wallets AS w
  ON w.user_id = m.user_id
  AND w.created_at = m.first_created_at;

[User] How many documents exist for each document_type? Return document_type and the count.

[Assistant]
SELECT document_type,
       COUNT(*) AS document_count
FROM insurance.claim_documents
GROUP BY document_type;

[User] How many users does each user follow? Show the follower user ID and the count.

[Assistant] SELECT follower_user_id, count(*) FROM social_media.follows GROUP BY follower_user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
##Table Structure
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
##Table Structure
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.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
##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.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_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.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] Show me document names and upload timestamps for documents linked to cases that were opened after January 1, 2023.

[Assistant] SELECT T1.document_name, T1.upload_timestamp FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.date_opened > '2023-01-01';

[User] Additionally, only include documents that have a version number greater than 1.

[Assistant] SELECT T1.document_name, T1.upload_timestamp FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.date_opened > '2023-01-01' AND T1.version > 1;

[User] For each driver, show their driver_id, first_name, last_name, along with any other driver whose license_expiry_date is earlier than theirs.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date;

[User] Exclude pairs where the two expiry dates are not in the same calendar year.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date);

[User] Also only include pairs where the difference between their expiry dates is more than 30 days.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date,
       DATE_PART('day', d1.license_expiry_date - d2.license_expiry_date) AS days_difference
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
WHERE d1.license_expiry_date - d2.license_expiry_date > INTERVAL '30 days';

[User] For each customer, provide a summary of their account statuses, showing their full name, account status, and the count of accounts for each status.

[Assistant] SELECT c.first_name, c.last_name, a.status, COUNT(a.account_id) AS account_count FROM financial_services.accounts a JOIN financial_services.customers c ON a.customer_id = c.customer_id GROUP BY c.customer_id, c.first_name, c.last_name, a.status ORDER BY c.last_name, c.first_name, a.status;

[User] Refine this to only include customers who have accounts in at least two different statuses.

[Assistant] SELECT c.first_name, c.last_name, a.status, COUNT(a.account_id) AS account_count FROM financial_services.accounts a JOIN financial_services.customers c ON a.customer_id = c.customer_id GROUP BY c.customer_id, c.first_name, c.last_name, a.status HAVING c.customer_id IN ( SELECT customer_id FROM financial_services.accounts GROUP BY customer_id HAVING COUNT(DISTINCT status) >= 2 ) ORDER BY c.last_name, c.first_name, a.status;

[User] How many unique users have a KYC audit record with status 'pending'?

[Assistant]
SELECT COUNT(DISTINCT user_id) AS pending_kyc_users
FROM trading_platform.kyc_audit
WHERE status = 'pending';

[User] Retrieve the first and last names of all doctors who specialize in Cardiology.

[Assistant]
SELECT first_name, last_name
FROM healthcare.doctors
WHERE specialty = 'Cardiology';


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.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
##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.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.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.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.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 )
##Table Structure
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) )
##Table Structure
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
##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.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
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, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id.text, policy_id.text, customer_id.text, first_name.text, last_name.text, relationship.text, percentage_share.numeric, contact_info.text, added_at.timestamp )
##Table Structure
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
##Table Structure
CREATE TABLE blockchain.nodes ( node_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (node_id) )

[User] For each user, find the previous user by registration time. List current user_id and username, previous user_id and username, and the time difference in minutes between their registrations.

[Assistant]
SELECT u.user_id AS current_user_id,
       u.username AS current_username,
       p.user_id AS previous_user_id,
       p.username AS previous_username,
       EXTRACT(EPOCH FROM (u.created_at - p.created_at)) / 60 AS diff_minutes
FROM web3.users u
JOIN web3.users p
  ON p.created_at = (
    SELECT MAX(created_at)
    FROM web3.users
    WHERE created_at < u.created_at
  )
ORDER BY u.created_at;

[User] List all unspent UTXOs with an amount greater than 10.

[Assistant] SELECT utxo_id, transaction_id, address, amount FROM utxos WHERE spent = FALSE AND amount > 10;

[User] Find for each category the service with the highest standard_fee and the service with the lowest standard_fee. Display the category, highest_fee_service, and lowest_fee_service.

[Assistant]
SELECT m.category,
       s_max.service_name AS highest_fee_service,
       s_min.service_name AS lowest_fee_service
FROM (
  SELECT category,
         MAX(standard_fee) AS max_fee,
         MIN(standard_fee) AS min_fee
  FROM government_services.services
  GROUP BY category
) m
JOIN government_services.services s_max
  ON s_max.category = m.category
  AND s_max.standard_fee = m.max_fee
JOIN government_services.services s_min
  ON s_min.category = m.category
  AND s_min.standard_fee = m.min_fee;

[User] Get all pairs of locations in the same city, showing both location IDs, names, and the shared city.

[Assistant]
SELECT l1.location_id AS location1_id, l1.name AS location1_name,
       l2.location_id AS location2_id, l2.name AS location2_name,
       l1.city
FROM transportation.locations l1
JOIN transportation.locations l2
  ON l1.city = l2.city
 AND l1.location_id < l2.location_id;

[User] List the names of manufacturers that produce at least one medication with a description and at least one medication without a description.

[Assistant] SELECT DISTINCT manufacturer FROM healthcare.medications m1 WHERE manufacturer IS NOT NULL AND EXISTS (SELECT 1 FROM healthcare.medications m2 WHERE m2.manufacturer = m1.manufacturer AND m2.description IS NOT NULL) AND EXISTS (SELECT 1 FROM healthcare.medications m3 WHERE m3.manufacturer = m1.manufacturer AND m3.description IS NULL);

[User] Find parent agencies and the number of direct child agencies they have. List the parent agency name and the count of their children.

[Assistant] SELECT T1.agency_name, COUNT(T2.agency_id) FROM government_services.agencies AS T1 JOIN government_services.agencies AS T2 ON T1.agency_id = T2.parent_agency_id GROUP BY T1.agency_name ORDER BY COUNT(T2.agency_id) DESC;

[User] Count the number of claim documents for each distinct MIME type.

[Assistant] SELECT mime_type, COUNT(*) FROM insurance.claim_documents GROUP BY mime_type

[User] Which employees share the same department with at least one other employee? Please show the employee ID, full name, and department.

[Assistant]
SELECT e1.employee_id, e1.first_name || ' ' || e1.last_name AS full_name, e1.department
FROM government_services.employees e1
WHERE e1.department IS NOT NULL AND EXISTS (
    SELECT 1 FROM government_services.employees e2
    WHERE e2.department = e1.department AND e2.employee_id <> e1.employee_id
);

[User] Find all pairs of node IDs that share the same IP address but operate on different ports.

[Assistant] SELECT a.node_id AS node1, b.node_id AS node2, a.ip_address, a.port AS port1, b.port AS port2 FROM blockchain.nodes a JOIN blockchain.nodes b ON a.ip_address = b.ip_address AND a.node_id < b.node_id AND a.port <> b.port;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )
##Table Structure
CREATE TABLE legal_services.law_firms (
    firm_id character varying(64) NOT NULL,  -- unique identifier for the law firm
    firm_name character varying(200) NOT NULL, -- official name of the law firm
    address text NOT NULL, -- primary address of the firm
    phone character varying(32), -- firm's main phone number
    website character varying(255), -- firm's website URL
    founded_date date, -- date the firm was established
    managing_partner_id character varying(64), -- FK to lawyers table (optional)
    PRIMARY KEY (firm_id)
)
##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] List all ERC20 tokens where the price is between $1 and $10, including their names, symbols, and contract addresses.

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.contract_address WHERE tm.is_erc20 = 1 AND tpl.price BETWEEN 1 AND 10;

[User] I think there's an error in your query - the token_prices_latest table isn't in the schema. Can you modify it to use the token_balances table instead?

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address FROM token_metas tm JOIN token_balances tb ON tm.contract_address = tb.wallet_address WHERE tm.is_erc20 = 1 AND CAST(tb.amount AS decimal) BETWEEN 1 AND 10;

[User] That doesn't seem right either. Let's just get the basic ERC20 token information without price filtering for now.

[Assistant] SELECT name, symbol, contract_address FROM token_metas WHERE is_erc20 = 1 LIMIT 100;

[User] Show me the name and founding date of every law firm.

[Assistant]
SELECT firm_name, founded_date
FROM law_firms;

[User] Also include the firm's phone number.

[Assistant]
SELECT firm_name, phone, founded_date
FROM law_firms;

[User] Exclude any firms that don't have a website specified.

[Assistant]
SELECT firm_name, phone, founded_date
FROM law_firms
WHERE website IS NOT NULL;

[User] Finally, order the list by firm_name in descending order.

[Assistant]
SELECT firm_name, phone, founded_date
FROM law_firms
WHERE website IS NOT NULL
ORDER BY firm_name DESC;

[User] Find all pairs of inventory entries where the same player acquired the same item twice. Show the player_id, item_id, the earlier inventory_id as first_inv, and the later inventory_id as second_inv.

[Assistant]
SELECT p1.player_id,
       p1.item_id,
       p1.inventory_id AS first_inv,
       p2.inventory_id AS second_inv
FROM gaming_technology.player_inventory p1
JOIN gaming_technology.player_inventory p2
  ON p1.player_id = p2.player_id
 AND p1.item_id = p2.item_id
 AND p1.acquired_at < p2.acquired_at;

[User] Also include the time difference in minutes between the two acquisitions as diff_minutes.

[Assistant]
SELECT p1.player_id,
       p1.item_id,
       p1.inventory_id AS first_inv,
       p2.inventory_id AS second_inv,
       EXTRACT(EPOCH FROM (p2.acquired_at - p1.acquired_at)) / 60 AS diff_minutes
FROM gaming_technology.player_inventory p1
JOIN gaming_technology.player_inventory p2
  ON p1.player_id = p2.player_id
 AND p1.item_id = p2.item_id
 AND p1.acquired_at < p2.acquired_at;


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.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.train_cars (
    car_id character varying(64) NOT NULL, -- Unique identifier for the train car
    train_id character varying(64) NOT NULL, -- Foreign key referencing trains
    car_number character varying(10) NOT NULL, -- Identifier of the car within the train set
    car_type character varying(64) NOT NULL, -- e.g., Locomotive, Passenger, Sleeper, Dining, Baggage
    class character varying(32), -- e.g., First, Business, Economy (null for non-passenger cars)
    capacity integer, -- Passenger capacity of this specific car (null for non-passenger cars)
    features text, -- Comma-separated list of features (e.g., 'WiFi', 'Power Outlet', 'Accessible Restroom')
    PRIMARY KEY (car_id),
    FOREIGN KEY (train_id) REFERENCES train_station_management.trains(train_id)
)
##Table Structure
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
##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 healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.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.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
##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 web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
##Table Structure
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )

[User] For each user, show how many users registered after them. Return the user_id, username, and the count of later registrants.

[Assistant] SELECT u1.user_id, u1.username, COUNT(u2.user_id) AS later_user_count FROM web3.users u1 LEFT JOIN web3.users u2 ON u2.created_at > u1.created_at GROUP BY u1.user_id, u1.username ORDER BY u1.user_id;

[User] What is the current location of a specific train car with car_id 'TC123'?

[Assistant] I'm sorry, but I can't provide the current location of a specific train car as this information is not stored in the database table. The table only contains static details about train cars such as car type, capacity, and features. For real-time location data, please refer to the train tracking system or contact the relevant department.

[User] Count the number of unread notifications for each notification_type across all users.

[Assistant]
SELECT
  notification_type,
  COUNT(*) AS unread_count
FROM social_media.notifications
WHERE read_at IS NULL
GROUP BY notification_type;

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

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

[User] Calculate the average total amount for invoices issued in each calendar year.

[Assistant] SELECT EXTRACT(YEAR FROM issue_date) AS issue_year, AVG(total_amount) AS average_total_amount FROM legal_services.invoices GROUP BY EXTRACT(YEAR FROM issue_date) ORDER BY issue_year

[User] Count the total number of chronic diagnoses for each code_type.

[Assistant]
SELECT
  code_type,
  COUNT(*) AS chronic_diagnosis_count
FROM healthcare.diagnoses
WHERE is_chronic = TRUE
GROUP BY code_type;

[User] List all active products, showing their product ID, name, and type, ordered by their creation date.

[Assistant] SELECT product_id, product_name, product_type FROM insurance.insurance_products WHERE is_active = TRUE ORDER BY created_at;

[User] Show the customer_id and pairs of payment_ids for any customers who have overlapping payment periods.

[Assistant]
SELECT p1.customer_id,
       p1.payment_id AS payment1_id,
       p2.payment_id AS payment2_id
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.customer_id = p2.customer_id
 AND p1.payment_id < p2.payment_id
 AND p1.payment_period_start <= p2.payment_period_end
 AND p1.payment_period_end   >= p2.payment_period_start;

[User] Which transaction_id has the highest total value transferred? Show the transaction_id and the sum of values for that transaction.

[Assistant] SELECT transaction_id, SUM(value) AS total_transaction_value FROM web3.token_transfers GROUP BY transaction_id ORDER BY total_transaction_value DESC LIMIT 1;

[User] How many appointments are scheduled to start tomorrow?

[Assistant] SELECT count(*) FROM government_services.appointments WHERE DATE(scheduled_start_time) = CURRENT_DATE + INTERVAL '1 day'

[User] Show me all guests from 'CA' along with their full name and email address.

[Assistant] SELECT guest_id, CONCAT(first_name, ' ', last_name) AS full_name, email FROM hospitality_technology.guests WHERE country_code = 'CA';

[User] Find all insurance providers that offer both HMO and PPO plans and list the provider name along with the corresponding HMO and PPO plan IDs.

[Assistant]
SELECT h.insurance_provider,
       h.plan_id AS hmo_plan_id,
       p.plan_id AS ppo_plan_id
FROM healthcare.insurance_plans h
JOIN healthcare.insurance_plans p
  ON h.insurance_provider = p.insurance_provider
WHERE h.plan_type = 'HMO'
  AND p.plan_type = 'PPO';

[User] Count the number of logs for each distinct action type.

[Assistant] SELECT action, COUNT(*) AS log_count FROM trading_platform.logs GROUP BY action;

[User] How many distinct posts does each hashtag appear in?

[Assistant] SELECT hashtag_id, COUNT(DISTINCT post_id) AS post_count FROM social_media.post_hashtags GROUP BY hashtag_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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 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 )
##Table Structure
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 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.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.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 gaming_technology.player_inventory ( inventory_id uuid, player_id uuid, item_id uuid, quantity integer, acquired_at timestamp with time zone, instance_data jsonb )
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
##Table Structure
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )
##Table Structure
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )

[User] List all unique peer ports that have been used at least once in the system.

[Assistant] SELECT DISTINCT port FROM trading_platform.peers ORDER BY port ASC;

[User] List pairs of smoking and non-smoking rooms on the same floor for each property, showing the property_id, floor, smoking room_number, and non_smoking room_number.

[Assistant]
SELECT r1.property_id,
       r1.floor,
       r1.room_number AS smoking_room,
       r2.room_number AS non_smoking_room
FROM hospitality_technology.rooms r1
JOIN hospitality_technology.rooms r2
  ON r1.property_id = r2.property_id
 AND r1.floor = r2.floor
 AND r1.is_smoking = TRUE
 AND r2.is_smoking = FALSE;

[User] Find cases where an address received tokens in one transfer and then sent tokens in another. List the receive transfer_id, the send transfer_id, the address, and both transfer values.

[Assistant]
SELECT recv.transfer_id AS receive_transfer_id,
       send.transfer_id AS send_transfer_id,
       recv.to_address AS address,
       recv.value       AS received_value,
       send.value       AS sent_value
FROM web3.token_transfers recv
JOIN web3.token_transfers send
  ON recv.to_address = send.from_address;

[User] Can you give me the total number of appointments grouped by status?

[Assistant]
SELECT status,
       COUNT(*) AS total_appointments
FROM healthcare.appointments
GROUP BY status;

[User] Filter the result to show only statuses with more than 50 appointments.

[Assistant]
SELECT status,
       COUNT(*) AS total_appointments
FROM healthcare.appointments
GROUP BY status
HAVING COUNT(*) > 50;

[User] List all trips for routes of type 'Express', showing the trip ID and route number.

[Assistant] SELECT T.trip_id, R.route_number FROM transportation.trips AS T JOIN transportation.routes AS R ON T.route_id = R.route_id WHERE R.type = 'Express';

[User] Show me all unique player IDs who have at least one item in their inventory with a quantity greater than 10.

[Assistant] SELECT DISTINCT player_id FROM gaming_technology.player_inventory WHERE quantity > 10;

[User] Which rooms on the 4th floor are non-smoking, along with their property IDs and type IDs?

[Assistant] SELECT room_id, property_id, room_number, room_type_id FROM hospitality_technology.rooms WHERE floor = 4 AND is_smoking = FALSE;

[User] Count the number of medical records created for each doctor, and list the doctor_id alongside their record count.

[Assistant] SELECT doctor_id, COUNT(*) AS record_count FROM healthcare.medical_records GROUP BY doctor_id;

[User] Show me the subject and start times of all appointments along with the corresponding lawyer IDs for each client.

[Assistant] SELECT client_id, lawyer_id, subject, start_time FROM legal_services.appointments;

[User] For each employee who has verified documents, show their full name and the total number of documents they have verified with a status of 'Verified'.

[Assistant] SELECT e.full_name, COUNT(d.document_id) FROM government_services.documents d JOIN employees e ON d.verified_by_employee_id = e.employee_id WHERE d.verification_status = 'Verified' GROUP BY e.full_name;

[User] Can you list the names of agencies that do not have a parent agency assigned, ordered by their established date?

[Assistant]
SELECT agency_id, agency_name, established_date
FROM government_services.agencies
WHERE parent_agency_id IS NULL
ORDER BY established_date;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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 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.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.transactions ( transaction_id.text, block_id.text, sender_address.text, receiver_address.text, amount.numeric, timestamp.timestamp, signature.text )
CREATE TABLE blockchain.addresses ( address_id.text, public_key.text, balance.numeric )
CREATE TABLE blockchain.nodes (
    node_id character varying(64) NOT NULL,  -- unique identifier for the node
    ip_address character varying(15) NOT NULL, -- IP address of the node
    port integer NOT NULL, -- port number of the node
    last_seen timestamp NOT NULL, -- last time the node was active
    PRIMARY KEY (node_id)
)
##Table Structure
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 smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
##Table Structure
CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
##Table Structure
CREATE TABLE blockchain.transactions ( transaction_id text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.addresses ( address_id text, public_key text, balance numeric )
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )
CREATE TABLE blockchain.users ( user_id text, username text, email text, password_hash text )
##Table Structure
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )

[User] Find all addresses that have both sent and received tokens. For each, show the address, the total value sent, and the total value received.

[Assistant]
SELECT s.address, s.total_sent, r.total_received
FROM (
  SELECT from_address AS address, SUM(value) AS total_sent
  FROM web3.token_transfers
  GROUP BY from_address
) s
JOIN (
  SELECT to_address   AS address, SUM(value) AS total_received
  FROM web3.token_transfers
  GROUP BY to_address
) r
  ON s.address = r.address;

[User] Show me all rooms along with their current overall review rating for each room, including the room number and property id.

[Assistant]
SELECT r.room_number, r.property_id, AVG(rv.rating_overall) AS average_overall_rating
FROM hospitality_technology.rooms r
LEFT JOIN hospitality_technology.reviews rv
  ON r.property_id = rv.property_id
GROUP BY r.room_number, r.property_id;

[User] Show me each transaction ID along with the sender's public key, the receiver's balance, and the transaction amount.

[Assistant]
SELECT t.transaction_id, a_sender.public_key AS sender_public_key, a_receiver.balance AS receiver_balance, t.amount
FROM blockchain.transactions t
JOIN blockchain.addresses a_sender ON t.sender_address = a_sender.address_id
JOIN blockchain.addresses a_receiver ON t.receiver_address = a_receiver.address_id;

[User] For each transaction, show the transaction id and the total number of unique addresses involved in token transfers for that transaction (both as sender and receiver).

[Assistant]
SELECT transaction_id, COUNT(DISTINCT addr) AS unique_address_count
FROM (
    SELECT transaction_id, from_address AS addr FROM web3.token_transfers
    UNION ALL
    SELECT transaction_id, to_address AS addr FROM web3.token_transfers
) a
GROUP BY transaction_id;

[User] Show the tokens with a negative net flow this month on all chains.

[Assistant] SELECT token_symbol, chain, net_flow FROM smart_money_token_performance WHERE net_flow < 0 AND date_trunc('month', CURRENT_DATE) = date_trunc('month', now());

[User] Order them by net flow ascending and only show the bottom 5.

[Assistant] SELECT token_symbol, chain, net_flow FROM smart_money_token_performance WHERE net_flow < 0 AND date_trunc('month', CURRENT_DATE) = date_trunc('month', now()) ORDER BY net_flow ASC LIMIT 5;

[User] List all partners who were hired in the same year. Show their first name, last name, hire year, and firm ID.

[Assistant] SELECT l1.first_name, l1.last_name, EXTRACT(YEAR FROM l1.hire_date) AS hire_year, l1.firm_id FROM legal_services.lawyers AS l1 JOIN legal_services.lawyers AS l2 ON EXTRACT(YEAR FROM l1.hire_date) = EXTRACT(YEAR FROM l2.hire_date) AND l1.lawyer_id != l2.lawyer_id WHERE l1.is_partner = TRUE AND l2.is_partner = TRUE GROUP BY l1.lawyer_id, hire_year, l1.firm_id ORDER BY hire_year, l1.last_name;

[User] How many contracts are deployed each month for each status?

[Assistant]
SELECT TO_CHAR(deployed_at, 'YYYY-MM') AS deploy_month,
       status,
       COUNT(*) AS contract_count
FROM web3.contracts
GROUP BY TO_CHAR(deployed_at, 'YYYY-MM'), status
ORDER BY deploy_month, status;

[User] Actually, I only want to see yearly totals instead of monthly.

[Assistant]
SELECT EXTRACT(YEAR FROM deployed_at) AS deploy_year,
       status,
       COUNT(*) AS contract_count
FROM web3.contracts
GROUP BY EXTRACT(YEAR FROM deployed_at), status
ORDER BY deploy_year, status;

[User] Show me each transaction with its ID, amount, timestamp, and the usernames of both sender and receiver.

[Assistant]
SELECT t.transaction_id, t.amount, t.timestamp, us.username AS sender_username, ur.username AS receiver_username
FROM blockchain.transactions t
LEFT JOIN blockchain.wallets ws ON t.sender_address = ws.address_id
LEFT JOIN blockchain.users us ON ws.user_id = us.user_id
LEFT JOIN blockchain.wallets wr ON t.receiver_address = wr.address_id
LEFT JOIN blockchain.users ur ON wr.user_id = ur.user_id;

[User] List the application ID and citizen ID for all documents of type 'Proof of Address'.

[Assistant] SELECT application_id, citizen_id FROM government_services.documents WHERE document_type = 'Proof of Address';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
##Table Structure
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.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] Show the symbol, name, and total supply for all SUI coins with status 'active'.

[Assistant]
SELECT scm.symbol, scm.name, scm.coin_type, scm.total_supply
FROM sui_coins_metadata scm
WHERE scm.status = 'active';

[User] I received an error that column 'total_supply' doesn't exist in sui_coins_metadata.

[Assistant]
SELECT scm.symbol, scm.name, scm.coin_type
FROM sui_coins_metadata scm
WHERE scm.status = 'active';

[User] Now, join with sui_coins to add up the total balance across all owners for each coin_type.

[Assistant]
SELECT scm.symbol, scm.name, scm.coin_type, SUM(CAST(sc.balance AS NUMERIC)) AS total_balance
FROM sui_coins_metadata scm
JOIN sui_coins sc ON scm.coin_type = sc.coin_type
WHERE scm.status = 'active'
GROUP BY scm.symbol, scm.name, scm.coin_type;

[User] Can you list all item names along with their type, rarity, and cost amount for every item in the database?

[Assistant] SELECT item_name, item_type, rarity, cost_amount FROM gaming_technology.in_game_items;

[User] Can you show only items where the cost amount is less than 100?

[Assistant] SELECT item_name, item_type, rarity, cost_amount FROM gaming_technology.in_game_items WHERE cost_amount < 100;

[User] I only want to see items that are of rarity 'Epic'.

[Assistant] SELECT item_name, item_type, rarity, cost_amount FROM gaming_technology.in_game_items WHERE cost_amount < 100 AND rarity = 'Epic';

[User] Could you also show the game_id for these items?

[Assistant] SELECT game_id, item_name, item_type, rarity, cost_amount FROM gaming_technology.in_game_items WHERE cost_amount < 100 AND rarity = 'Epic';

[User] List tokens with net outflow (type=2) on the 'Ethereum' chain. Show token_symbol and total usd_value sold.

[Assistant]
SELECT token_symbol, SUM(usd_value) AS total_sold
FROM smart_money_token_inflow
WHERE type = 2 AND chain = 'Ethereum'
GROUP BY token_symbol;

[User] Now limit to tokens with total_sold above 10000 and order by total_sold descending.

[Assistant]
SELECT token_symbol, SUM(usd_value) AS total_sold
FROM smart_money_token_inflow
WHERE type = 2 AND chain = 'Ethereum'
GROUP BY token_symbol
HAVING SUM(usd_value) > 10000
ORDER BY total_sold DESC;

[User] Count the number of patients grouped by gender, showing gender and patient_count.

[Assistant]
SELECT gender, COUNT(*) AS patient_count
FROM healthcare.patients
GROUP BY gender;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
##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.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text PRIMARY KEY, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.securities ( security_id text PRIMARY KEY, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.loans ( loan_id text PRIMARY KEY, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months int, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
##Table Structure
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )

[User] Show me all available services with a unit of 'Per Hour'.

[Assistant] SELECT service_name ,  description ,  price FROM hospitality_technology.services WHERE is_available  =  true AND unit  =  'Per Hour'

[User] Also include the department and filter the results to only show services priced above 100.

[Assistant] SELECT service_name ,  description ,  price ,  department FROM hospitality_technology.services WHERE is_available  =  true AND unit  =  'Per Hour' AND price  >  100

[User] List all distinct plan types available in the insurance_plans table.

[Assistant] SELECT DISTINCT plan_type FROM healthcare.insurance_plans;

[User] Show the average current_principal_balance for each loan_type, and include the number of active loans per type.

[Assistant]
SELECT loan_type,
       COUNT(*) AS active_loan_count,
       AVG(current_principal_balance) AS avg_balance
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type;

[User] Exclude loan_types where the average balance is below 50,000.

[Assistant]
SELECT loan_type,
       COUNT(*) AS active_loan_count,
       AVG(current_principal_balance) AS avg_balance
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type
HAVING AVG(current_principal_balance) >= 50000;

[User] Also include the account_number and interest_rate for individual loans that are above this threshold.

[Assistant]
SELECT l.loan_id,
       a.account_number,
       l.current_principal_balance,
       l.interest_rate
FROM financial_services.loans l
JOIN financial_services.accounts a
  ON l.account_id = a.account_id
WHERE l.status = 'Active'
  AND l.current_principal_balance >= 50000;

[User] For each employee, find their first and last name along with the number of applications they've been assigned. Only include employees with at least 5 assigned applications.

[Assistant]
SELECT e.first_name,
       e.last_name,
       COUNT(a.application_id) AS assigned_count
FROM government_services.employees e
JOIN government_services.applications a ON e.employee_id = a.assigned_employee_id
GROUP BY e.first_name, e.last_name
HAVING COUNT(a.application_id) >= 5;

[User] Show me all appointment IDs and their scheduled start times along with the employee ID and service ID for appointments that have been booked using the 'Kiosk' booking method.

[Assistant] SELECT appointment_id, scheduled_start_time, employee_id, service_id FROM government_services.appointments WHERE booking_method = 'Kiosk';

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

[Assistant] SELECT appointment_id, scheduled_start_time, employee_id, service_id FROM government_services.appointments WHERE booking_method = 'Kiosk' AND status = 'Scheduled';

[User] How many distinct fundraising round names are recorded in the table?

[Assistant] SELECT COUNT(DISTINCT rounds_name) FROM project_fundraising_record;

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.routes (
    route_id character varying(64) NOT NULL,  -- unique identifier for the route
    route_number character varying(32) NOT NULL UNIQUE, -- public-facing route number/name
    description text, -- description of the route
    origin_location_id character varying(64) NOT NULL, -- identifier of the starting location
    destination_location_id character varying(64) NOT NULL, -- identifier of the ending location
    distance_km numeric(10, 2), -- estimated distance in kilometers
    estimated_duration_minutes integer, -- estimated travel time in minutes
    type character varying(32) NOT NULL, -- e.g., City Bus, Intercity Train, Cargo Delivery
    PRIMARY KEY (route_id)
)
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.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.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 )

[User] What is the average estimated_duration_minutes for each route type?

[Assistant] SELECT type, AVG(estimated_duration_minutes) AS avg_duration FROM transportation.routes GROUP BY type;

[User] Exclude route types where the average duration is less than 60 minutes, and sort the results by avg_duration DESC.

[Assistant] SELECT type, AVG(estimated_duration_minutes) AS avg_duration FROM transportation.routes GROUP BY type HAVING AVG(estimated_duration_minutes) >= 60 ORDER BY avg_duration DESC;

[User] What is the average market cap and average 24-hour trading volume for tokens on each chain?

[Assistant] SELECT chain, AVG(market_cap) AS average_market_cap, AVG(volume_24h) AS average_volume_24h FROM token_dexpool_info GROUP BY chain

[User] Can you also include the count of tokens for each chain and filter out chains with less than 100 tokens?

[Assistant] SELECT chain, AVG(market_cap) AS average_market_cap, AVG(volume_24h) AS average_volume_24h, COUNT(token_symbol) AS token_count FROM token_dexpool_info GROUP BY chain HAVING COUNT(token_symbol) >= 100

[User] Show all documents of type 'Evidence' uploaded in the last 30 days, including document_name, case_id, upload_timestamp, and version.

[Assistant]
SELECT document_name, case_id, upload_timestamp, version
FROM legal_services.documents
WHERE document_type = 'Evidence'
  AND upload_timestamp >= NOW() - INTERVAL '30 days';

[User] Show me all users whose email address contains the word 'test', along with their user IDs and the date they registered.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE email ILIKE '%test%';

[User] Actually, only include users who registered after January 1, 2024, and sort them by newest registration date first.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE email ILIKE '%test%' AND created_at > '2024-01-01' ORDER BY created_at DESC;

[User] Show me the subjects and start times of all appointments for a specific client, along with the assigned lawyer ID.

[Assistant] SELECT subject, start_time, lawyer_id FROM legal_services.appointments WHERE client_id = 'CLIENT123';

[User] Could you narrow it down to only include appointments where the status is 'Rescheduled' or 'Postponed'?

[Assistant] SELECT subject, start_time, lawyer_id FROM legal_services.appointments WHERE client_id = 'CLIENT123' AND status IN ('Rescheduled', 'Postponed');

[User] Also, please make sure the appointments were created after June 1st, 2024 and order the results by start_time ascending.

[Assistant] SELECT subject, start_time, lawyer_id FROM legal_services.appointments WHERE client_id = 'CLIENT123' AND status IN ('Rescheduled', 'Postponed') AND created_at > '2024-06-01' ORDER BY start_time ASC;

[User] Which servers are currently 'online' and located in the 'us-west-2' region, and what is the title of the game each server is hosting?

[Assistant]
SELECT s.server_id, s.server_name, s.region, g.title AS game_title
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.status = 'online' AND s.region = 'us-west-2';

[User] Can you also include each server's current_players count and the game's genre in the result?

[Assistant]
SELECT s.server_id, s.server_name, s.region, s.current_players, g.title AS game_title, g.genre
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.status = 'online' AND s.region = 'us-west-2';