System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets ( asset_id 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.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.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
##Table Structure
CREATE TABLE insurance.customers ( customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL DEFAULT 'USA', phone_number character varying(30), email character varying(128) UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, status character varying(20) NOT NULL DEFAULT 'Active', PRIMARY KEY (customer_id) )
##Table Structure
Use Hashes. Key pattern: 'component:<component_id>'. Example: HSET component:LGSTRUT01 part_number "PN-5521-A" component_name "Landing Gear Strut" material_id "mat:TI64" supplier_id "sup:ACME_AERO" ... Consider Sets for reverse lookups (e.g., 'material_components:<material_id>' -> Set<component_id>).
##Table Structure
CREATE TABLE blockchain.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, PRIMARY KEY (user_id) )

[User] List all time entries where the description includes the word 'email', showing the entry ID, date worked, hours spent, and description.

[Assistant] SELECT entry_id, date_worked, hours_spent, description FROM legal_services.time_entries WHERE description ILIKE '%email%';

[User] For each peer port, count how many peers have used that port.

[Assistant]
SELECT port,
       COUNT(*) AS peer_count
FROM trading_platform.peers
GROUP BY port;

[User] Retrieve the route number and description for routes whose estimated duration exceeds 120 minutes.

[Assistant]
SELECT route_number, description
FROM transportation.routes
WHERE estimated_duration_minutes > 120;

[User] Also, filter to include only routes with distance greater than 200 km and order by distance_km descending.

[Assistant]
SELECT route_number, description
FROM transportation.routes
WHERE estimated_duration_minutes > 120
  AND distance_km > 200
ORDER BY distance_km DESC;

[User] How many customers are there in each state?

[Assistant]
SELECT state, COUNT(*) AS customer_count
FROM insurance.customers
GROUP BY state;

[User] I need to find all components associated with a specific supplier. Can you help with that?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE

[User] Can you also show me the material ID for each of these components?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE
HGET component:<component_id> material_id

[User] What if I want to exclude components with a specific material ID?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE
HGET component:<component_id> material_id
IF HGET component:<component_id> material_id != 'mat:TI64' THEN INCLUDE

[User] Can you add the component name to the result as well?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE
HGET component:<component_id> material_id
IF HGET component:<component_id> material_id != 'mat:TI64' THEN INCLUDE
HGET component:<component_id> component_name

[User] How many unique email domains are there among all registered users?

[Assistant] SELECT COUNT(DISTINCT SUBSTRING(email FROM '@(.*)$')) AS unique_domains FROM blockchain.users;

[User] Can you list these domains along with the count of users for each domain?

[Assistant] SELECT SUBSTRING(email FROM '@(.*)$') AS domain, COUNT(*) AS user_count FROM blockchain.users GROUP BY domain;

[User] Now show only domains that have more than 10 users.

[Assistant] SELECT SUBSTRING(email FROM '@(.*)$') AS domain, COUNT(*) AS user_count FROM blockchain.users GROUP BY domain HAVING COUNT(*) > 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
CREATE TABLE legal_services.cases ( case_id text PRIMARY KEY, case_number text UNIQUE, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )
##Table Structure
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
##Table Structure
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
##Table Structure
CREATE TABLE transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
##Table Structure
CREATE TABLE blockchain.blocks ( block_id character varying(64) NOT NULL, previous_block_id character varying(64), timestamp timestamp NOT NULL, nonce integer NOT NULL, merkle_root character varying(128) NOT NULL, difficulty integer NOT NULL, PRIMARY KEY (block_id) )

[User] Show me the full name of every lawyer, their specialization, and the number of cases they are the lead lawyer for.

[Assistant]
SELECT CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name, l.specialization, COUNT(c.case_id) AS lead_case_count
FROM legal_services.lawyers l
LEFT JOIN legal_services.cases c ON l.lawyer_id = c.lead_lawyer_id
GROUP BY l.first_name, l.last_name, l.specialization;

[User] Show me the booking ID, fare, and the city of the destination location for all bookings with 'Confirmed' status.

[Assistant] SELECT b.booking_id, b.fare, dl.city AS destination_city FROM transportation.bookings AS b JOIN transportation.trips AS t ON b.trip_id = t.trip_id JOIN transportation.locations AS dl ON t.destination_location_id = dl.location_id WHERE b.status = 'Confirmed';

[User] Instead of 'Confirmed', list 'Completed' bookings from locations in 'California', and order by fare descending.

[Assistant] SELECT b.booking_id, b.fare, dl.city AS destination_city FROM transportation.bookings AS b JOIN transportation.trips AS t ON b.trip_id = t.trip_id JOIN transportation.locations AS dl ON t.destination_location_id = dl.location_id WHERE b.status = 'Completed' AND dl.state_province = 'CA' ORDER BY b.fare DESC;

[User] For each passenger, show their full name, email, and the number of unique trips they have participated in.

