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 trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.stations (
    station_id character varying(64) NOT NULL,  -- Unique identifier for the station
    station_name character varying(128) NOT NULL, -- Name of the station
    city character varying(100) NOT NULL, -- City where the station is located
    state_province character varying(100), -- State or province
    country_code character varying(3) NOT NULL, -- ISO country code
    address text, -- Full address of the station
    timezone character varying(64) NOT NULL, -- Timezone ID (e.g., 'America/New_York')
    number_of_platforms integer NOT NULL DEFAULT 0, -- Total number of platforms
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When the station record was created
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When the station record was last updated
    PRIMARY KEY (station_id)
)
##Table Structure
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 token_basic_info ( coin_id character varying(100) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, token_address character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, highest_price_24h double precision, lowest_price_24h double precision, market_cap double precision, market_cap_rank bigint, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank bigint )
##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 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 insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
##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 )
##Table Structure
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 )
##Table Structure
CREATE TABLE web3.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) )

[User] For each token, show its token_id, decimals, and the average total_supply of all tokens with the same decimals.

[Assistant]
SELECT t.token_id,
       t.decimals,
       avg_data.avg_total_supply
FROM web3.tokens t
JOIN (
  SELECT decimals,
         AVG(total_supply) AS avg_total_supply
  FROM web3.tokens
  GROUP BY decimals
) AS avg_data
  ON t.decimals = avg_data.decimals;

[User] Show all users who have no wallets yet.

[Assistant]
SELECT DISTINCT k.user_id
FROM trading_platform.kyc_audit k
LEFT JOIN trading_platform.wallets w ON k.user_id = w.user_id
WHERE w.wallet_id IS NULL;

[User] What is the current number of passengers at station with ID 'ST123' right now?

[Assistant] I'm sorry, but I can't provide information on the current number of passengers at a station. The data I have access to only includes static details about stations such as their name, location, and number of platforms, not real-time passenger counts.

[User] List the IDs of citizens who have received notifications related to more than one distinct type of entity.

[Assistant] SELECT citizen_id FROM government_services.notifications WHERE related_entity_type IS NOT NULL AND related_entity_type != '' GROUP BY citizen_id HAVING COUNT(DISTINCT related_entity_type) > 1;

[User] List all tokens with a price below $1 and a 24-hour trading volume over $5 million.

[Assistant] SELECT token_name, token_symbol, price, total_volume FROM token_basic_info WHERE price < 1 AND total_volume::numeric > 5000000;

[User] List all pairs of wallets with the same creation timestamp but different wallet addresses, including both wallet_ids and the creation timestamp.

[Assistant]
SELECT w1.wallet_id AS wallet_id_1, w2.wallet_id AS wallet_id_2, w1.created_at
FROM web3.wallets w1
JOIN web3.wallets w2
  ON w1.created_at = w2.created_at
     AND w1.address <> w2.address
     AND w1.wallet_id < w2.wallet_id;

[User] List each unique plan_id and the total number of patients enrolled in that plan.

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

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

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

[User] Show the names and phone numbers of all law firms whose website ends with '.org'.

[Assistant]
SELECT firm_name, phone
FROM legal_services.law_firms
WHERE website LIKE '%.org';

[User] Find pairs of notifications for the same citizen where one was sent via 'Email' and another via 'SMS'. Display citizen_id, email_notification_id, sms_notification_id, email_sent_at, and sms_sent_at.

[Assistant]
SELECT e.citizen_id,
       e.notification_id AS email_notification_id,
       s.notification_id AS sms_notification_id,
       e.sent_at           AS email_sent_at,
       s.sent_at           AS sms_sent_at
FROM government_services.notifications e
JOIN government_services.notifications s
  ON e.citizen_id = s.citizen_id
 AND e.channel = 'Email'
 AND s.channel = 'SMS';

[User] List the content and creation time of all posts made in the last 7 days.

[Assistant] SELECT content, created_at FROM social_media.posts WHERE created_at >= NOW() - INTERVAL '7 day';

[User] For each user, can you list all their wallet addresses and the creation timestamps of those wallets?

[Assistant] SELECT user_id, address, created_at FROM web3.wallets ORDER BY user_id, created_at;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.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.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )
##Table Structure
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##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.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
##Table Structure
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
##Table Structure
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)

[User] List every booking together with the route number and description for the trip being booked.

[Assistant]
SELECT b.booking_id, b.passenger_id, b.trip_id, r.route_number, r.description
FROM transportation.bookings b
JOIN transportation.routes r ON b.trip_id = r.route_id;

[User] How many agents were hired in the year 2023?

[Assistant] SELECT COUNT(*) AS agents_hired_2023 FROM insurance.agents WHERE hire_date BETWEEN '2023-01-01' AND '2023-12-31';

