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 )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##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 government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
##Table Structure
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
##Table Structure
CREATE TABLE insurance.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
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 )
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 web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
##Table Structure
CREATE TABLE transportation.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 )
##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 transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] List all pairs of routes where the origin location of one route is the destination location of the other, showing both route numbers and their types.

[Assistant]
SELECT r1.route_number AS route_number_1, r1.type AS type_1,
       r2.route_number AS route_number_2, r2.type AS type_2
FROM transportation.routes r1
JOIN transportation.routes r2
  ON r1.origin_location_id = r2.destination_location_id
 AND r1.route_id <> r2.route_id;

[User] Find pairs of wallet IDs that belong to the same user, showing the user ID and the two wallet IDs.

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

[User] List all document IDs, file names, and uploaded timestamps for documents that were uploaded on a weekend.

[Assistant] SELECT document_id, file_name, uploaded_at FROM insurance.claim_documents WHERE EXTRACT(DOW FROM uploaded_at) IN (0, 6);

[User] List all services whose eligibility criteria mention 'citizen'.

[Assistant] SELECT service_id, service_name, eligibility_criteria FROM government_services.services WHERE eligibility_criteria ILIKE '%citizen%';

[User] Show me all failed payments along with the application ID, citizen ID, and payment timestamp.

[Assistant]
SELECT payment_id, application_id, citizen_id, payment_timestamp
FROM government_services.payments
WHERE status = 'Failed';

[User] Calculate the average star rating for each property type.

[Assistant] SELECT property_type, AVG(star_rating) AS average_star_rating FROM hospitality_technology.properties GROUP BY property_type;

[User] Find pairs of products that share the same product_type but have different is_active statuses. Return the product_type, active product_id, active product_name, inactive product_id, and inactive product_name.

[Assistant]
SELECT a.product_type,
       a.product_id   AS active_product_id,
       a.product_name AS active_product_name,
       i.product_id   AS inactive_product_id,
       i.product_name AS inactive_product_name
FROM insurance.insurance_products a
JOIN insurance.insurance_products i
  ON a.product_type = i.product_type
WHERE a.is_active = TRUE
  AND i.is_active = FALSE;

[User] Count the number of policies issued in each calendar year, and show the year and the count.

[Assistant] SELECT EXTRACT(YEAR FROM issued_at), COUNT(*) FROM insurance.policies WHERE issued_at IS NOT NULL GROUP BY 1 ORDER BY 1;

[User] Show all token symbols along with the names of any other tokens on the same contract address.

[Assistant]
SELECT t1.token_symbol, t2.token_name AS other_token_name, t1.contract_address
FROM web3.tokens t1
JOIN web3.tokens t2
  ON t1.contract_address = t2.contract_address
  AND t1.token_id <> t2.token_id;

[User] Provide a count of locations for each country listed in the table.

[Assistant] SELECT country, COUNT(*) FROM transportation.locations GROUP BY country

[User] List each child agency ID and name along with its parent agency ID and name.

[Assistant]
SELECT c.agency_id AS child_id,
       c.agency_name AS child_name,
       p.agency_id AS parent_id,
       p.agency_name AS parent_name
FROM government_services.agencies AS c
JOIN government_services.agencies AS p
  ON c.parent_agency_id = p.agency_id;

[User] List all pairs of vehicles in the same depot with different status. Include both vehicle IDs with their statuses and the depot_id.

[Assistant]
SELECT v1.vehicle_id   AS vehicle1_id,
       v1.status       AS status1,
       v2.vehicle_id   AS vehicle2_id,
       v2.status       AS status2,
       v1.depot_id
FROM transportation.vehicles v1
JOIN transportation.vehicles v2
  ON v1.depot_id = v2.depot_id
 AND v1.vehicle_id < v2.vehicle_id
 AND v1.status <> v2.status;

[User] Give me the website for the insurance plan named 'Family Advantage'.