[Assistant]
SELECT p.first_name, p.last_name, p.email, COUNT(DISTINCT b.trip_id) AS unique_trips
FROM transportation.passengers p
LEFT JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name, p.email;

[User] List all pairs of tokens that are deployed on the same contract address and have the same number of decimals. Show both token IDs, the shared contract_address, and the decimals value.

[Assistant]
SELECT t1.token_id AS token_id_1, t2.token_id AS token_id_2, t1.contract_address, t1.decimals
FROM web3.tokens t1
JOIN web3.tokens t2
  ON t1.contract_address = t2.contract_address
  AND t1.decimals = t2.decimals
  AND t1.token_id < t2.token_id;

[User] For each fueling event, show its fuel_log_id, vehicle_id, log_timestamp, and the previous fueling event's fuel_log_id, log_timestamp, and quantity for the same vehicle.

[Assistant]
SELECT fl.fuel_log_id,
       fl.vehicle_id,
       fl.log_timestamp AS current_timestamp,
       fl.quantity AS current_quantity,
       prev.fuel_log_id AS previous_fuel_log_id,
       prev.log_timestamp AS previous_timestamp,
       prev.quantity AS previous_quantity
FROM transportation.fuel_logs fl
LEFT JOIN transportation.fuel_logs prev
  ON fl.vehicle_id = prev.vehicle_id
  AND prev.log_timestamp = (
    SELECT MAX(log_timestamp)
    FROM transportation.fuel_logs
    WHERE vehicle_id = fl.vehicle_id
      AND log_timestamp < fl.log_timestamp
  );

[User] Show me the usernames and registration dates for players who registered between '2023-01-01' and '2023-12-31'.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE registration_date >= '2023-01-01' AND registration_date < '2024-01-01';

[User] Show me the block with the earliest timestamp and its corresponding previous block's difficulty level.

[Assistant] SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty FROM blockchain.blocks b1 LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id ORDER BY b1.timestamp ASC LIMIT 1;

[User] Now show me the same information but for the 5 earliest blocks instead of just one.

[Assistant] SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty FROM blockchain.blocks b1 LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id ORDER BY b1.timestamp ASC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.comments ( comment_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, parent_comment_id character varying(64), content text NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (comment_id) )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
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) )
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) )
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )
##Table Structure
CREATE TABLE insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
##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 )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.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 )
CREATE TABLE government_services.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
##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) )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE web3.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 government_services.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] How many likes were given to comments in June 2024?

[Assistant]
SELECT COUNT(*) AS comment_likes_count
FROM social_media.likes
WHERE comment_id IS NOT NULL
  AND DATE_TRUNC('month', created_at) = '2024-06-01';

[User] List policy IDs and policy numbers for policies that have a null cancellation reason.

[Assistant] SELECT policy_id, policy_number FROM insurance.policies WHERE cancellation_reason IS NULL;

[User] Find the names and addresses of service locations where no appointments have been scheduled.

[Assistant] SELECT sl.location_name, sl.address FROM government_services.service_locations sl LEFT JOIN government_services.appointments a ON sl.location_id = a.location_id WHERE a.appointment_id IS NULL;

[User] Can you show me the total number of available services and the average price for each department?

[Assistant] SELECT department, COUNT(*) AS available_service_count, AVG(price) AS average_price FROM hospitality_technology.services WHERE is_available = true GROUP BY department;

[User] Now, include only departments where the average price is greater than 60 and sort by average_price descending.

[Assistant] SELECT department, COUNT(*) AS available_service_count, AVG(price) AS average_price FROM hospitality_technology.services WHERE is_available = true GROUP BY department HAVING AVG(price) > 60 ORDER BY average_price DESC;

[User] Find users who have at least one wallet created before their user registration date. List their username and the address of any such wallet.

[Assistant] SELECT u.username, w.address AS wallet_address FROM web3.users AS u JOIN web3.wallets AS w ON u.user_id = w.user_id WHERE w.created_at < u.created_at;

[User] Find all notifications where the message subject contains the word 'Alert'.

[Assistant] SELECT notification_id, citizen_id, application_id, message_subject, message_body, channel, sent_at, status, related_entity_type, related_entity_id FROM government_services.notifications WHERE message_subject LIKE '%Alert%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.policies ( policy_id 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.drivers ( driver_id text PRIMARY KEY, 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 government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.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.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
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 )
##Table Structure
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 )
##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 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.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )

[User] Find all customers who have at least two active policies with overlapping coverage periods. List the customer ID and the policy numbers of any two such overlapping active policies.

[Assistant]
SELECT
  p1.customer_id,
  p1.policy_number AS policy_number_1,
  p2.policy_number AS policy_number_2
FROM insurance.policies AS p1
JOIN insurance.policies AS p2
  ON p1.customer_id = p2.customer_id
  AND p1.policy_id < p2.policy_id
WHERE
  p1.status = 'Active'
  AND p2.status = 'Active'
  AND p1.start_date <= p2.end_date
  AND p1.end_date >= p2.start_date;