[User] Retrieve all unique chief complaints from medical_records.

[Assistant]
SELECT DISTINCT chief_complaint
FROM healthcare.medical_records;

[User] Now show chief complaints that occur more than 3 times along with their occurrence count.

[Assistant]
SELECT chief_complaint,
       COUNT(*) AS complaint_count
FROM healthcare.medical_records
GROUP BY chief_complaint
HAVING COUNT(*) > 3;

[User] I need a list of all group chat names with every username.

[Assistant]
SELECT u.username, c.group_name
FROM social_media.users u
JOIN social_media.conversations c ON 1=1
WHERE c.is_group_chat = true;

[User] Actually, only include users who are verified.

[Assistant]
SELECT u.username, c.group_name
FROM social_media.users u
JOIN social_media.conversations c ON 1=1
WHERE c.is_group_chat = true
  AND u.is_verified = true;

[User] List all pairs of clients who registered on the same day, showing each client's first_name, last_name, and the registration date.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, DATE(c1.date_registered) AS registration_date FROM legal_services.clients c1 JOIN legal_services.clients c2 ON DATE(c1.date_registered) = DATE(c2.date_registered) AND c1.client_id < c2.client_id;

[User] Calculate the total value of unspent UTXOs for each user whose KYC status has been 'approved'.

[Assistant] SELECT kyc.user_id, SUM(u.amount) FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status = 'approved' AND u.spent = false GROUP BY kyc.user_id;

[User] Refine that to only show users where this total value exceeds 1000.

[Assistant] SELECT kyc.user_id, SUM(u.amount) FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status = 'approved' AND u.spent = false GROUP BY kyc.user_id HAVING SUM(u.amount) > 1000;

[User] How many game sessions started on each calendar day?

[Assistant] SELECT DATE(start_time), COUNT(*) FROM gaming_technology.game_sessions GROUP BY DATE(start_time) ORDER BY DATE(start_time);

[User] Only display days that had more than 100 sessions.

[Assistant] SELECT DATE(start_time), COUNT(*) FROM gaming_technology.game_sessions GROUP BY DATE(start_time) HAVING COUNT(*) > 100 ORDER BY DATE(start_time);

[User] Find all service locations whose postal code starts with '75' and display their names, cities, and operating hours, including the agency ID.

[Assistant] SELECT location_name, city, operating_hours, agency_id FROM government_services.service_locations WHERE postal_code LIKE '75%';


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, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.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 )
##Table Structure
CREATE TABLE smart_money_profit ( address.text, rank.numeric, profit.numeric, roi.numeric, realized_ratio.numeric, most_profit_token.text, last_trade_time.text, chain.text )
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
##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) )
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 )
##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 )
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
##Table Structure
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )

[User] List all invoices that were paid within 7 days of their issue date. Show invoice number, issue date, payment date, and total amount.

[Assistant] SELECT invoice_number, issue_date, payment_date, total_amount FROM legal_services.invoices WHERE status = 'Paid' AND payment_date IS NOT NULL AND (payment_date::DATE - issue_date) <= 7;

[User] For each pair of origin and destination location IDs, show the number of completed trips between them.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS completed_trip_count FROM transportation.trips WHERE status = 'Completed' GROUP BY origin_location_id, destination_location_id;

[User] How many addresses have a realized_ratio below 0.5?

[Assistant] SELECT COUNT(*) AS address_count FROM smart_money_profit WHERE realized_ratio < 0.5;

[User] For each state, count the number of customers and display state as state and the count as customer_count, ordered by customer_count descending.

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

[User] Show the full names and contact emails of all citizens who have applied for services with a standard fee greater than 100.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.services s ON c.citizen_id IS NOT NULL -- Replace with actual application linking table if exists
WHERE s.standard_fee > 100;

[User] For each citizen, find the timestamp of their first 'SMS' notification and their first 'Email' notification. Show citizen_id, first_sms_at, and first_email_at.

[Assistant]
SELECT citizen_id,
       MIN(sent_at) FILTER (WHERE channel = 'SMS')   AS first_sms_at,
       MIN(sent_at) FILTER (WHERE channel = 'Email') AS first_email_at
FROM government_services.notifications
GROUP BY citizen_id;

[User] How many beneficiaries were added on each unique date?

[Assistant] SELECT DATE(added_at), COUNT(*) FROM insurance.policy_beneficiaries GROUP BY DATE(added_at);

[User] What is the total investment_value per fundraising round for the year 2023? Order by total investment descending.

[Assistant]
SELECT
  substr(investment_date,1,7) AS month,
  rounds_name,
  SUM(investment_value) AS total_investment
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%'
GROUP BY substr(investment_date,1,7), rounds_name
ORDER BY total_investment DESC;

[User] Show all insurance plans where the plan name includes the word 'Care'.