[Assistant] SELECT website FROM healthcare.insurance_plans WHERE plan_name = 'Family Advantage';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
##Table Structure
CREATE TABLE social_media.users ( user_id.text, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.messages ( message_id.text, conversation_id.text, sender_user_id.text, content.text, media_url.text, media_type.text, sent_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.transactions ( transaction_id 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 hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )

[User] List each participant_id along with the total number of participants in their conversation, and include user_id and conversation_id.

[Assistant]
SELECT cp.participant_id, cp.user_id, cp.conversation_id, counts.participant_count
FROM social_media.conversation_participants cp
JOIN (
  SELECT conversation_id, COUNT(*) AS participant_count
  FROM social_media.conversation_participants
  GROUP BY conversation_id
) counts ON cp.conversation_id = counts.conversation_id;

[User] Actually, only include conversations where the participant_count is greater than 2.

[Assistant]
SELECT cp.participant_id, cp.user_id, cp.conversation_id, counts.participant_count
FROM social_media.conversation_participants cp
JOIN (
  SELECT conversation_id, COUNT(*) AS participant_count
  FROM social_media.conversation_participants
  GROUP BY conversation_id
  HAVING COUNT(*) > 2
) counts ON cp.conversation_id = counts.conversation_id;

[User] Which hashtags appear on the most posts? Return hashtag_id, tag_name, and the number of posts each hashtag is used in, sorted descending, limited to the top 3.

[Assistant]
SELECT
  h.hashtag_id,
  h.tag_name,
  COUNT(ph.post_id) AS post_count
FROM social_media.hashtags h
JOIN social_media.post_hashtags ph
  ON h.hashtag_id = ph.hashtag_id
GROUP BY h.hashtag_id, h.tag_name
ORDER BY post_count DESC
LIMIT 3;

[User] Get the total value and average gas_price for each from_address in transactions, but only include senders who have sent more than 5 transactions.

[Assistant]
SELECT from_address,
       SUM(value) AS total_value,
       AVG(gas_price) AS avg_gas_price,
       COUNT(*) AS tx_count
FROM web3.transactions
GROUP BY from_address
HAVING COUNT(*) > 5;

[User] Actually, I also want to include the number of distinct to_address recipients for each sender.

[Assistant]
SELECT from_address,
       SUM(value) AS total_value,
       AVG(gas_price) AS avg_gas_price,
       COUNT(*) AS tx_count,
       COUNT(DISTINCT to_address) AS distinct_recipients
FROM web3.transactions
GROUP BY from_address
HAVING COUNT(*) > 5;

[User] List all rooms, showing their room number, type name, and the name of the property they are in.

[Assistant] SELECT T1.room_number, T2.type_name, T3.property_name FROM hospitality_technology.rooms AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.room_type_id = T2.room_type_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id;

[User] List pairs of law firms that are located at the same address. Display the names of both firms and the shared address, ensuring the address is not null.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.address
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.address = t2.address
WHERE
  t1.firm_id < t2.firm_id AND t1.address IS NOT NULL;

[User] Only show pairs where both firms were founded before 2020.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.address
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.address = t2.address
WHERE
  t1.firm_id < t2.firm_id AND t1.address IS NOT NULL AND EXTRACT(YEAR FROM t1.founded_date) < 2020 AND EXTRACT(YEAR FROM t2.founded_date) < 2020;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE healthcare.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.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.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.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) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, 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 )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id 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, first_name.text, last_name.text, company_name.text, email.text, phone.text, address.text, date_registered.timestamp, status.text )
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.time_entries ( entry_id.text, case_id.text, lawyer_id.text, date_worked.date, hours_spent.numeric, billing_rate.numeric, description.text, is_billable.boolean, is_billed.boolean, invoice_id.text, created_at.timestamp )
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )

[User] List all patients who have received a prescription with the route 'Topical', showing their ID, first name, and last name.

[Assistant]
SELECT DISTINCT
    p.patient_id,
    p.first_name,
    p.last_name
FROM
    healthcare.patients p
JOIN
    healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE
    pr.route = 'Topical';

[User] Only show patients who have received at least 2 such prescriptions.

[Assistant]
SELECT
    p.patient_id,
    p.first_name,
    p.last_name,
    COUNT(pr.prescription_id) AS topical_prescription_count
FROM
    healthcare.patients p
JOIN
    healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE
    pr.route = 'Topical'
GROUP BY
    p.patient_id, p.first_name, p.last_name
HAVING
    COUNT(pr.prescription_id) >= 2;

[User] List all hashtags that have never been associated with any post, showing hashtag_id and tag_name.

[Assistant]
SELECT h.hashtag_id, h.tag_name
FROM social_media.hashtags h
LEFT JOIN social_media.post_hashtags ph ON h.hashtag_id = ph.hashtag_id
WHERE ph.post_hashtag_id IS NULL;

[User] List all unique actions that have been logged in the system.

[Assistant] SELECT DISTINCT action FROM trading_platform.logs;

[User] Show the invoice number, issue date, total amount, and the client's full name for all invoices, including only those invoices that have not been paid fully.

[Assistant] SELECT i.invoice_number, i.issue_date, i.total_amount, c.first_name || ' ' || c.last_name AS client_full_name FROM legal_services.invoices i JOIN legal_services.clients c ON i.client_id = c.client_id WHERE i.amount_paid < i.total_amount;

[User] List all lawyers who were hired before the year 2020 and are partners. Show their full name (first and last name combined), bar number, and hire date. Order the results by hire date.