[User] Find all pairs of drivers where one driver's license_expiry_date is earlier than another's. Return each pair's driver_ids, full names, and respective expiry dates.

[Assistant] SELECT d1.driver_id AS driver1_id, d1.first_name || ' ' || d1.last_name AS driver1_name, d1.license_expiry_date AS expiry1, d2.driver_id AS driver2_id, d2.first_name || ' ' || d2.last_name AS driver2_name, d2.license_expiry_date AS expiry2 FROM transportation.drivers d1 JOIN transportation.drivers d2 ON d1.license_expiry_date < d2.license_expiry_date;

[User] Which citizens have received notifications for applications processed by employees from the 'Legal' department? List the citizen ID, full name, and notification ID.

[Assistant]
SELECT n.citizen_id, CONCAT(e.first_name, ' ', e.last_name) AS full_name, n.notification_id
FROM government_services.notifications n
JOIN government_services.payments p ON n.application_id = p.application_id AND n.citizen_id = p.citizen_id
JOIN government_services.employees e ON p.service_id IN (
  SELECT s.service_id
  FROM government_services.services s
  JOIN government_services.agencies a ON s.agency_id = a.agency_id
)
WHERE e.department = 'Legal';

[User] For each origin and destination location pair, provide the total number of trips along with the average actual_arrival time.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival)) AS avg_actual_arrival_epoch FROM transportation.trips GROUP BY origin_location_id, destination_location_id;

[User] Can you also filter this to only include pairs where the trip count is greater than 3?

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival)) AS avg_actual_arrival_epoch FROM transportation.trips GROUP BY origin_location_id, destination_location_id HAVING COUNT(*) > 3;

[User] Instead of the epoch average, show the average difference (in minutes) between scheduled_arrival and actual_arrival for these pairs.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival - scheduled_arrival)/60.0) AS avg_delay_minutes FROM transportation.trips GROUP BY origin_location_id, destination_location_id HAVING COUNT(*) > 3;

[User] List all trips with their trip_id, vehicle_id, and the corresponding origin_location_id and destination_location_id, but only where the origin and destination are not the same.

[Assistant] SELECT trip_id, vehicle_id, origin_location_id, destination_location_id FROM transportation.trips WHERE origin_location_id <> destination_location_id;

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

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name || ' ' || p1.last_name AS patient1_name, p2.patient_id AS patient2_id, p2.first_name || ' ' || p2.last_name AS patient2_name, p1.created_at::date AS registration_date FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.created_at::date = p2.created_at::date AND p1.patient_id < p2.patient_id;

[User] List the name of each law firm along with the first and last name of its managing partner.

[Assistant] SELECT T1.firm_name, T2.first_name, T2.last_name FROM law_firms AS T1 JOIN lawyers AS T2 ON T1.managing_partner_id = T2.lawyer_id

[User] Can you give me a count of players for each player status?

[Assistant] SELECT status, COUNT(player_id) FROM gaming_technology.players GROUP BY status;

[User] Now, only show me the statuses that have fewer than 100 players.

[Assistant] SELECT status, COUNT(player_id) FROM gaming_technology.players GROUP BY status HAVING COUNT(player_id) < 100;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
##Table Structure
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id.text, property_name.text, address_line1.text, address_line2.text, city.text, state_province.text, postal_code.text, country_code.text, phone_number.text, email_address.text, property_type.text, star_rating.numeric, timezone.text, manager_staff_id.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
##Table Structure
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
##Table Structure
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )
##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.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 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 healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] Count how many tokens exist for each contract_address.

[Assistant]
SELECT contract_address,
       COUNT(*) AS token_count
FROM web3.tokens
GROUP BY contract_address;

[User] Now only include contract_address values that have more than 2 tokens.

[Assistant]
SELECT contract_address,
       COUNT(*) AS token_count
FROM web3.tokens
GROUP BY contract_address
HAVING COUNT(*) > 2;

[User] List the appointment_id, patient_id, and reason for all appointments where the notes mention 'urgent'.

[Assistant]
SELECT appointment_id, patient_id, reason
FROM healthcare.appointments
WHERE notes ILIKE '%urgent%';

[User] What is the average delivery time in hours for all delivered service orders?

[Assistant]
SELECT AVG(EXTRACT(EPOCH FROM (so.delivery_timestamp - so.order_timestamp)) / 3600) AS avg_delivery_hours
FROM hospitality_technology.service_orders so
WHERE so.status = 'delivered' AND so.delivery_timestamp IS NOT NULL;

[User] Now only include orders delivered after January 1, 2024.

[Assistant]
SELECT AVG(EXTRACT(EPOCH FROM (so.delivery_timestamp - so.order_timestamp)) / 3600) AS avg_delivery_hours
FROM hospitality_technology.service_orders so
WHERE so.status = 'delivered'
  AND so.delivery_timestamp >= '2024-01-01'::timestamp;