[Assistant]
SELECT plan_id, plan_name, insurance_provider, plan_type
FROM healthcare.insurance_plans
WHERE plan_name ILIKE '%Care%';

[User] List all tokens along with the contract addresses for symbols that appear more than once.

[Assistant]
SELECT t.token_id, t.token_symbol, t.contract_address
FROM web3.tokens t
JOIN (
  SELECT token_symbol
  FROM web3.tokens
  GROUP BY token_symbol
  HAVING COUNT(*) > 1
) dup ON t.token_symbol = dup.token_symbol;

[User] List all distinct asset types from the assets table.

[Assistant]
SELECT DISTINCT type
FROM trading_platform.assets;

[User] Show me, for each game, the achievement that has been unlocked by the most players. Include the game title, achievement name, and the number of players who unlocked it.

[Assistant] WITH RankedAchievements AS ( SELECT pa.achievement_id, COUNT(pa.player_id) AS unlock_count, ROW_NUMBER() OVER(PARTITION BY a.game_id ORDER BY COUNT(pa.player_id) DESC) as rn FROM player_achievements pa JOIN gaming_technology.achievements a ON pa.achievement_id = a.achievement_id GROUP BY pa.achievement_id, a.game_id ) SELECT g.title AS game_title, a.name AS achievement_name, ra.unlock_count FROM RankedAchievements ra JOIN gaming_technology.achievements a ON ra.achievement_id = a.achievement_id JOIN games g ON a.game_id = g.game_id WHERE ra.rn = 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
##Table Structure
CREATE TABLE 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 )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
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 )
##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 government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##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) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
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) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id 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) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text PRIMARY KEY, from_address text, to_address text, value numeric, gas_used int, gas_price numeric, block_number int, timestamp timestamp, input_data text, status text, nonce int )

[User] I would like to see a list of agencies and the names of their respective parent agencies.

[Assistant]
SELECT a.agency_id, a.agency_name, p.agency_name AS parent_agency_name
FROM government_services.agencies a
LEFT JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id;

[User] Could you only show agencies that actually have a parent agency, and order the result by the agency name?

[Assistant]
SELECT a.agency_id, a.agency_name, p.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
ORDER BY a.agency_name;

[User] For each sender address that has sent at least 10 transactions, show the address and the total gas used by their transactions.

[Assistant]
SELECT from_address, SUM(gas_used) AS total_gas_used
FROM web3.transactions
GROUP BY from_address
HAVING COUNT(*) >= 10;

[User] Show each law firm's name and the number of cases where its managing partner is the lead attorney.

[Assistant] SELECT T1.firm_name, COUNT(T2.case_id) AS case_count_as_managing_partner FROM law_firms AS T1 JOIN cases AS T2 ON T1.managing_partner_id = T2.lead_lawyer_id GROUP BY T1.firm_name;

[User] Only include firms that have at least 2 such cases.

[Assistant] SELECT T1.firm_name, COUNT(T2.case_id) AS case_count_as_managing_partner FROM law_firms AS T1 JOIN cases AS T2 ON T1.managing_partner_id = T2.lead_lawyer_id GROUP BY T1.firm_name HAVING COUNT(T2.case_id) >= 2;

[User] Show the usernames of users who have used any hashtag in their posts, along with the tag name.

[Assistant] SELECT DISTINCT T1.username, T4.tag_name FROM social_media.users AS T1 JOIN posts AS T2 ON T1.user_id = T2.user_id JOIN post_hashtags AS T3 ON T2.post_id = T3.post_id JOIN hashtags AS T4 ON T3.hashtag_id = T4.hashtag_id;

[User] Only include users who have used hashtags more than 3 times across all their posts.

[Assistant] SELECT T1.username, COUNT(T3.hashtag_id) AS hashtag_usage_count FROM social_media.users AS T1 JOIN posts AS T2 ON T1.user_id = T2.user_id JOIN post_hashtags AS T3 ON T2.post_id = T3.post_id GROUP BY T1.username HAVING COUNT(T3.hashtag_id) > 3;

[User] For each notification, list the next notification sent to the same citizen (if any). Show citizen_id, notification_id, sent_at, next_notification_id, and next_sent_at.

[Assistant]
SELECT
  n1.citizen_id,
  n1.notification_id,
  n1.sent_at,
  n2.notification_id AS next_notification_id,
  n2.sent_at         AS next_sent_at
FROM government_services.notifications n1
LEFT JOIN government_services.notifications n2
  ON n1.citizen_id = n2.citizen_id
  AND n2.sent_at = (
    SELECT MIN(sent_at)
    FROM government_services.notifications n3
    WHERE n3.citizen_id = n1.citizen_id
      AND n3.sent_at > n1.sent_at
  );

[User] Count the number of registered citizens by gender.