[Assistant] SELECT first_name || ' ' || last_name AS full_name, bar_number, hire_date FROM legal_services.lawyers WHERE hire_date < '2020-01-01' AND is_partner = TRUE ORDER BY hire_date;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )
##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.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
##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 web3.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
##Table Structure
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )

[User] Show the transaction ID, the transaction value from the transactions table, and the sum of the value from token_transfers for all transactions that have at least one associated token transfer. Name the sum column total_token_transfer_value.

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

[User] List all chronic diagnoses made by Cardiology specialists in the last year, including the patient ID, diagnosis description, and doctor's full name.

[Assistant] SELECT dg.patient_id, dg.description, d.first_name || ' ' || d.last_name AS doctor_name FROM healthcare.diagnoses dg JOIN healthcare.doctors d ON dg.doctor_id = d.doctor_id WHERE d.specialty = 'Cardiology' AND dg.is_chronic = TRUE AND dg.diagnosis_date >= CURRENT_DATE - INTERVAL '1 year';

[User] List all pairs of insurance products that share the same product_type but have differing active statuses. Return both product_ids, the product_type, and each is_active flag.

[Assistant]
SELECT p1.product_id AS product_id_1, p2.product_id AS product_id_2, p1.product_type, p1.is_active AS is_active_1, p2.is_active AS is_active_2
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p1.is_active <> p2.is_active
WHERE p1.product_id < p2.product_id;

[User] List the total value and count of transactions for each status, ordered by total value descending.

[Assistant]
SELECT status, COUNT(*) AS transaction_count, SUM(value) AS total_value
FROM web3.transactions
GROUP BY status
ORDER BY total_value DESC;

[User] Actually, can you also include the average value per transaction for each status?

[Assistant]
SELECT status, COUNT(*) AS transaction_count, SUM(value) AS total_value, AVG(value) AS avg_value
FROM web3.transactions
GROUP BY status
ORDER BY total_value DESC;

[User] List all pairs of wallet IDs where both wallets were created on the same day but belong to different users, showing the user IDs and the creation date.

[Assistant] SELECT w1.wallet_id AS wallet_id_1, w2.wallet_id AS wallet_id_2, w1.user_id AS user_id_1, w2.user_id AS user_id_2, DATE(w1.created_at) AS creation_date FROM web3.wallets w1 JOIN web3.wallets w2 ON DATE(w1.created_at) = DATE(w2.created_at) AND w1.user_id <> w2.user_id AND w1.wallet_id < w2.wallet_id;

[User] Find pairs of distinct locations in the same city that have different types. Include location IDs, names, city, and type for both locations.

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

[User] List tokens with trend rank 5 or better and a price below $1. Show symbol, price, and trend rank.

[Assistant] SELECT token_symbol, price, trend_rank FROM token_dexpool_info WHERE trend_rank IS NOT NULL AND trend_rank <= 5 AND price < 1;

[User] For each wallet, find the previous wallet created by the same user. Show current wallet_id, previous_wallet_id, user_id, and the difference in days between their creation dates.

[Assistant]
SELECT
  wallet_id AS current_wallet_id,
  LAG(wallet_id) OVER (PARTITION BY user_id ORDER BY created_at) AS previous_wallet_id,
  user_id,
  EXTRACT(EPOCH FROM (
    created_at - LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at)
  )) / 86400 AS diff_days
FROM web3.wallets;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text, user_id text, action text, details text, logged_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
##Table Structure
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
##Table Structure
CREATE TABLE legal_services.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 )
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 blockchain.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction
    sender_address character varying(128) NOT NULL, -- address of the sender
    receiver_address character varying(128) NOT NULL, -- address of the receiver
    amount numeric(38,14) NOT NULL, -- amount transferred
    timestamp timestamp NOT NULL, -- time when the transaction was created
    signature text NOT NULL, -- digital signature of the transaction
    PRIMARY KEY (transaction_id)
)

[User] List peer IDs and IP addresses for all peers whose IP address starts with '10.'.

[Assistant] SELECT peer_id, ip_address FROM trading_platform.peers WHERE ip_address LIKE '10.%';

[User] List the first and last names of guests residing in California who are loyalty members.

[Assistant] SELECT first_name, last_name FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL;

[User] Now, only include those who have communication consent enabled and sort by last name.

[Assistant] SELECT first_name, last_name FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL AND communication_consent = TRUE ORDER BY last_name;

[User] Show me the count of trips by status for each vehicle, but only include vehicles that have had more than 5 trips total.

[Assistant] SELECT vehicle_id, status, COUNT(*) as trip_count FROM transportation.trips GROUP BY vehicle_id, status HAVING COUNT(*) > 5;

[User] Now filter this to only show vehicles that have had at least 2 cancelled trips.