[User] List the names of employees whose job title is the same as their manager's job title. Include the employee's first name, last name, their manager's first name, last name, and their shared job title.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T2.first_name ,  T2.last_name ,  T1.job_title FROM employees AS T1 JOIN employees AS T2 ON T1.manager_employee_id  =  T2.employee_id WHERE T1.job_title  =  T2.job_title

[User] Show the number of UTXOs associated with each unique address in the system.

[Assistant] SELECT address, COUNT(utxo_id) FROM trading_platform.utxos GROUP BY address;

[User] What are the top 5 most recently registered verified citizens? Return the citizen ID, full name, and registration date.

[Assistant]
SELECT citizen_id,
       first_name || ' ' || last_name AS full_name,
       registration_date
FROM government_services.citizens
WHERE is_verified = TRUE
ORDER BY registration_date DESC
LIMIT 5;

[User] List the product ID and product name for all insurance products where the coverage details mention 'warranty'.

[Assistant] SELECT product_id, product_name FROM insurance.insurance_products WHERE coverage_details LIKE '%warranty%';

[User] Please also include the product type and base premium, and only show products that are currently active.

[Assistant] SELECT product_id, product_name, product_type, base_premium FROM insurance.insurance_products WHERE coverage_details LIKE '%warranty%' AND is_active = TRUE;

[User] Show the medication ID, medication name, and manufacturer for all entries where the generic name is not listed.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE generic_name IS NULL OR generic_name = '';

[User] For all medications, list the medication name, generic name, and the length of the description, but only for descriptions longer than 50 characters.

[Assistant] SELECT medication_name, generic_name, LENGTH(description) AS description_length FROM healthcare.medications WHERE LENGTH(description) > 50;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
##Table Structure
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.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 social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) )
CREATE TABLE web3.token_transfers ( transfer_id character varying(64) NOT NULL, token_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128) NOT NULL, value numeric(38,14) NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (transfer_id) )
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 gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
##Table Structure
CREATE TABLE trading_platform.metadata ( metadata_id text, asset_id text, key text, value text )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )

[User] Find all pairs of overlapping payment periods for the same customer. Return customer_id, first payment_id as payment1_id, second payment_id as payment2_id, and both periods' start and end dates.

[Assistant]
SELECT p1.customer_id,
       p1.payment_id AS payment1_id,
       p2.payment_id AS payment2_id,
       p1.payment_period_start AS start1,
       p1.payment_period_end   AS end1,
       p2.payment_period_start AS start2,
       p2.payment_period_end   AS end2
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.customer_id = p2.customer_id
 AND p1.payment_id < p2.payment_id
 -- periods overlap
 AND p1.payment_period_start <= p2.payment_period_end
 AND p2.payment_period_start <= p1.payment_period_end;

[User] How many tokens are there for each number of decimals?

[Assistant] SELECT decimals, COUNT(*) FROM web3.tokens GROUP BY decimals;

[User] Now, only show the decimal counts where there are more than 10 tokens.

[Assistant] SELECT decimals, COUNT(*) FROM web3.tokens GROUP BY decimals HAVING COUNT(*) > 10;

[User] Show the username, full name, and location for all users who registered before January 1, 2024 and are not verified.

[Assistant] SELECT username, full_name, location FROM social_media.users WHERE created_at < '2024-01-01' AND is_verified = false;

[User] Only include those who have a non-empty location.

[Assistant] SELECT username, full_name, location FROM social_media.users WHERE created_at < '2024-01-01' AND is_verified = false AND location IS NOT NULL AND location <> '';

[User] For each token, show its token name, token symbol, the address of the contract it was created on, and the deployer address of that contract.

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

[User] Can you show me the number of servers in each region, as well as the total max_players for each region?

[Assistant] SELECT region, COUNT(*) AS server_count, SUM(max_players) AS total_max_players FROM gaming_technology.servers GROUP BY region;

[User] Actually, can you also include the average number of current players per region?

[Assistant] SELECT region, COUNT(*) AS server_count, SUM(max_players) AS total_max_players, AVG(current_players) AS avg_current_players FROM gaming_technology.servers GROUP BY region;

[User] How many wallets were created in each distinct month?

[Assistant] SELECT DATE_TRUNC('month', created_at) AS creation_month, COUNT(*) AS wallet_count FROM web3.wallets GROUP BY DATE_TRUNC('month', created_at) ORDER BY creation_month;

[User] Filter that to only show months where more than 100 wallets were created.

[Assistant] SELECT DATE_TRUNC('month', created_at) AS creation_month, COUNT(*) AS wallet_count FROM web3.wallets GROUP BY DATE_TRUNC('month', created_at) HAVING COUNT(*) > 100 ORDER BY creation_month;

[User] Which assets have at least two different types of metadata keys, and for each asset, list its asset_id and a comma-separated list of the unique keys?

[Assistant]
SELECT asset_id, string_agg(DISTINCT key, ', ') AS unique_keys
FROM trading_platform.metadata
GROUP BY asset_id
HAVING COUNT(DISTINCT key) >= 2;