[Assistant]
SELECT
  gender,
  COUNT(*) AS citizen_count
FROM government_services.citizens
GROUP BY gender;

[User] Show all transactions where the transaction value is greater than the average value of all transactions, including transaction_id, from_address, to_address, value, and timestamp.

[Assistant]
SELECT transaction_id, from_address, to_address, value, timestamp
FROM web3.transactions
WHERE value > (SELECT AVG(value) FROM web3.transactions);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
##Table Structure
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) )
##Table Structure
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 )
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
##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)
)
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)
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)
)
##Table Structure
CREATE TABLE financial_services.securities ( security_id text PRIMARY KEY, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )
##Table Structure
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )

[User] Show me the count of achievements that are hidden versus those that are not hidden.

[Assistant] SELECT hidden, COUNT(*) FROM achievements GROUP BY hidden;

[User] Include the average points for each group as well.

[Assistant] SELECT hidden, COUNT(*), AVG(points) FROM achievements GROUP BY hidden;

[User] Could you also add the average length of the description for each group?

[Assistant] SELECT hidden, COUNT(*), AVG(points), AVG(LENGTH(description)) FROM achievements GROUP BY hidden;

[User] Filter the results to only show groups that have more than 5 achievements.

[Assistant] SELECT hidden, COUNT(*), AVG(points), AVG(LENGTH(description)) FROM achievements GROUP BY hidden HAVING COUNT(*) > 5;

[User] List pairs of transfer IDs that occurred sequentially (log_index difference is 1) within the same transaction. Show the transaction ID, the first transfer ID, the second transfer ID, and their log indices.

[Assistant] SELECT t1.transaction_id, t1.transfer_id AS first_transfer_id, t2.transfer_id AS second_transfer_id, t1.log_index AS first_log_index, t2.log_index AS second_log_index FROM web3.token_transfers t1 JOIN web3.token_transfers t2 ON t1.transaction_id = t2.transaction_id AND t2.log_index = t1.log_index + 1;

[User] Show the count of posts for each distinct media type.

[Assistant] SELECT media_type, COUNT(*) FROM social_media.posts GROUP BY media_type;

[User] Only include posts created after June 1, 2024.

[Assistant] SELECT media_type, COUNT(*) FROM social_media.posts WHERE created_at >= '2024-06-01' GROUP BY media_type;

[User] List the diagnosis ID, description, and diagnosis date for all non-chronic diagnoses recorded for patient 'pat123'.

[Assistant] SELECT diagnosis_id, description, diagnosis_date FROM healthcare.diagnoses WHERE patient_id = 'pat123' AND is_chronic = false;

[User] Okay, now show me the count of non-chronic diagnoses for patient 'pat123' for each doctor who has also recorded at least one *chronic* diagnosis for that same patient. Display the doctor ID and the count of non-chronic diagnoses.

[Assistant] SELECT d1.doctor_id, COUNT(d1.diagnosis_id) AS non_chronic_count FROM healthcare.diagnoses d1 WHERE d1.patient_id = 'pat123' AND d1.is_chronic = false AND EXISTS (SELECT 1 FROM healthcare.diagnoses d2 WHERE d2.patient_id = d1.patient_id AND d2.doctor_id = d1.doctor_id AND d2.is_chronic = true) GROUP BY d1.doctor_id;

[User] List each wallet that has received tokens of more than one distinct token type. Show wallet_id, address, the number of distinct tokens received as distinct_token_count, and the total received value, ordered by total_received_value descending.

[Assistant]
SELECT w.wallet_id,
       w.address,
       COUNT(DISTINCT t.token_id) AS distinct_token_count,
       SUM(tt.value)            AS total_received_value
FROM web3.wallets w
JOIN web3.token_transfers tt
  ON w.address = tt.to_address
JOIN web3.tokens t
  ON tt.token_id = t.token_id
GROUP BY w.wallet_id, w.address
HAVING COUNT(DISTINCT t.token_id) > 1
ORDER BY total_received_value DESC;

[User] Can you provide a summary of how many securities exist for each combination of exchange and sector?

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
GROUP BY exchange, sector;

[User] Please exclude any records where sector is NULL.

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
WHERE sector IS NOT NULL
GROUP BY exchange, sector;

[User] Finally, sort the output by total_count in descending order.

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
WHERE sector IS NOT NULL
GROUP BY exchange, sector
ORDER BY total_count DESC;

[User] List the user ID, theme, and updated_at for users who have updated their settings in the last 90 days and have their theme set to 'dark'.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE updated_at >= NOW() - INTERVAL '90 days' AND theme = 'dark';