[Assistant] SELECT vehicle_id, COUNT(*) as cancelled_trips FROM transportation.trips WHERE status = 'Cancelled' GROUP BY vehicle_id HAVING COUNT(*) >= 2;

[User] Combine both queries to show me vehicles with more than 5 total trips and at least 2 cancelled trips, along with their complete status distribution.

[Assistant] SELECT t.vehicle_id, t.status, COUNT(*) as trip_count FROM transportation.trips t JOIN (SELECT vehicle_id FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 5 INTERSECT SELECT vehicle_id FROM transportation.trips WHERE status = 'Cancelled' GROUP BY vehicle_id HAVING COUNT(*) >= 2) v ON t.vehicle_id = v.vehicle_id GROUP BY t.vehicle_id, t.status;

[User] Show me a list of all clients and their invoices, including the client's full name, email, invoice number, total amount, and invoice status.

[Assistant]
SELECT c.first_name, c.last_name, c.email, i.invoice_number, i.total_amount, i.status
FROM legal_services.clients c
LEFT JOIN legal_services.invoices i ON c.client_id = i.client_id;

[User] Can you update the query to include only those invoices with a total amount greater than 2,000?

[Assistant]
SELECT c.first_name, c.last_name, c.email, i.invoice_number, i.total_amount, i.status
FROM legal_services.clients c
LEFT JOIN legal_services.invoices i ON c.client_id = i.client_id
WHERE i.total_amount > 2000;

[User] Actually, I want to see only clients who have at least two such invoices. Can you modify the query to reflect that?

[Assistant]
SELECT c.first_name, c.last_name, c.email, i.invoice_number, i.total_amount, i.status
FROM legal_services.clients c
JOIN (
    SELECT client_id
    FROM legal_services.invoices
    WHERE total_amount > 2000
    GROUP BY client_id
    HAVING COUNT(*) >= 2
) filtered_clients ON c.client_id = filtered_clients.client_id
JOIN legal_services.invoices i ON c.client_id = i.client_id AND i.total_amount > 2000;

[User] Find all pairs of transactions where the sender address and the receiver address are the same, but the transactions occurred on different days. Show transaction IDs, addresses, and their timestamps.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.sender_address, t1.timestamp AS tx1_time, t2.timestamp AS tx2_time
FROM blockchain.transactions t1
JOIN blockchain.transactions t2
  ON t1.sender_address = t2.sender_address
 AND t1.receiver_address = t2.receiver_address
 AND t1.transaction_id <> t2.transaction_id
 AND DATE(t1.timestamp) <> DATE(t2.timestamp)
WHERE t1.sender_address = t1.receiver_address;

[User] Exclude pairs where the two transactions happened more than 7 days apart.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.sender_address, t1.timestamp AS tx1_time, t2.timestamp AS tx2_time
FROM blockchain.transactions t1
JOIN blockchain.transactions t2
  ON t1.sender_address = t2.sender_address
 AND t1.receiver_address = t2.receiver_address
 AND t1.transaction_id <> t2.transaction_id
 AND DATE(t1.timestamp) <> DATE(t2.timestamp)
WHERE t1.sender_address = t1.receiver_address
  AND ABS(DATE_PART('day', t1.timestamp - t2.timestamp)) <= 7;


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.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)
)
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.trips ( trip_id 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 token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )

[User] List the record ID, record date, patient ID, and chief complaint for medical records belonging to patients whose last name is 'Smith'. Also include the patient's last name in the results.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith';

[User] Refine this list to only show records where the record date is in 2024 and the chief complaint is not null. Sort by record_date in ascending order.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith' AND EXTRACT(YEAR FROM mr.record_date) = 2024 AND (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') ORDER BY mr.record_date ASC;

[User] Show me a list of all users who have participated in any trade (either as a buyer or a seller), including their username and the total number of trades they were involved in.

[Assistant] SELECT T1.username , count(T2.trade_id) FROM trading_platform.users AS T1 JOIN (SELECT buyer_id, trade_id FROM trading_platform.trades UNION ALL SELECT seller_id, trade_id FROM trading_platform.trades) AS T2 ON T1.user_id  =  T2.buyer_id GROUP BY T1.username

[User] From that list, now only show users who were involved in at least one trade *as a buyer*, and include their email address as well.

[Assistant] SELECT T1.username , T1.email , count(T2.trade_id) FROM trading_platform.users AS T1 JOIN trading_platform.trades AS T2 ON T1.user_id  =  T2.buyer_id GROUP BY T1.username , T1.email HAVING count(T2.trade_id)  >=  1

[User] For each driver, show the driver's full name and the total number of trips they have driven. Only include drivers whose status is 'Active' and sort the result by trip count in descending order.