[User] Also, show the total count of metadata entries for each asset in the result.

[Assistant]
SELECT asset_id, string_agg(DISTINCT key, ', ') AS unique_keys, COUNT(*) AS metadata_count
FROM trading_platform.metadata
GROUP BY asset_id
HAVING COUNT(DISTINCT key) >= 2;

[User] List the NDC code and description for any medication that has an NDC code starting with '5'.

[Assistant] SELECT ndc_code, description FROM healthcare.medications WHERE ndc_code LIKE '5%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
##Table Structure
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
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 transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
##Table Structure
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
##Table Structure
CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash 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 )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )

[User] How many premium payments are currently in 'Pending' status?

[Assistant] SELECT COUNT(*) FROM insurance.premium_payments WHERE status = 'Pending';

[User] How many notifications have been sent by each sender? Show sender_user_id and notification count.

[Assistant]
SELECT sender_user_id, COUNT(*) AS notification_count
FROM social_media.notifications
WHERE sender_user_id IS NOT NULL
GROUP BY sender_user_id;

[User] List all unique pairs of origin and destination location IDs that have been used in trips, and count how many trips have occurred for each pair.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count FROM transportation.trips GROUP BY origin_location_id, destination_location_id;

[User] List pairs of documents uploaded by the same lawyer but for different cases, showing both document names, their case IDs, and the lawyer ID.

[Assistant] SELECT t1.document_name AS document1_name, t1.case_id AS document1_case_id, t2.document_name AS document2_name, t2.case_id AS document2_case_id, t1.uploaded_by_lawyer_id FROM legal_services.documents AS t1 JOIN legal_services.documents AS t2 ON t1.uploaded_by_lawyer_id = t2.uploaded_by_lawyer_id AND t1.case_id <> t2.case_id AND t1.document_id < t2.document_id;

[User] Find the contract ID, address, and deployer address for all contracts that have not emitted any events.

[Assistant] SELECT c.contract_id, c.address, c.deployer_address FROM web3.contracts AS c LEFT JOIN web3.events AS e ON c.contract_id = e.contract_id WHERE e.event_id IS NULL;

[User] Retrieve route_number, description, and distance_km for routes that have a distance greater than the average distance of all routes.

[Assistant]
SELECT route_number, description, distance_km
FROM transportation.routes
WHERE distance_km > (
  SELECT AVG(distance_km)
  FROM transportation.routes
);

[User] Actually, I only want those routes where estimated_duration_minutes is less than 120, and sort by distance_km in descending order.

[Assistant]
SELECT route_number, description, distance_km
FROM transportation.routes
WHERE distance_km > (
  SELECT AVG(distance_km)
  FROM transportation.routes
)
  AND estimated_duration_minutes < 120
ORDER BY distance_km DESC;

[User] Provide a count of payments for each unique currency type recorded in the system.

[Assistant] SELECT currency, COUNT(*) AS payment_count FROM government_services.payments GROUP BY currency;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.applications ( application_id text, 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.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, 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 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 trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
##Table Structure
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] For each citizen, show their citizen ID and the total number of applications and notifications they have.

[Assistant]
SELECT c.citizen_id,
       COALESCE(a.application_count, 0) AS application_count,
       COALESCE(n.notification_count, 0) AS notification_count
FROM (
    SELECT citizen_id FROM government_services.applications
    UNION
    SELECT citizen_id FROM government_services.notifications
) c
LEFT JOIN (
    SELECT citizen_id, COUNT(*) AS application_count
    FROM government_services.applications
    GROUP BY citizen_id
) a ON c.citizen_id = a.citizen_id
LEFT JOIN (
    SELECT citizen_id, COUNT(*) AS notification_count
    FROM government_services.notifications
    GROUP BY citizen_id
) n ON c.citizen_id = n.citizen_id;

[User] Find all pairs of drivers who share the same status. Include both driver_ids, full names, and the shared status.

[Assistant] SELECT d1.driver_id AS driver1_id, d1.first_name || ' ' || d1.last_name AS driver1_name, d2.driver_id AS driver2_id, d2.first_name || ' ' || d2.last_name AS driver2_name, d1.status FROM transportation.drivers d1 JOIN transportation.drivers d2 ON d1.status = d2.status AND d1.driver_id < d2.driver_id;

[User] Show me the first name, last name, and job title of employees along with the first name and last name of their managers.

[Assistant]
SELECT e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.job_title, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM government_services.employees e
LEFT JOIN government_services.employees m
  ON e.manager_employee_id = m.employee_id;

[User] Can you filter this to only show employees who report to a manager whose job_title is 'Supervisor'?

[Assistant]
SELECT e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.job_title, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM government_services.employees e
JOIN government_services.employees m
  ON e.manager_employee_id = m.employee_id
WHERE m.job_title = 'Supervisor';

[User] Show me the top 3 peers by the number of active days (days they were last seen) in the last month, along with their IP addresses.