[User] Refine the list to only show users who have also disabled push notifications.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE updated_at >= NOW() - INTERVAL '90 days' AND theme = 'dark' AND push_notifications_enabled = FALSE;


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. You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE manufacturing.aircraft_models ( model_id text PRIMARY KEY, model_name text, manufacturer text, passenger_capacity int, max_range_km int, engine_type text, wingspan_m numeric, status text, first_flight_date date )
##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 smart_money_token_inflow ( token_address.text, token_symbol.text, token_amount.numeric, usd_value.numeric, avg_price.numeric, type.numeric, address_amount.numeric, narrative.text, chain.text )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
##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 )
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
##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 social_media.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
##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) ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.train_cars ( car_id character varying(64) NOT NULL, train_id character varying(64) NOT NULL, car_number character varying(10) NOT NULL, car_type character varying(64) NOT NULL, class character varying(32), capacity integer, features text, PRIMARY KEY (car_id), FOREIGN KEY (train_id) REFERENCES train_station_management.trains(train_id) ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.stations ( station_id text PRIMARY KEY, station_name text, city text, state_province text, country_code text, address text, timezone text, number_of_platforms int, created_at timestamp, last_updated_at timestamp )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
##Table Structure
CREATE TABLE 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 ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE manufacturing.aircraft_models ( model_id text, model_name text, manufacturer text, passenger_capacity integer, max_range_km integer, engine_type text, wingspan_m numeric, status text, first_flight_date date )
##Table Structure
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )

[User] What are the environmental impact assessments for the production of the Airbus A350 model?

[Assistant] I'm sorry, but I don't have access to data regarding the environmental impact assessments for the production of specific aircraft models like the Airbus A350. My information is limited to the technical specifications and basic details stored in the database, such as model name, manufacturer, and capacity. If you have a question related to the available data, I'd be happy to assist.

[User] How many documents are there for each document_type? Show document_type and count ordered by the count in descending order.

[Assistant]
SELECT document_type,
       COUNT(*) AS count
FROM legal_services.documents
GROUP BY document_type
ORDER BY count DESC;

[User] What is the average USD value per address for each narrative across all chains?

[Assistant]
SELECT
  narrative,
  AVG(usd_value / NULLIF(address_amount, 0)) AS avg_usd_per_address
FROM smart_money_token_inflow
GROUP BY narrative;

[User] List the first_name, last_name, and email of all clients whose email domain is 'gmail.com'.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE SUBSTRING(email FROM POSITION('@' IN email) + 1) = 'gmail.com';

[User] List all users who signed up in 2024 and have not set a bio. Show their usernames, emails, and account creation dates.

[Assistant] SELECT username, email, created_at FROM social_media.users WHERE bio IS NULL AND EXTRACT(YEAR FROM created_at) = 2024;

[User] List all claim documents where the description contains the word 'invoice'.

[Assistant] SELECT document_id, claim_id, file_name, description FROM insurance.claim_documents WHERE description ILIKE '%invoice%';

[User] Count how many users have not specified a value for their bio.

[Assistant] SELECT COUNT(*) FROM social_media.users WHERE bio IS NULL OR bio = '';

[User] How many messages include a media attachment?

[Assistant] SELECT COUNT(*) FROM social_media.messages WHERE media_url IS NOT NULL AND TRIM(media_url) <> '';

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

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

[User] Can you provide a count of users for each unique email domain?

[Assistant] SELECT SUBSTRING(email FROM POSITION('@' IN email) + 1), COUNT(*) FROM blockchain.users GROUP BY SUBSTRING(email FROM POSITION('@' IN email) + 1);

[User] What is the maintenance schedule for the train car with car_id 'CAR456'?

[Assistant] I'm sorry, but I can't provide information about the maintenance schedule for train cars as it is not included in the data available in the train_cars table.

[User] What is the maintenance schedule for the platforms at the station with ID 'ST234' for the next month?

[Assistant] I'm sorry, but I don't have access to the maintenance schedule for the platforms at any station. The data I have only includes basic station information such as station ID, name, location, and number of platforms. For maintenance schedules, you may need to contact the station management or relevant authorities.

[User] For each driver, show their driver_id, email, and the number of days until their license expires.

[Assistant]
SELECT driver_id, email, (license_expiry_date - CURRENT_DATE) AS days_until_expiry
FROM transportation.drivers;

[User] Count the number of completed premium payments grouped by payment_method.

[Assistant]
SELECT payment_method,
       COUNT(*) AS payment_count
FROM insurance.premium_payments
WHERE status = 'Completed'
GROUP BY payment_method;

[User] What are the safety ratings or crash statistics for the Boeing 787 Dreamliner?

[Assistant] I'm sorry, but I don't have access to safety ratings or crash statistics for specific aircraft models like the Boeing 787 Dreamliner. My data is limited to the information in the aircraft_models table, which includes details such as model name, manufacturer, passenger capacity, and technical specifications. For safety-related information, I recommend consulting official aviation authorities or safety reports.