[Assistant]
SELECT d.driver_id,
       d.first_name || ' ' || d.last_name AS driver_name,
       COUNT(t.trip_id) AS trip_count
FROM transportation.drivers d
LEFT JOIN transportation.trips t ON d.driver_id = t.driver_id
WHERE d.status = 'Active'
GROUP BY d.driver_id, d.first_name, d.last_name
ORDER BY trip_count DESC;

[User] What is the average market cap for all tokens belonging to the 'GameFi' narrative?

[Assistant] SELECT AVG(market_cap) FROM token_basic_info WHERE narrative = 'GameFi'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.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.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE government_services.agencies (
    agency_id character varying(64) NOT NULL, -- unique identifier for the agency
    agency_name character varying(255) NOT NULL, -- full name of the government agency
    jurisdiction_level character varying(50) NOT NULL, -- e.g., Federal, State, County, City
    primary_contact_email character varying(128),
    main_phone_number character varying(32),
    website_url character varying(255),
    established_date date,
    parent_agency_id character varying(64), -- FK to self for hierarchical structure
    PRIMARY KEY (agency_id)
)
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE web3.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
##Table Structure
CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.trades ( trade_id.text, order_id.text, buyer_id.text, seller_id.text, asset_id.text, quantity.numeric, price.numeric, traded_at.timestamp )
CREATE TABLE trading_platform.assets ( asset_id.text, name.text, symbol.text, type.text )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id.text, asset_id.text, key.text, value.text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
##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 gaming_technology.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )

[User] For each contract that has received transactions, list its address and the total value of Ether received.

[Assistant] SELECT T1.address, SUM(T2.value) FROM web3.contracts AS T1 JOIN web3.transactions AS T2 ON T1.address = T2.to_address GROUP BY T1.address;

[User] Show me a list of all agencies and the number of distinct citizens who have submitted documents to each agency.

[Assistant]
SELECT a.agency_name, COUNT(DISTINCT d.citizen_id) AS citizen_count
FROM government_services.documents d
JOIN government_services.applications app ON d.application_id = app.application_id
JOIN government_services.services s ON app.service_id = s.service_id
JOIN government_services.agencies a ON s.agency_id = a.agency_id
GROUP BY a.agency_name;

[User] How many users registered in each month?

[Assistant]
SELECT date_trunc('month', created_at) AS month,
       COUNT(*) AS registrations
FROM web3.users
GROUP BY month
ORDER BY month;

[User] Actually, show only those months where registrations exceed 10.

[Assistant]
SELECT date_trunc('month', created_at) AS month,
       COUNT(*) AS registrations
FROM web3.users
GROUP BY month
HAVING COUNT(*) > 10
ORDER BY month;

[User] For each employee who has verified more than one document, list their employee ID, the first document they verified, and the next document they verified, along with both verification timestamps.

[Assistant]
SELECT
  d1.verified_by_employee_id AS employee_id,
  d1.document_id AS first_verified_document,
  d1.verification_timestamp AS first_verification_time,
  d2.document_id AS next_verified_document,
  d2.verification_timestamp AS next_verification_time
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.verified_by_employee_id = d2.verified_by_employee_id
  AND d2.verification_timestamp > d1.verification_timestamp
WHERE d1.verification_status = 'Verified'
  AND d2.verification_status = 'Verified';

[User] Find the address that has the highest total amount across all its UTXOs.

[Assistant] SELECT address FROM utxos GROUP BY address ORDER BY SUM(amount) DESC LIMIT 1;

[User] For each driver, find the other driver whose license_expiry_date is the next one after theirs. Show both IDs, names and their expiry dates.

[Assistant]
SELECT
  d1.driver_id            AS driver_id,
  d1.first_name || ' ' || d1.last_name     AS driver_name,
  d1.license_expiry_date  AS expiry_date,
  d2.driver_id            AS next_driver_id,
  d2.first_name || ' ' || d2.last_name     AS next_driver_name,
  d2.license_expiry_date  AS next_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date = (
    SELECT MIN(d3.license_expiry_date)
    FROM transportation.drivers d3
    WHERE d3.license_expiry_date > d1.license_expiry_date
  );

[User] How can I calculate how many years each developer has been in business based on their founded_year?

[Assistant]
SELECT name,
       EXTRACT(year FROM age(CURRENT_DATE, make_date(founded_year, 1, 1))) AS years_in_business
FROM gaming_technology.developers;

[User] Actually, I'd like to include only developers founded before 2000 and order the result by years_in_business descending.

[Assistant]
SELECT name,
       EXTRACT(year FROM age(CURRENT_DATE, make_date(founded_year, 1, 1))) AS years_in_business