[Assistant] SELECT peer_id, ip_address, COUNT(DISTINCT DATE(last_seen)) AS active_days FROM trading_platform.peers WHERE last_seen >= NOW() - INTERVAL '1 month' GROUP BY peer_id, ip_address ORDER BY active_days DESC LIMIT 3;

[User] Show the usernames and email addresses of all users who have never created a post.

[Assistant]
SELECT u.username, u.email
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.post_id IS NULL;

[User] Show me the number of direct replies each top-level comment has on post 'P200'.

[Assistant] SELECT c.comment_id, COUNT(r.comment_id) AS reply_count FROM comments AS c LEFT JOIN comments AS r ON r.parent_comment_id = c.comment_id WHERE c.post_id = 'P200' AND c.parent_comment_id IS NULL GROUP BY c.comment_id;

[User] Order by reply_count descending and limit to top 5.

[Assistant] SELECT c.comment_id, COUNT(r.comment_id) AS reply_count FROM comments AS c LEFT JOIN comments AS r ON r.parent_comment_id = c.comment_id WHERE c.post_id = 'P200' AND c.parent_comment_id IS NULL GROUP BY c.comment_id ORDER BY reply_count DESC LIMIT 5;

[User] How many users currently have their profile set to private?

[Assistant] SELECT COUNT(*) FROM social_media.user_settings WHERE private_profile = true;

[User] Which documents have a version number of at least 5? List their document_name, case_id, and version.

[Assistant]
SELECT document_name, case_id, version
FROM legal_services.documents
WHERE version >= 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.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.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 )
CREATE TABLE government_services.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text, previous_block_id text, timestamp timestamp, nonce integer, merkle_root text, difficulty integer )
##Table Structure
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.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) )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )
##Table Structure
// 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 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 web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )

[User] List the names of employees and the agency they work for who have scheduled at least one appointment. Show the employee's first name, last name, and agency_id.

[Assistant]
SELECT DISTINCT e.first_name, e.last_name, e.agency_id
FROM government_services.employees e
JOIN government_services.appointments a ON e.employee_id = a.employee_id;

[User] List all appointments that were marked as 'No-show'. Show appointment ID, patient ID, and appointment time.

[Assistant] SELECT appointment_id, patient_id, appointment_time FROM healthcare.appointments WHERE status = 'No-show';

[User] Show me the block with the earliest timestamp and its corresponding previous block's difficulty level.

[Assistant]
SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty
FROM blockchain.blocks b1
LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id
ORDER BY b1.timestamp ASC
LIMIT 1;

[User] Now show me the same information but for the 5 earliest blocks instead of just one.

[Assistant]
SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty
FROM blockchain.blocks b1
LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id
ORDER BY b1.timestamp ASC
LIMIT 5;

[User] Show me all notifications where the target entity type is 'comment', and for each notification, include the content of the corresponding comment.

[Assistant] SELECT n.*, c.content AS comment_content FROM social_media.notifications n JOIN social_media.comments c ON n.target_entity_id = c.comment_id WHERE n.target_entity_type = 'comment';

[User] Now, only include notifications that are of type 'like' or 'reply'.

[Assistant] SELECT n.*, c.content AS comment_content FROM social_media.notifications n JOIN social_media.comments c ON n.target_entity_id = c.comment_id WHERE n.target_entity_type = 'comment' AND n.notification_type IN ('like', 'reply');

[User] Which medications do not have a generic name listed? Show their medication_id, medication_name, and manufacturer.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE generic_name IS NULL OR generic_name = '';

[User] Could you also include the description for each medication?

[Assistant] SELECT medication_id, medication_name, manufacturer, description FROM healthcare.medications WHERE generic_name IS NULL OR generic_name = '';

[User] 特定の予約ID 'book_zyx' に関連するすべてのチケットの詳細を取得するのを手伝っていただけますか？また、関連する車両情報も含めてください。

[Assistant]
SMEMBERS booking:book_zyx:tickets
HGETALL ticket:<ticket_id>
HGETALL car:<car_id>

[User] チェックイン済みのチケットだけを表示するようにフィルタリングしていただけますか？

[Assistant]
SMEMBERS booking:book_zyx:tickets
HGET ticket:<ticket_id> is_checked_in
HGETALL ticket:<ticket_id> (only if is_checked_in = 1)
HGETALL car:<car_id>

[User] 座席番号も結果に含めて、座席番号順に並べ替えることは可能ですか？

[Assistant]
SMEMBERS booking:book_zyx:tickets
HGET ticket:<ticket_id> is_checked_in
HGETALL ticket:<ticket_id> (only if is_checked_in = 1)
HGETALL car:<car_id>
(Sort results by seat_number in ascending order)

[User] 車両IDごとにチケットの総数を追加していただけますか？

[Assistant]
SMEMBERS booking:book_zyx:tickets
HGET ticket:<ticket_id> is_checked_in
HGETALL ticket:<ticket_id> (only if is_checked_in = 1)
HGETALL car:<car_id>
(Group by car_id and count total tickets per car_id)
(Sort results by seat_number in ascending order)