[User] Count the total number of likes each post has received.

[Assistant]
SELECT post_id, COUNT(*) AS like_count
FROM social_media.likes
WHERE post_id IS NOT NULL
GROUP BY post_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, asset_type character varying(32) NOT NULL, maintenance_type character varying(128) NOT NULL, staff_id character varying(64), start_datetime timestamp NOT NULL, end_datetime timestamp, description text NOT NULL, cost numeric(12, 2), status character varying(32) NOT NULL DEFAULT 'Completed', PRIMARY KEY (record_id), FOREIGN KEY (staff_id) REFERENCES train_station_management.staff(staff_id) ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id.text, asset_id.text, asset_type.text, maintenance_type.text, staff_id.text, start_datetime.timestamp, end_datetime.timestamp, description.text, cost.numeric, status.text ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.staff ( staff_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, role character varying(64) NOT NULL, primary_station_id character varying(64), employee_number character varying(32) UNIQUE NOT NULL, hire_date date NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), is_active boolean NOT NULL DEFAULT true, PRIMARY KEY (staff_id), FOREIGN KEY (primary_station_id) REFERENCES train_station_management.stations(station_id) ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id text, asset_id text, asset_type text, maintenance_type text, staff_id text, start_datetime timestamp, end_datetime timestamp, description text, cost numeric, status text )
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
##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 ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.trains ( train_id text PRIMARY KEY, train_number text UNIQUE, model text, manufacturer text, year_manufactured int, capacity int, status text, last_maintenance_date date, next_maintenance_date date ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id text PRIMARY KEY, asset_id text, asset_type text, maintenance_type text, staff_id text, start_datetime timestamp, end_datetime timestamp, description text, cost numeric, status text )
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.stations ( station_id.text, station_name.text, city.text, state_province.text, country_code.text, address.text, timezone.text, number_of_platforms.integer, created_at.timestamp, last_updated_at.timestamp )
##Table Structure
CREATE TABLE project_fundraising_record ( id text, project_id text, project_name text, rounds_name text, investment_value numeric, investment_date text, introduction text, valuation numeric ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.stations ( station_id text, station_name text, city text, state_province text, country_code text, address text, timezone text, number_of_platforms integer, created_at timestamp, last_updated_at timestamp ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.train_cars ( car_id text PRIMARY KEY, train_id text, car_number text, car_type text, class text, capacity int, features text )

[User] What is the reason behind the cost variation for maintenance of asset_id 'ASSET456' over the past year?

[Assistant] I'm sorry, but I can't provide information on the reasons behind cost variations for maintenance. The data in the maintenance_records table includes only the cost amount and other basic details of each maintenance record, but it does not contain explanations or factors influencing cost changes.

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

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

[User] What is the salary or compensation package for a staff member with the role of Ticket Inspector?

[Assistant] I'm sorry, but I can't provide information about salary or compensation packages as this data is not included in the staff table. For details on salaries, please refer to the HR department or relevant documentation.

[User] What are the personal contact details of the staff member associated with staff_id 'STAFF789' who worked on a specific maintenance record?

[Assistant] I'm sorry, but I can't provide personal contact details of staff members as this information is not stored in the maintenance_records table and is outside the scope of the available data.

[User] Now, sort the results by the date opened, oldest first, and show only the top 10.

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE lead_lawyer_id = 'lawyer_abc' AND status = 'Open' AND case_type = 'Criminal' ORDER BY date_opened ASC LIMIT 10;

[User] Count the total number of comments each user has made.

[Assistant] SELECT user_id, COUNT(*) AS comment_count FROM comments GROUP BY user_id;

[User] What is the ticket price for a journey on train number T4321?

[Assistant] I'm sorry, but I don't have access to information about ticket prices for specific trains. The data I have is limited to train details such as model, manufacturer, capacity, and maintenance schedules. For ticket pricing, please consult the ticketing office or the official website.

[User] What are the specific tools or equipment used during the maintenance with record_id 'REC456'?

[Assistant] I'm sorry, but I can't provide information about the specific tools or equipment used during a maintenance record. The data in the maintenance_records table does not include details about tools or equipment used.

[User] Find appointments that are longer than 30 minutes.

[Assistant] SELECT * FROM legal_services.appointments WHERE end_time IS NOT NULL AND start_time IS NOT NULL AND end_time > start_time + INTERVAL '30 minutes'

[User] What is the total revenue generated by ticket sales at the station with ID 'ST101' for the past month?

[Assistant] I'm sorry, but I can't provide information on the revenue generated by ticket sales as this data is not available in the current database table. The table only contains details about station information such as name, location, and platform count. If you have another question or need assistance with something else related to the station data, I'm happy to help.

[User] How many fundraising rounds did each project complete?

[Assistant] SELECT project_name, COUNT(*) AS round_count FROM project_fundraising_record GROUP BY project_name;

[User] What is the schedule of trains arriving at station with ID 'ST789' tomorrow?

[Assistant] I'm sorry, but I can't provide the train schedule for station ID 'ST789' as this information is not available in the current database. The table only contains details about station attributes such as name, location, and number of platforms. For train schedules, please refer to the relevant train service provider or timetable database.

[User] What is the current operational status of the train car with car_id 'CAR123'?

[Assistant] I'm sorry, but I can't provide information on the current operational status of the train car with car_id 'CAR123'. The data in the train_cars table does not include real-time status updates or operational conditions.


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE healthcare.appointments (
    appointment_id 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)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)
##Table Structure
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id 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) )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )

[User] For each scheduled appointment, list the appointment_id, appointment_time, patient_id, and the name of the patient's primary insurance plan. Only include appointments that have not been cancelled.

[Assistant]
SELECT a.appointment_id,
       a.appointment_time,
       a.patient_id,
       ip.plan_name
FROM healthcare.appointments a
JOIN healthcare.patient_insurance pi
  ON a.patient_id = pi.patient_id
 AND pi.is_primary = TRUE
JOIN healthcare.insurance_plans ip
  ON pi.plan_id = ip.plan_id
WHERE a.status != 'Cancelled';

[User] I want to know the total number of appointments per location along with the location name for appointments scheduled in March 2024.

[Assistant]
SELECT
  sl.location_name,
  COUNT(a.appointment_id) AS appointment_count
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE a.scheduled_start_time >= '2024-03-01'
  AND a.scheduled_start_time < '2024-04-01'
GROUP BY sl.location_name;

[User] Actually, only include appointments with status 'Completed' and locations that are accessible.

[Assistant]
SELECT
  sl.location_name,
  COUNT(a.appointment_id) AS completed_appointment_count
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE a.scheduled_start_time >= '2024-03-01'
  AND a.scheduled_start_time < '2024-04-01'
  AND a.status = 'Completed'
  AND sl.is_accessible = TRUE
GROUP BY sl.location_name;

[User] List each user's username, email, and the total count of log entries they have recorded.

[Assistant] SELECT T1.username, T1.email, count(T2.log_id) FROM users AS T1 LEFT JOIN logs AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username, T1.email

[User] Also include the date of their most recent log entry.

[Assistant] SELECT T1.username, T1.email, count(T2.log_id), max(T2.logged_at) FROM users AS T1 LEFT JOIN logs AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username, T1.email

[User] Can you show me the company name, email, and phone of all clients who share the same status?

[Assistant]
SELECT a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id;

[User] What if I only want to see those clients who registered before January 1st, 2023?

[Assistant]
SELECT a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id
WHERE a.date_registered < '2023-01-01';

[User] Please add each client's first and last name, and sort the results by company_name.

[Assistant]
SELECT a.first_name, a.last_name, a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id
WHERE a.date_registered < '2023-01-01'
ORDER BY a.company_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id text, first_name text, last_name text, bar_number text, firm_id text, email text, phone text, specialization text, hire_date timestamp, is_partner boolean )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )
##Table Structure
CREATE TABLE 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 government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
##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 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)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
##Table Structure
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] List all appointments along with their subject and start time for lawyers specializing in 'Criminal Law'.

[Assistant] SELECT T1.subject, T1.start_time FROM legal_services.appointments AS T1 JOIN legal_services.lawyers AS T2 ON T1.lawyer_id = T2.lawyer_id WHERE T2.specialization = 'Criminal Law';

[User] Show the latest version number of each document_name for every case.

[Assistant]
SELECT case_id,
       document_name,
       MAX(version) AS latest_version
FROM legal_services.documents
GROUP BY case_id, document_name;

[User] Actually, I also need the upload_timestamp of that latest version.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id,
         document_name,
         MAX(version) AS latest_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) sub
  ON d.case_id = sub.case_id
 AND d.document_name = sub.document_name
 AND d.version = sub.latest_version;

[User] Also include the uploaded_by_lawyer_id for each latest version.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version AS latest_version,
       d.upload_timestamp,
       d.uploaded_by_lawyer_id
FROM legal_services.documents d
JOIN (
  SELECT case_id,
         document_name,
         MAX(version) AS latest_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) sub
  ON d.case_id = sub.case_id
 AND d.document_name = sub.document_name
 AND d.version = sub.latest_version;

[User] Find employees who work in the same department as their manager. Display the employee's full name, the manager's full name, and the department they share.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_full_name, m.first_name || ' ' || m.last_name AS manager_full_name, e.department FROM government_services.employees AS e JOIN government_services.employees AS m ON e.manager_employee_id = m.employee_id WHERE e.department = m.department;