FROM gaming_technology.developers
WHERE founded_year < 2000
ORDER BY years_in_business DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id.text, property_name.text, address_line1.text, address_line2.text, city.text, state_province.text, postal_code.text, country_code.text, phone_number.text, email_address.text, property_type.text, star_rating.numeric, timezone.text, manager_staff_id.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )
##Table Structure
CREATE TABLE web3.contracts (
    contract_id character varying(64) NOT NULL,  -- unique identifier for the contract
    address character varying(128) NOT NULL, -- address of the deployed contract
    abi text NOT NULL, -- application binary interface of the contract
    bytecode text NOT NULL, -- bytecode of the contract
    deployer_address character varying(128) NOT NULL, -- address of the deployer
    deployed_at timestamp NOT NULL, -- time when the contract was deployed
    network_id character varying(64) NOT NULL, -- identifier of the network where the contract is deployed
    status character varying(32) NOT NULL, -- status of the contract (e.g., active, deprecated)
    PRIMARY KEY (contract_id)
)
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.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.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)
)

[User] Which users have commented on posts created by the users they follow? Please show the commenter user_ids and the followed user_ids.

[Assistant] SELECT DISTINCT c.user_id AS commenter_user_id, f.following_user_id AS followed_user_id FROM social_media.comments c JOIN social_media.follows f ON c.user_id = f.follower_user_id AND c.post_id IN (SELECT post_id FROM social_media.comments WHERE user_id = f.following_user_id);

[User] Can you also include the post_id in the results?

[Assistant] SELECT DISTINCT c.user_id AS commenter_user_id, f.following_user_id AS followed_user_id, c.post_id FROM social_media.comments c JOIN social_media.follows f ON c.user_id = f.follower_user_id AND c.post_id IN (SELECT post_id FROM social_media.comments WHERE user_id = f.following_user_id);

[User] Show the first name, last name, and email for guests residing in California.

[Assistant] SELECT first_name, last_name, email FROM hospitality_technology.guests WHERE state_province = 'CA'

[User] Only show those who have a phone number.

[Assistant] SELECT first_name, last_name, email, phone_number FROM hospitality_technology.guests WHERE state_province = 'CA' AND phone_number IS NOT NULL

[User] Show each contract's address along with the total number of events it has emitted and the total number of transactions sent to it.

[Assistant]
SELECT
  c.address,
  COUNT(e.event_id) AS event_count,
  COUNT(t.transaction_id) AS tx_count
FROM web3.contracts c
LEFT JOIN web3.events e
  ON c.contract_id = e.contract_id
LEFT JOIN web3.transactions t
  ON c.address = t.to_address
GROUP BY c.address;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
##Table Structure
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )
##Table Structure
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
##Table Structure
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
##Table Structure
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )
##Table Structure
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
##Table Structure
CREATE TABLE blockchain.nodes ( node_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
##Table Structure
CREATE TABLE web3.contracts ( contract_id text, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )
CREATE TABLE web3.events ( event_id text, contract_id text, event_name text, data text, emitted_at timestamp, transaction_id text, log_index integer )
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
CREATE TABLE web3.tokens ( token_id text, contract_address text, token_name text, token_symbol text, decimals integer, total_supply numeric )
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
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) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] For each patient, count the total number of medical records they have in the system, and show patient_id along with record_count.

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

[User] For each overall rating level (1-5), count how many reviews received that rating.

[Assistant] SELECT rating_overall, COUNT(*) FROM reviews GROUP BY rating_overall ORDER BY rating_overall;

[User] Only show ratings with more than 100 reviews and sort by the count descending.

[Assistant] SELECT rating_overall, COUNT(*) FROM reviews GROUP BY rating_overall HAVING COUNT(*) > 100 ORDER BY COUNT(*) DESC;

[User] List the full names of employees whose direct manager themselves report to another manager. Also show the direct manager's full name.

[Assistant] SELECT E.first_name, E.last_name, M.first_name AS manager_first_name, M.last_name AS manager_last_name FROM government_services.employees AS E JOIN government_services.employees AS M ON E.manager_employee_id = M.employee_id WHERE M.manager_employee_id IS NOT NULL;

[User] Show me all users who had their KYC rejected along with when their review was completed.

[Assistant] SELECT user_id, reviewed_at FROM trading_platform.kyc_audit WHERE status = 'rejected';

[User] List public reviews whose comment contains the word 'slow'.

[Assistant] SELECT review_id, comment, review_date, rating_overall, property_id FROM hospitality_technology.reviews WHERE is_public = TRUE AND LOWER(comment) LIKE '%slow%';

[User] Also, only include reviews submitted for property 'P007'.

[Assistant] SELECT review_id, comment, review_date, rating_overall, property_id FROM hospitality_technology.reviews WHERE is_public = TRUE AND LOWER(comment) LIKE '%slow%' AND property_id = 'P007';