[User] Show me the top 10 token transfers by value, including the token ID and the transaction ID, sorted in descending order.

[Assistant] SELECT token_id, transaction_id, value FROM web3.token_transfers ORDER BY value DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
// db.createCollection('platforms')
// Optional: db.platforms.createIndex({ platform_id: 1 }, { unique: true })
// Optional: db.platforms.createIndex({ station_id: 1 })
{
  _id: ObjectId(),
  platform_id: "plat_123", // String (unique)
  station_id: "station_xyz", // String (references stations.station_id)
  platform_number: "1A", // String
  track_number: "T1", // String
  status: "Operational", // String ('Operational', 'Maintenance', 'Closed')
  length_meters: 250.50, // Decimal128 or Double
  accessible: true // Boolean
}
// db.createCollection('routes')
// Optional: db.routes.createIndex({ route_id: 1 }, { unique: true })
{
  _id: ObjectId(),
  route_id: "route_ne_corr", // String (unique)
  route_name: "Northeast Corridor", // String
  description: "High-speed rail linking Boston and Washington D.C.", // String
  origin_station_id: "station_bos", // String (references stations.station_id)
  destination_station_id: "station_was", // String (references stations.station_id)
  is_active: true // Boolean
}
// db.createCollection('route_stations')
// Optional: db.route_stations.createIndex({ route_station_id: 1 }, { unique: true })
// Optional: db.route_stations.createIndex({ route_id: 1, sequence_order: 1 }, { unique: true })
{
  _id: ObjectId(),
  route_station_id: "rs_ne_1", // String (unique)
  route_id: "route_ne_corr", // String (references routes.route_id)
  station_id: "station_bos", // String (references stations.station_id)
  sequence_order: 1, // Int32
  distance_from_previous_km: null, // Decimal128 or Double (null for first stop)
  typical_stop_duration_minutes: null // Int32 (null for origin/destination or if no stop)
}
// --- OR --- Embed within the Route document:
// {
//   _id: ObjectId(), route_id: "route_ne_corr", ...,
//   stations: [
//     { station_id: "station_bos", sequence_order: 1, distance_from_previous_km: null, typical_stop_duration_minutes: null },
//     { station_id: "station_pvd", sequence_order: 2, distance_from_previous_km: 70.5, typical_stop_duration_minutes: 5 },
//     ...
//   ]
// }
// db.createCollection('schedules')
// Optional: db.schedules.createIndex({ schedule_id: 1 }, { unique: true })
// Optional: db.schedules.createIndex({ route_id: 1, departure_datetime: 1 })
{
  _id: ObjectId(),
  schedule_id: "sched_1122", // String (unique)
  train_id: "train_789", // String (references trains.train_id)
  route_id: "route_ne_corr", // String (references routes.route_id)
  departure_datetime: ISODate("2024-05-10T08:00:00-04:00"), // Date (with timezone)
  arrival_datetime: ISODate("2024-05-10T15:30:00-04:00"), // Date (with timezone)
  status: "Scheduled", // String ('Scheduled', 'On Time', 'Delayed', 'Cancelled', 'Arrived')
  notes: "Track work expected near Philadelphia" // String
}
// db.createCollection('schedule_stops')
// Optional: db.schedule_stops.createIndex({ stop_id: 1 }, { unique: true })
// Optional: db.schedule_stops.createIndex({ schedule_id: 1, sequence_order: 1 }, { unique: true })
{
  _id: ObjectId(),
  stop_id: "stop_sched1122_1", // String (unique)
  schedule_id: "sched_1122", // String (references schedules.schedule_id)
  station_id: "station_bos", // String (references stations.station_id)
  platform_id: "plat_bos_3", // String (references platforms.platform_id, nullable)
  sequence_order: 1, // Int32
  scheduled_arrival_time: null, // Date
  scheduled_departure_time: ISODate("2024-05-10T08:00:00-04:00"), // Date
  actual_arrival_time: null, // Date
  actual_departure_time: ISODate("2024-05-10T08:01:00-04:00"), // Date
  status: "On Time" // String
}
// --- OR --- Embed within the Schedule document using an array 'stops'
// db.createCollection('passengers')
// Optional: db.passengers.createIndex({ passenger_id: 1 }, { unique: true })
// Optional: db.passengers.createIndex({ email: 1 }, { unique: true, sparse: true })
// Optional: db.passengers.createIndex({ phone_number: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  passenger_id: "pass_pqr", // String (unique)
  first_name: "Alice", // String
  last_name: "Smith", // String
  email: "alice.smith@example.com", // String (unique, sparse)
  phone_number: "+15551234567", // String (unique, sparse)
  date_of_birth: ISODate("1990-03-20"), // Date
  loyalty_program_id: "LOYALTY123", // String
  created_at: ISODate("2023-02-01T11:00:00Z") // Date
}
// db.createCollection('staff')
// Optional: db.staff.createIndex({ staff_id: 1 }, { unique: true })
// Optional: db.staff.createIndex({ employee_number: 1 }, { unique: true })
// Optional: db.staff.createIndex({ contact_email: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  staff_id: "staff_mno", // String (unique)
  first_name: "Bob", // String
  last_name: "Jones", // String
  role: "Conductor", // String
  primary_station_id: null, // String (references stations.station_id, nullable)
  employee_number: "E12345", // String (unique)
  hire_date: ISODate("2018-06-01"), // Date
  contact_email: "bob.jones@example-rail.com", // String (unique, sparse)
  contact_phone: "+15559876543", // String
  is_active: true // Boolean
}
##Table Structure
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 web3.events ( event_id text PRIMARY KEY, contract_id text, event_name text, data text, emitted_at timestamp, transaction_id text, log_index int )