[User] List the username, registration date, and the creation date of the first wallet created by each user who owns at least one wallet.

[Assistant] SELECT u.username, u.created_at AS registration_date, MIN(w.created_at) AS first_wallet_creation_date FROM web3.users AS u JOIN web3.wallets AS w ON u.user_id = w.user_id GROUP BY u.user_id, u.username, u.created_at;

[User] For each passenger, list their email along with the total amount spent on fares across all their bookings.

[Assistant]
SELECT p.passenger_id, p.email, SUM(b.fare) AS total_fare_spent
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.email;

[User] What are the average and maximum fare amounts for each booking status?

[Assistant]
SELECT status, AVG(fare) AS avg_fare, MAX(fare) AS max_fare
FROM transportation.bookings
GROUP BY status;

[User] Only include statuses where the average fare is greater than 50.

[Assistant]
SELECT status, AVG(fare) AS avg_fare, MAX(fare) AS max_fare
FROM transportation.bookings
GROUP BY status
HAVING AVG(fare) > 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 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.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
##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 web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id.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 legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
##Table Structure
CREATE TABLE financial_services.securities ( security_id character varying(64) NOT NULL, ticker_symbol character varying(20) NOT NULL UNIQUE, isin_code character varying(12) UNIQUE, cusip_code character varying(9) UNIQUE, security_name text NOT NULL, security_type character varying(50) NOT NULL, exchange character varying(50), currency character varying(3) NOT NULL, issuer_name character varying(255), sector character varying(100), last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (security_id) )
##Table Structure
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )
##Table Structure
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] List all pairs of transactions where the recipient of the first transaction became the sender in the second, showing the first transaction_id, the second transaction_id, the shared address, and the timestamps of both transactions.

[Assistant] SELECT t1.transaction_id AS first_transaction_id, t2.transaction_id AS second_transaction_id, t1.to_address AS shared_address, t1.timestamp AS first_transaction_timestamp, t2.timestamp AS second_transaction_timestamp FROM web3.transactions AS t1 JOIN web3.transactions AS t2 ON t1.to_address = t2.from_address WHERE t1.transaction_id <> t2.transaction_id AND t2.timestamp > t1.timestamp;

[User] List all appointments with a non-empty notes field. Return appointment_id, appointment_time, and doctor_id.

[Assistant]
SELECT appointment_id, appointment_time, doctor_id
FROM healthcare.appointments
WHERE notes IS NOT NULL AND notes <> '';

[User] Could you further filter to only appointments where status is 'No-show'?

[Assistant]
SELECT appointment_id, appointment_time, doctor_id
FROM healthcare.appointments
WHERE notes IS NOT NULL AND notes <> ''
  AND status = 'No-show';

[User] List the username, registration date, and address of all users who have created a wallet.

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

[User] Can you also include how many wallets each user has created in the result?

[Assistant]
SELECT u.username, u.created_at AS registration_date, COUNT(w.wallet_id) AS wallet_count
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
GROUP BY u.user_id, u.username, u.created_at
ORDER BY u.username;

[User] Find all pairs of lawyers from the same firm who have the same specialization.

[Assistant] SELECT a.lawyer_id AS lawyer_id_1, a.first_name AS first_name_1, a.last_name AS last_name_1, b.lawyer_id AS lawyer_id_2, b.first_name AS first_name_2, b.last_name AS last_name_2, a.specialization FROM legal_services.lawyers a JOIN legal_services.lawyers b ON a.firm_id = b.firm_id AND a.specialization = b.specialization AND a.lawyer_id < b.lawyer_id;

[User] List all securities (security_id, ticker_symbol, issuer_name) where the currency is 'EUR' and the security_type is 'Equity', along with their exchange information.

[Assistant] SELECT security_id, ticker_symbol, issuer_name, exchange FROM financial_services.securities WHERE currency = 'EUR' AND security_type = 'Equity';

[User] How many distinct IP addresses have ever connected as peers on the platform?

[Assistant]
SELECT COUNT(DISTINCT ip_address) AS distinct_ip_count
FROM trading_platform.peers;

[User] Find all pairs of bookings that share the same payment_transaction_id.

[Assistant]
SELECT b1.booking_id AS booking_id_1, b2.booking_id AS booking_id_2, b1.payment_transaction_id
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.payment_transaction_id = b2.payment_transaction_id
 AND b1.booking_id < b2.booking_id;

[User] Now limit the results to pairs where both bookings have status 'Completed'.

[Assistant]
SELECT b1.booking_id AS booking_id_1, b2.booking_id AS booking_id_2, b1.payment_transaction_id
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.payment_transaction_id = b2.payment_transaction_id
 AND b1.booking_id < b2.booking_id
WHERE b1.status = 'Completed'
  AND b2.status = 'Completed';