[User] Show me the distribution of UTXO amounts by creating buckets (0-10, 10-50, 50-100, 100-500, 500+), along with the count and total amount in each bucket.

[Assistant] SELECT CASE WHEN amount <= 10 THEN '0-10' WHEN amount <= 50 THEN '10-50' WHEN amount <= 100 THEN '50-100' WHEN amount <= 500 THEN '100-500' ELSE '500+' END AS amount_range, COUNT(*) AS utxo_count, SUM(amount) AS total_amount FROM trading_platform.utxos GROUP BY amount_range ORDER BY MIN(amount);

[User] Show me pairs of node_id and node_id for nodes that share the same ip_address but have different port numbers.

[Assistant] SELECT n1.node_id AS node_id1, n2.node_id AS node_id2, n1.ip_address, n1.port AS port1, n2.port AS port2 FROM blockchain.nodes n1 JOIN blockchain.nodes n2 ON n1.ip_address = n2.ip_address WHERE n1.node_id < n2.node_id AND n1.port <> n2.port;

[User] What is the average profit and average ROI for smart money addresses ranked in the top 500?

[Assistant] SELECT AVG(profit), AVG(roi) FROM smart_money_profit WHERE rank <= 500

[User] For each contract, can you list the token symbols and total supply of all tokens created by that contract, along with the contract's current status?

[Assistant]
SELECT c.contract_id, c.address AS contract_address, c.status, t.token_symbol, t.total_supply
FROM web3.contracts c
JOIN web3.tokens t ON c.address = t.contract_address
ORDER BY c.contract_id, t.token_symbol;

[User] How many followers does each user have? Show user_id and follower_count.

[Assistant]
SELECT following_user_id AS user_id, COUNT(*) AS follower_count
FROM social_media.follows
GROUP BY following_user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
##Table Structure
CREATE TABLE blockchain.blocks (
    block_id character varying(64) NOT NULL,  -- unique identifier for the block
    previous_block_id character varying(64), -- identifier of the previous block
    timestamp timestamp NOT NULL, -- time when the block was mined
    nonce integer NOT NULL, -- nonce value used in the proof of work
    merkle_root character varying(128) NOT NULL, -- root of the Merkle tree for transactions
    difficulty integer NOT NULL, -- difficulty level of the block
    PRIMARY KEY (block_id)
)
##Table Structure
CREATE TABLE 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.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)
)
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    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, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
##Table Structure
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )

[User] Can you list all appointments along with the scheduled start time, purpose, and booking method, as well as the employee ID and location ID for each appointment?

[Assistant] SELECT appointment_id, scheduled_start_time, purpose, booking_method, employee_id, location_id FROM government_services.appointments;

[User] Now, only include appointments that are scheduled for a future date and have the status 'Scheduled'.

[Assistant] SELECT appointment_id, scheduled_start_time, purpose, booking_method, employee_id, location_id FROM government_services.appointments WHERE scheduled_start_time > CURRENT_TIMESTAMP AND status = 'Scheduled';

[User] Show me the average difficulty for blocks that have a previous block versus those that don't have a previous block.

[Assistant] SELECT CASE WHEN previous_block_id IS NULL THEN 'No Previous Block' ELSE 'Has Previous Block' END AS block_type, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks GROUP BY block_type;

[User] Now break this down further by year, showing the yearly averages for each block type.

[Assistant] SELECT EXTRACT(YEAR FROM timestamp) AS year, CASE WHEN previous_block_id IS NULL THEN 'No Previous Block' ELSE 'Has Previous Block' END AS block_type, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks GROUP BY year, block_type ORDER BY year;

[User] Can you also include the count of blocks for each year and type combination?

[Assistant] SELECT EXTRACT(YEAR FROM timestamp) AS year, CASE WHEN previous_block_id IS NULL THEN 'No Previous Block' ELSE 'Has Previous Block' END AS block_type, COUNT(*) AS block_count, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks GROUP BY year, block_type ORDER BY year;

[User] List all appointments along with their scheduled start time and the purpose, as well as the name of the location where each appointment is scheduled.

[Assistant]
SELECT a.appointment_id, a.scheduled_start_time, a.purpose, l.location_name
FROM government_services.appointments a
JOIN government_services.service_locations l ON a.location_id = l.location_id;

[User] List the number of applications submitted by each citizen.

[Assistant]
SELECT c.citizen_id, c.first_name, c.last_name, COUNT(a.application_id) AS application_count
FROM government_services.citizens c
LEFT JOIN government_services.applications a ON c.citizen_id = a.citizen_id
GROUP BY c.citizen_id, c.first_name, c.last_name;

[User] Retrieve all room types with a base_rate above 150 for each property.