[User] Can you help me get the total number of operational platforms across all stations?

[Assistant] db.platforms.countDocuments({ status: 'Operational' });

[User] Show me the top 5 users with the most KYC audits, along with their latest audit status.

[Assistant] SELECT user_id, status, COUNT(*) as audit_count FROM trading_platform.kyc_audit GROUP BY user_id, status ORDER BY audit_count DESC LIMIT 5;

[User] Now modify the query to show only users whose latest KYC status was rejected.

[Assistant] WITH latest_audit AS (SELECT user_id, status, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY reviewed_at DESC) as rn FROM trading_platform.kyc_audit) SELECT user_id, status FROM latest_audit WHERE rn = 1 AND status = 'rejected' LIMIT 5;

[User] Actually, I want to see the count of rejected audits per user instead of just the latest status.

[Assistant] SELECT user_id, COUNT(*) as rejected_count FROM trading_platform.kyc_audit WHERE status = 'rejected' GROUP BY user_id ORDER BY rejected_count DESC LIMIT 5;

[User] Find all events where the data field contains 'amount' and show the event name, contract ID, and transaction ID, along with the log index, sorted by log index in ascending order.

[Assistant] SELECT event_name, contract_id, transaction_id, log_index FROM web3.events WHERE data LIKE '%amount%' ORDER BY log_index ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.transactions ( transaction_id.text, from_address.text, to_address.text, value.numeric, gas_used.integer, gas_price.numeric, block_number.integer, timestamp.timestamp, input_data.text, status.text, nonce.integer )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
##Table Structure
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 )
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )

[User] Provide the message_subject and agency_name for all notifications that are related to agencies and have a status of 'Sent'.

[Assistant]
SELECT n.message_subject, a.agency_name
FROM government_services.notifications n
JOIN government_services.agencies a ON n.related_entity_id = a.agency_id
WHERE n.related_entity_type = 'agency' AND n.status = 'Sent';

[User] Find all tokens with their contract addresses and the number of wallets that hold each token, sorted by wallet count in descending order.

[Assistant] SELECT t.token_id, t.contract_address, COUNT(DISTINCT w.wallet_id) AS wallet_count FROM web3.tokens t LEFT JOIN web3.transactions tr ON t.contract_address = tr.to_address OR t.contract_address = tr.from_address JOIN web3.wallets w ON tr.from_address = w.address OR tr.to_address = w.address GROUP BY t.token_id, t.contract_address ORDER BY wallet_count DESC;

[User] How many insurance policies does each subscriber have? Please display the subscriber name and policy count.

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

[User] Please include only subscribers who have more than one policy.

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

[User] Find pairs of wallets that were created at the exact same timestamp but are owned by different users. List the IDs of both wallets and the shared creation timestamp.

[Assistant]
SELECT
    w1.wallet_id AS wallet1_id,
    w2.wallet_id AS wallet2_id,
    w1.created_at
FROM
    web3.wallets w1
JOIN
    web3.wallets w2 ON w1.created_at = w2.created_at
WHERE
    w1.wallet_id < w2.wallet_id
    AND w1.user_id != w2.user_id;

[User] Provide a list of all email addresses used by citizens whose national ID number starts with 'X'.

[Assistant] SELECT contact_email FROM government_services.citizens WHERE national_id_number LIKE 'X%';

[User] Show the payment_id and amount_paid for all premium payments where the status is 'pending'.

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

[User] List all unavailable services along with their names, prices, and the departments they belong to.

[Assistant] SELECT service_name, price, department FROM hospitality_technology.services WHERE is_available = false;

[User] Only include services that are priced below 30 and belong to the 'Laundry' or 'Housekeeping' departments.

[Assistant] SELECT service_name, price, department FROM hospitality_technology.services WHERE is_available = false AND price < 30 AND department IN ('Laundry', 'Housekeeping');

[User] Count how many assets have metadata entries for each metadata key, and list the metadata key and asset_count ordered by asset_count descending.

[Assistant]
SELECT key,
       COUNT(DISTINCT asset_id) AS asset_count
FROM trading_platform.metadata
GROUP BY key
ORDER BY asset_count DESC;