[Assistant]
SELECT property_id, type_name, base_rate
FROM hospitality_technology.room_types
WHERE base_rate > 150;

[User] Also filter to only include room types with max_occupancy >= 3.

[Assistant]
SELECT property_id, type_name, base_rate
FROM hospitality_technology.room_types
WHERE base_rate > 150
  AND max_occupancy >= 3;

[User] Finally, show guest first and last names of guests created after '2023-01-01' who could book these room types.

[Assistant]
SELECT g.first_name, g.last_name, rt.property_id, rt.type_name, rt.base_rate
FROM hospitality_technology.room_types rt
CROSS JOIN hospitality_technology.guests g
WHERE rt.base_rate > 150
  AND rt.max_occupancy >= 3
  AND g.created_at > '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.transactions ( transaction_id 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.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
##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 trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
##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.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE 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
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 )

[User] List the usernames and registration dates for users who registered before the earliest deployed contract.

[Assistant] SELECT T1.username, T1.created_at FROM web3.users AS T1 JOIN (SELECT MIN(deployed_at) AS earliest_deploy FROM web3.contracts) AS T2 ON T1.created_at < T2.earliest_deploy;

[User] List every diagnosis description paired with every insurance plan's website.

[Assistant] SELECT T1.description, T2.website FROM healthcare.diagnoses AS T1 CROSS JOIN healthcare.insurance_plans AS T2;

[User] Only include chronic diagnoses and plans whose website ends with '.org'.

[Assistant] SELECT T1.description, T2.website FROM healthcare.diagnoses AS T1 CROSS JOIN healthcare.insurance_plans AS T2 WHERE T1.is_chronic = true AND T2.website LIKE '%.org';

[User] What is the average ROI and average realized_ratio for each chain?

[Assistant]
SELECT chain,
       AVG(roi) AS avg_roi,
       AVG(realized_ratio) AS avg_realized_ratio
FROM smart_money_token_performance
GROUP BY chain;

[User] Now filter to only include chains where average ROI is above 0.5.

[Assistant]
WITH stats AS (
  SELECT chain,
         AVG(roi) AS avg_roi,
         AVG(realized_ratio) AS avg_realized_ratio
  FROM smart_money_token_performance
  GROUP BY chain
)
SELECT chain, avg_roi, avg_realized_ratio
FROM stats
WHERE avg_roi > 0.5;

[User] Show me the total fuel quantity and cost for each route, grouped by route number, only for trips that have associated fuel logs.

[Assistant]
SELECT r.route_number, SUM(f.quantity) AS total_quantity, SUM(f.total_cost) AS total_cost
FROM transportation.fuel_logs f
JOIN transportation.routes r ON f.trip_id IS NOT NULL AND f.trip_id IN (
    SELECT DISTINCT trip_id FROM transportation.fuel_logs
)
JOIN transportation.bookings b ON f.trip_id = b.trip_id
WHERE r.route_id = b.trip_id
GROUP BY r.route_number;

[User] List all trades for asset 'BTC' where the trade quantity is greater than 5.

[Assistant] SELECT trade_id, order_id, buyer_id, seller_id, quantity, price, traded_at FROM trading_platform.trades WHERE asset_id = 'BTC' AND quantity > 5;

[User] List all post IDs that have more than one hashtag associated with them.

[Assistant] SELECT post_id FROM social_media.post_hashtags GROUP BY post_id HAVING COUNT(hashtag_id) > 1;

[User] For each of these posts that have multiple hashtags, show the post ID and all associated hashtag IDs.

[Assistant] SELECT DISTINCT t1.post_id, t1.hashtag_id FROM social_media.post_hashtags AS t1 JOIN social_media.post_hashtags AS t2 ON t1.post_id = t2.post_id WHERE t1.post_hashtag_id != t2.post_hashtag_id;

[User] List the names of law firms whose managing partner has uploaded at least one document, and show the managing partner ID along with the firm's phone number.

[Assistant] SELECT DISTINCT T1.firm_name, T1.managing_partner_id, T1.phone FROM legal_services.law_firms AS T1 JOIN legal_services.documents AS T2 ON T1.managing_partner_id = T2.uploaded_by_lawyer_id;

[User] How many medications does each manufacturer have?

[Assistant]
SELECT manufacturer, COUNT(*) AS med_count
FROM healthcare.medications
GROUP BY manufacturer;

[User] Only include manufacturers with more than 10 medications.

[Assistant]
SELECT manufacturer, COUNT(*) AS med_count
FROM healthcare.medications
GROUP BY manufacturer
HAVING COUNT(*) > 10;

[User] For each access level, count the number of employees. Return access_level and the corresponding employee_count.

[Assistant] SELECT access_level, COUNT(*) AS employee_count FROM government_services.employees GROUP BY access_level;