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 )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] List the asset names and symbols for all assets of type 'token'.

[Assistant] SELECT name, symbol FROM trading_platform.assets WHERE type = 'token';

[User] Find all pairs of achievement unlocks and item acquisitions by the same player where the item was acquired after the achievement was unlocked. List player_id, achievement_id, unlocked_at, item_id, and acquired_at.

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at, pi.item_id, pi.acquired_at FROM gaming_technology.player_achievements pa JOIN gaming_technology.player_inventory pi ON pa.player_id = pi.player_id WHERE pi.acquired_at > pa.unlocked_at;

[User] Only include pairs where the item acquisition happened within 24 hours after the achievement unlock.

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at, pi.item_id, pi.acquired_at FROM gaming_technology.player_achievements pa JOIN gaming_technology.player_inventory pi ON pa.player_id = pi.player_id WHERE pi.acquired_at > pa.unlocked_at AND pi.acquired_at <= pa.unlocked_at + INTERVAL '24 hours';

[User] List all insurance products along with their product type and creation date.

[Assistant]
SELECT product_name, product_type, created_at
FROM insurance.insurance_products;

[User] Show me pairs of invoice numbers for the same case.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id ORDER BY T1.case_id, T1.invoice_number, T2.invoice_number

[User] Only include pairs where the total amount of one invoice is greater than the other.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id, T1.total_amount AS invoice1_amount, T2.total_amount AS invoice2_amount FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id WHERE T1.total_amount > T2.total_amount ORDER BY T1.case_id, invoice1_amount DESC

[User] Exclude pairs where the issue dates are more than 90 days apart.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id, T1.total_amount AS invoice1_amount, T2.total_amount AS invoice2_amount, ABS(DATE_PART('day', T1.issue_date - T2.issue_date)) AS days_apart FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id WHERE T1.total_amount > T2.total_amount AND ABS(DATE_PART('day', T1.issue_date - T2.issue_date)) <= 90 ORDER BY T1.case_id, days_apart ASC

[User] Can you list all the policy numbers and their group_numbers for policies that will expire within the next 90 days from today?

[Assistant] SELECT policy_number, group_number FROM healthcare.patient_insurance WHERE expiration_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '90 days';

[User] Only show results where the group_number is not null.

[Assistant] SELECT policy_number, group_number FROM healthcare.patient_insurance WHERE expiration_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '90 days' AND group_number IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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) )
##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.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
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.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE healthcare.prescriptions ( prescription_id text PRIMARY KEY, 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 int, prescription_date timestamp )
##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.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 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.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 )
##Table Structure
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )

[User] Find all law firms that share the same address, listing each address and the two firm names.

[Assistant] SELECT f1.address, f1.firm_name AS firm1, f2.firm_name AS firm2 FROM law_firms f1 JOIN law_firms f2 ON f1.address = f2.address AND f1.firm_id < f2.firm_id;

[User] Actually, only show addresses containing the word 'Street'.

[Assistant] SELECT f1.address, f1.firm_name AS firm1, f2.firm_name AS firm2 FROM law_firms f1 JOIN law_firms f2 ON f1.address = f2.address AND f1.firm_id < f2.firm_id WHERE f1.address LIKE '%Street%';

[User] Count the number of medications for each unique generic name. Show the generic name and the count.

[Assistant]
SELECT
  generic_name,
  COUNT(medication_id) AS medication_count
FROM healthcare.medications
WHERE
  generic_name IS NOT NULL
GROUP BY
  generic_name;

[User] Only show generic names that have more than 5 associated medications.

[Assistant]
SELECT
  generic_name,
  COUNT(medication_id) AS medication_count
FROM healthcare.medications
WHERE
  generic_name IS NOT NULL
GROUP BY
  generic_name
HAVING
  COUNT(medication_id) > 5;

[User] List all unread notifications for group conversations, including the conversation name, sender_user_id, and notification creation time.

[Assistant]
SELECT c.group_name, n.sender_user_id, n.created_at
FROM social_media.notifications n
JOIN social_media.conversations c
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
WHERE c.is_group_chat = TRUE
  AND n.read_at IS NULL;

[User] Actually, show only those notifications created in the last 7 days.

[Assistant]
SELECT c.group_name, n.sender_user_id, n.created_at
FROM social_media.notifications n
JOIN social_media.conversations c
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
WHERE c.is_group_chat = TRUE
  AND n.read_at IS NULL
  AND n.created_at >= now() - interval '7 days';

[User] Find pairs of prescriptions issued to the same patient but for different medications, issued on the same date. Show the patient ID, the prescription IDs of the two prescriptions, and their medication IDs and prescription dates.

[Assistant] SELECT p1.patient_id, p1.prescription_id AS prescription1_id, p1.medication_id AS medication1_id, p2.prescription_id AS prescription2_id, p2.medication_id AS medication2_id, p1.prescription_date FROM healthcare.prescriptions p1 JOIN healthcare.prescriptions p2 ON p1.patient_id = p2.patient_id AND p1.prescription_date = p2.prescription_date AND p1.medication_id <> p2.medication_id AND p1.prescription_id < p2.prescription_id;

[User] Show me the number of notifications sent by each sender in March 2024.

[Assistant]
SELECT sender_user_id, COUNT(notification_id) AS notification_count
FROM social_media.notifications
WHERE created_at >= '2024-03-01'::timestamp
  AND created_at < '2024-04-01'::timestamp
GROUP BY sender_user_id;

[User] What is the average estimated_loss for claims with status 'Filed' or 'Approved'?

[Assistant]
SELECT AVG(estimated_loss) AS avg_estimated_loss
FROM insurance.claims
WHERE status IN ('Filed', 'Approved');

[User] Count how many insurance plans exist for each plan type.

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

[User] Now filter to only show plan types with more than 2 plans.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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)
)
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
##Table Structure
CREATE TABLE legal_services.law_firms (
    firm_id character varying(64) NOT NULL,  -- unique identifier for the law firm
    firm_name character varying(200) NOT NULL, -- official name of the law firm
    address text NOT NULL, -- primary address of the firm
    phone character varying(32), -- firm's main phone number
    website character varying(255), -- firm's website URL
    founded_date date, -- date the firm was established
    managing_partner_id character varying(64), -- FK to lawyers table (optional)
    PRIMARY KEY (firm_id)
)
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address text, token_name text, token_symbol text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_6h numeric, price_change_percentage_24h numeric, makers_24h numeric, volume_24h numeric, liquidity numeric, market_cap numeric, trend_rank numeric )
CREATE TABLE cex_token_balance ( snapshot_time text, chain text, address text, exchange text, token_address text, token_symbol text, balance numeric, usd_value numeric, price numeric )
##Table Structure
CREATE TABLE erc1155_approval_for_all ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text )
CREATE TABLE erc20_balances_historical ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins ( object_id.text, status.text, coin_type.text, balance.text, owner.text )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE token_prices ( uuid.text, blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_bitcoin ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.text, amount.text )
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_activities_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_avalanche ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )

[User] Show properties and the names of their room types.

[Assistant] SELECT T1.property_name ,  T2.type_name FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id  =  T2.property_id

[User] Only list properties in 'California' and include the base rate.

[Assistant] SELECT T1.property_name ,  T2.type_name ,  T2.base_rate FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id  =  T2.property_id WHERE T1.state  =  'California'

[User] Show me each patient and doctor pair that have both an active chronic diagnosis and at least one prescription recorded in the same medical record. Include patient_id, doctor_id, diagnosis_date, prescription_date, and medication_id.

[Assistant]
SELECT
  d.patient_id,
  d.doctor_id,
  d.diagnosis_date,
  p.prescription_date,
  p.medication_id
FROM healthcare.diagnoses d
JOIN healthcare.prescriptions p
  ON d.record_id = p.record_id
WHERE d.is_chronic = TRUE
  AND d.status = 'Active';

[User] I only want records from the last six months and please order by prescription_date descending.

[Assistant]
SELECT
  d.patient_id,
  d.doctor_id,
  d.diagnosis_date,
  p.prescription_date,
  p.medication_id
FROM healthcare.diagnoses d
JOIN healthcare.prescriptions p
  ON d.record_id = p.record_id
WHERE d.is_chronic = TRUE
  AND d.status = 'Active'
  AND d.diagnosis_date >= CURRENT_DATE - INTERVAL '6 months'
ORDER BY p.prescription_date DESC;

[User] List all law firms that have not provided a website.

[Assistant] SELECT firm_id, firm_name FROM legal_services.law_firms WHERE website IS NULL;

[User] Please include their founded date in the output.

[Assistant] SELECT firm_id, firm_name, founded_date FROM legal_services.law_firms WHERE website IS NULL;

[User] What is the total USD value of tokens held by Binance exchange on the Ethereum chain according to the cex_token_balance table?

[Assistant] SELECT SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE exchange = 'Binance' AND chain = 'Ethereum';

[User] List all ERC20 tokens where the price is between $1 and $10, including their names, symbols, and contract addresses.

[Assistant] SELECT t.name, t.symbol, t.address FROM token_prices_latest t WHERE t.price BETWEEN 1 AND 10;

[User] I think there's an error in your query - it should be joining with sui_coins_metadata on coin_type not address. Also, can you add the current price to the results?

[Assistant] SELECT scm.name, scm.symbol, tpl.address, tpl.price FROM token_prices_latest tpl JOIN sui_coins_metadata scm ON tpl.address = scm.coin_type WHERE tpl.price BETWEEN 1 AND 10;

[User] Now filter these results to only show tokens with decimals equal to 18 and sort by name alphabetically.

[Assistant] SELECT scm.name, scm.symbol, tpl.address, tpl.price FROM token_prices_latest tpl JOIN sui_coins_metadata scm ON tpl.address = scm.coin_type WHERE tpl.price BETWEEN 1 AND 10 AND scm.decimals = 18 ORDER BY scm.name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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.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.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
##Table Structure
CREATE TABLE 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) )
##Table Structure
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
##Table Structure
CREATE TABLE 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.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id.text, property_name.text, address_line1.text, address_line2.text, city.text, state_province.text, postal_code.text, country_code.text, phone_number.text, email_address.text, property_type.text, star_rating.numeric, timezone.text, manager_staff_id.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )

[User] Show each contract address and the count of successful transactions sent to that contract.

[Assistant] SELECT c.address, COUNT(t.transaction_id) AS success_tx_count FROM web3.contracts c JOIN web3.transactions t ON t.to_address = c.address AND t.status = 'success' GROUP BY c.address;

[User] Show all contracts that share the same deployment date, along with their contract IDs and the corresponding deployment date.

[Assistant]
SELECT a.contract_id AS contract_id_1, b.contract_id AS contract_id_2, a.deployed_at::date AS deployment_date
FROM web3.contracts a
JOIN web3.contracts b
  ON a.deployed_at::date = b.deployed_at::date AND a.contract_id < b.contract_id;

[User] Actually, I only want to see such pairs where the contracts were deployed by different deployer addresses.

[Assistant]
SELECT a.contract_id AS contract_id_1, b.contract_id AS contract_id_2, a.deployed_at::date AS deployment_date
FROM web3.contracts a
JOIN web3.contracts b
  ON a.deployed_at::date = b.deployed_at::date
  AND a.contract_id < b.contract_id
  AND a.deployer_address <> b.deployer_address;

[User] Show the total amount of payments processed by each payment_method.

[Assistant]
SELECT payment_method,
       SUM(amount) AS total_amount
FROM hospitality_technology.payments
GROUP BY payment_method;

[User] Include only payments with status 'Succeeded' or 'Pending', and order by total_amount descending.

[Assistant]
SELECT payment_method,
       SUM(amount) AS total_amount
FROM hospitality_technology.payments
WHERE status IN ('Succeeded', 'Pending')
GROUP BY payment_method
ORDER BY total_amount DESC;

[User] Find pairs of documents within the same case that were uploaded on the same day but by different lawyers. Show the case_id, upload_date, document_id and uploader_id for both documents in the pair.

[Assistant] SELECT d1.case_id, DATE(d1.upload_timestamp) AS upload_date, d1.document_id AS document1_id, d1.uploaded_by_lawyer_id AS lawyer1_id, d2.document_id AS document2_id, d2.uploaded_by_lawyer_id AS lawyer2_id FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.case_id = d2.case_id AND DATE(d1.upload_timestamp) = DATE(d2.upload_timestamp) AND d1.uploaded_by_lawyer_id <> d2.uploaded_by_lawyer_id WHERE d1.document_id < d2.document_id;

[User] List `user_id` and `conversation_id` for participants who are in conversations where there is at least one message sent by *another* user that they have not read.

[Assistant] SELECT DISTINCT T1.user_id, T1.conversation_id FROM social_media.conversation_participants AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T2.sender_user_id != T1.user_id AND (T1.last_read_at IS NULL OR T2.sent_at > T1.last_read_at);

[User] List each property along with the number of service orders placed by its manager in the last 30 days.

[Assistant]
SELECT p.property_name, COUNT(so.order_id) AS order_count
FROM hospitality_technology.properties p
JOIN hospitality_technology.service_orders so
  ON p.manager_staff_id = so.staff_id_ordered
WHERE so.order_timestamp >= NOW() - INTERVAL '30 days'
GROUP BY p.property_name;

[User] Show product_id, product_name, and base_premium for the five most recently created active insurance products.

[Assistant]
SELECT product_id, product_name, base_premium
FROM insurance.insurance_products
WHERE is_active = true
ORDER BY created_at DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE 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.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
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) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text PRIMARY KEY, 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 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 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 legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] List all employees with the job title 'Analyst'. Show their first name, last name, and department.

[Assistant]
SELECT first_name, last_name, department
FROM government_services.employees
WHERE job_title = 'Analyst';

[User] Count how many prescriptions exist for each medication_id and order the results by the highest count first.

[Assistant]
SELECT medication_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions
GROUP BY medication_id
ORDER BY prescription_count DESC;

[User] List all room numbers with their room type name and property name for rooms that have a Jacuzzi feature.

[Assistant]
SELECT r.room_number, rt.type_name, p.property_name
FROM hospitality_technology.rooms r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.features ILIKE '%Jacuzzi%';

[User] Calculate the total quantity traded for each day in the dataset.

[Assistant] SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at) ORDER BY trade_day;

[User] Could you also include the total trade value (quantity * price) for each day in that report?

[Assistant] SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity, SUM(quantity * price) AS total_daily_value FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at) ORDER BY trade_day;

[User] Now, for each day, show how the total quantity compares to the overall average daily quantity across all days in the dataset.

[Assistant] WITH DailySummary AS (SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at)) SELECT trade_day, total_daily_quantity, total_daily_quantity - AVG(total_daily_quantity) OVER () AS quantity_difference_from_average FROM DailySummary ORDER BY trade_day;

[User] Finally, only show the days where the total quantity was higher than the overall average daily quantity.

[Assistant] WITH DailySummary AS (SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at)) SELECT trade_day, total_daily_quantity FROM DailySummary WHERE total_daily_quantity > (SELECT AVG(total_daily_quantity) FROM DailySummary) ORDER BY trade_day;

[User] Show me the total number of invoices issued.

[Assistant] SELECT COUNT(*) FROM invoices;

[User] How many invoices were issued in each status?

[Assistant] SELECT status, COUNT(*) FROM invoices GROUP BY status;

[User] Only include statuses that have more than 10 invoices.

[Assistant] SELECT status, COUNT(*) FROM invoices GROUP BY status HAVING COUNT(*) > 10;

[User] Also, only consider invoices issued in the year 2023 and order the results by the count in descending order.

[Assistant] SELECT status, COUNT(*) FROM invoices WHERE EXTRACT(YEAR FROM issue_date) = 2023 GROUP BY status HAVING COUNT(*) > 10 ORDER BY COUNT(*) DESC;

[User] List all insurance plans along with their provider, plan type, and the contact phone number. Also, for each plan, show how many doctors have their hospital affiliation ID matching the plan ID.

[Assistant] SELECT ip.plan_id, ip.plan_name, ip.insurance_provider, ip.plan_type, ip.contact_phone, COUNT(d.doctor_id) FROM healthcare.insurance_plans ip LEFT JOIN healthcare.doctors d ON ip.plan_id = d.hospital_affiliation_id GROUP BY ip.plan_id, ip.plan_name, ip.insurance_provider, ip.plan_type, ip.contact_phone


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.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.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
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) )
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
##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 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 )

[User] Count the number of active services provided by each agency. Return the agency_name and the count of active services for each.

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

[User] List the plan_id, plan_name, and plan_type for all insurance plans where the insurance_provider is 'Humana'.

[Assistant]
SELECT
  plan_id,
  plan_name,
  plan_type
FROM healthcare.insurance_plans
WHERE
  insurance_provider = 'Humana';

[User] Get each review with the next review date for the same guest.

[Assistant]
SELECT guest_id, review_id, review_date,
       LEAD(review_date) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_date
FROM hospitality_technology.reviews;

[User] Exclude entries where there's no next review.

[Assistant]
SELECT guest_id, review_id, review_date, next_review_date
FROM (
  SELECT guest_id, review_id, review_date,
         LEAD(review_date) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_date
  FROM hospitality_technology.reviews
) t
WHERE next_review_date IS NOT NULL;

[User] Now join the table to retrieve the comment of the next review as well.

[Assistant]
WITH sequenced AS (
  SELECT guest_id, review_id, review_date,
         LEAD(review_id) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_id,
         LEAD(review_date) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_date
  FROM hospitality_technology.reviews
)
SELECT s.guest_id,
       s.review_id,
       s.review_date,
       r2.review_id AS next_review_id,
       r2.review_date AS next_review_date,
       r2.comment AS next_comment
FROM sequenced s
JOIN hospitality_technology.reviews r2
  ON s.next_review_id = r2.review_id
WHERE s.next_review_id IS NOT NULL;

[User] List all contracts along with the username of the deployer, showing contract_id, contract address, deployed_at, and the username. Order by deployed_at descending.

[Assistant]
SELECT c.contract_id,
       c.address AS contract_address,
       c.deployed_at,
       u.username
FROM web3.contracts c
LEFT JOIN web3.wallets w ON c.deployer_address = w.address
LEFT JOIN web3.users u ON w.user_id = u.user_id
ORDER BY c.deployed_at 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 healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
##Table Structure
CREATE TABLE 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 )

[User] Show the names of all insurance plans and the number of patients enrolled in each plan.

[Assistant] SELECT ip.plan_name, COUNT(pi.patient_id) AS enrolled_patients FROM healthcare.insurance_plans ip JOIN healthcare.patient_insurance pi ON ip.plan_id = pi.plan_id GROUP BY ip.plan_name;

[User] List pairs of invoice_number for invoices that share the same due_date.

[Assistant]
SELECT a.due_date,
       a.invoice_number AS invoice1,
       b.invoice_number AS invoice2
FROM legal_services.invoices a
JOIN legal_services.invoices b
  ON a.due_date = b.due_date
  AND a.invoice_id < b.invoice_id;

[User] Only include pairs where the due_date is in March 2024.

[Assistant]
SELECT a.due_date,
       a.invoice_number AS invoice1,
       b.invoice_number AS invoice2
FROM legal_services.invoices a
JOIN legal_services.invoices b
  ON a.due_date = b.due_date
  AND a.invoice_id < b.invoice_id
WHERE a.due_date BETWEEN '2024-03-01' AND '2024-03-31';

[User] Retrieve each managing partner who oversees more than one firm, showing the managing_partner_id and the count of firms they manage.

[Assistant]
SELECT managing_partner_id, COUNT(*) AS firm_count
FROM legal_services.law_firms
GROUP BY managing_partner_id
HAVING COUNT(*) > 1;

[User] Actually, I want to include the names of the firms under each managing partner, separated by commas.

[Assistant]
SELECT managing_partner_id,
       COUNT(*) AS firm_count,
       STRING_AGG(firm_name, ', ') AS firms
FROM legal_services.law_firms
GROUP BY managing_partner_id
HAVING COUNT(*) > 1;

[User] Also, exclude any records where the managing_partner_id is null and sort the results by firm_count descending.

[Assistant]
SELECT managing_partner_id,
       COUNT(*) AS firm_count,
       STRING_AGG(firm_name, ', ') AS firms
FROM legal_services.law_firms
WHERE managing_partner_id IS NOT NULL
GROUP BY managing_partner_id
HAVING COUNT(*) > 1
ORDER BY firm_count DESC;

[User] Show me law firms that were founded after 2018 and have a website provided.

[Assistant]
SELECT firm_name, founded_date, website
FROM legal_services.law_firms
WHERE founded_date > '2018-12-31' AND website IS NOT NULL AND website <> '';

[User] Actually, only include firms where the phone number starts with '+1'.

[Assistant]
SELECT firm_name, founded_date, website, phone
FROM legal_services.law_firms
WHERE founded_date > '2018-12-31' AND website IS NOT NULL AND website <> '' AND phone LIKE '+1%';

[User] Also add the firm address and sort the results by founded_date descending.

[Assistant]
SELECT firm_name, founded_date, website, phone, address
FROM legal_services.law_firms
WHERE founded_date > '2018-12-31' AND website IS NOT NULL AND website <> '' AND phone LIKE '+1%'
ORDER BY founded_date DESC;

[User] Show me all vehicles that are due for their next service before the end of this month, along with their last service date and type.

[Assistant] SELECT v.vehicle_id, v.make, v.model, s.service_date, s.service_type FROM transportation.vehicles v JOIN transportation.service_logs s ON v.vehicle_id = s.vehicle_id WHERE s.next_service_due <= DATE('now', 'start of month', '+1 month', '-1 day') ORDER BY s.next_service_due;

[User] Can you include the mechanic who performed the last service and order the results by how soon the next service is due?

[Assistant] SELECT v.vehicle_id, v.make, v.model, s.service_date, s.service_type, s.mechanic, s.next_service_due FROM transportation.vehicles v JOIN transportation.service_logs s ON v.vehicle_id = s.vehicle_id WHERE s.next_service_due <= DATE('now', 'start of month', '+1 month', '-1 day') ORDER BY s.next_service_due ASC;

[User] Now filter this to only show vehicles where the last service was an 'Engine Tune-up'.

[Assistant] SELECT v.vehicle_id, v.make, v.model, s.service_date, s.service_type, s.mechanic, s.next_service_due FROM transportation.vehicles v JOIN transportation.service_logs s ON v.vehicle_id = s.vehicle_id WHERE s.next_service_due <= DATE('now', 'start of month', '+1 month', '-1 day') AND s.service_type = 'Engine Tune-up' ORDER BY s.next_service_due ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
##Table Structure
CREATE TABLE 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 trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text PRIMARY KEY, 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 PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
##Table Structure
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
##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 hospitality_technology.payments ( payment_id text PRIMARY KEY, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
##Table Structure
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )

[User] List all pairs of token transfers occurring within the same transaction where one transferred value is greater than the other, showing both transfer IDs, the transaction ID, and both values.

[Assistant]
SELECT t1.transaction_id,
       t1.transfer_id AS transfer_id_1,
       t2.transfer_id AS transfer_id_2,
       t1.value       AS value_1,
       t2.value       AS value_2
FROM web3.token_transfers t1
JOIN web3.token_transfers t2
  ON t1.transaction_id = t2.transaction_id
 AND t1.value > t2.value;

[User] List all drivers whose licenses are set to expire within the next 60 days, along with their full name, license number, and contact number.

[Assistant]
SELECT driver_id, first_name, last_name, license_number, contact_number
FROM transportation.drivers
WHERE license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days';

[User] Provide a summary for each transaction ID, showing the total amount of all its unspent UTXOs.

[Assistant] SELECT transaction_id, SUM(amount) FROM utxos WHERE spent = false GROUP BY transaction_id

[User] List all wallets that were created during the hour of the day which saw the highest number of wallet creations. Show the wallet ID, user ID, address, and creation timestamp.

[Assistant]
WITH HourlyCounts AS (
    SELECT EXTRACT(HOUR FROM created_at) AS hour, COUNT(*) AS wallet_count
    FROM web3.wallets
    GROUP BY 1
),
MaxHour AS (
    SELECT hour
    FROM HourlyCounts
    ORDER BY wallet_count DESC
    LIMIT 1
)
SELECT wallet_id, user_id, address, created_at
FROM web3.wallets
WHERE EXTRACT(HOUR FROM created_at) = (SELECT hour FROM MaxHour);

[User] For each block that contains more than 5 transactions, list the block number, the total sum of values transferred within that block, and the average gas used per transaction in that block.

[Assistant] SELECT block_number, SUM(value) AS total_value_in_block, AVG(gas_used) AS average_gas_used FROM web3.transactions GROUP BY block_number HAVING COUNT(*) > 5 ORDER BY block_number;

[User] For each service location, find its nearest accessible location by geographic distance.

[Assistant]
SELECT sl.location_id,
       sl.location_name,
       nearest.location_id   AS nearest_location_id,
       nearest.location_name AS nearest_location_name
FROM government_services.service_locations sl
JOIN LATERAL (
  SELECT sl2.location_id,
         sl2.location_name
  FROM government_services.service_locations sl2
  WHERE sl2.is_accessible = TRUE
    AND sl2.location_id <> sl.location_id
  ORDER BY ((sl.latitude - sl2.latitude)^2 + (sl.longitude - sl2.longitude)^2) ASC
  LIMIT 1
) AS nearest ON TRUE;

[User] How many appointments were created in the month of July 2024?

[Assistant]
SELECT COUNT(*) AS appointment_count
FROM legal_services.appointments
WHERE DATE_TRUNC('month', created_at) = DATE '2024-07-01';

[User] Show me each product_type along with the count of products for that type, but only include types where the average base_premium exceeds 500. Order the results by the product count in descending order.

[Assistant]
SELECT product_type,
       COUNT(*) AS product_count
FROM insurance.insurance_products
GROUP BY product_type
HAVING AVG(base_premium) > 500
ORDER BY product_count DESC;

[User] Show me each generic_name and the number of medications with that generic_name, sorted by the highest count first.

[Assistant] SELECT generic_name, COUNT(*) AS medication_count FROM healthcare.medications GROUP BY generic_name ORDER BY medication_count DESC;

[User] What is the average and maximum standard fee for services in each category?

[Assistant] SELECT category, AVG(standard_fee) AS avg_standard_fee, MAX(standard_fee) AS max_standard_fee FROM government_services.services GROUP BY category;

[User] Show me all payments along with the currency code and payment method for each payment, and include the amount and status. Group the results by payment method and currency code, and order by total payment amount descending.

[Assistant]
SELECT payment_method, currency_code, SUM(amount) AS total_payment_amount, COUNT(*) AS payment_count
FROM hospitality_technology.payments
GROUP BY payment_method, currency_code
ORDER BY total_payment_amount DESC;

[User] How many active services currently provide an online application URL?

[Assistant]
SELECT COUNT(*)
FROM government_services.services
WHERE is_active = TRUE
  AND online_application_url IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE gaming_technology.developers (
    developer_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the developer studio
    name character varying(150) NOT NULL UNIQUE, -- name of the development studio
    country character varying(100), -- country where the studio is based
    founded_year integer, -- year the studio was founded
    website character varying(255), -- developer's official website
    created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (developer_id)
)
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )
##Table Structure
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) )
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, game_id uuid NOT NULL, server_id uuid, start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb, PRIMARY KEY (session_id) )
CREATE TABLE gaming_technology.servers ( server_id uuid PRIMARY KEY, game_id uuid, server_name text, region text, ip_address text, port int, current_players int, max_players int, status text, last_heartbeat timestamptz )
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
##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 insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )

[User] Show for each developer and inventory item combination the number of times that item appears in player inventories.

[Assistant] SELECT d.developer_id, d.name AS developer_name, pi.item_id, COUNT(pi.inventory_id) AS inventory_count FROM gaming_technology.developers d JOIN gaming_technology.player_inventory pi ON d.developer_id = pi.item_id GROUP BY d.developer_id, d.name, pi.item_id;

[User] The query failed because developer_id and item_id are not the same. Can you count, for each developer, how many player inventory records exist for items created in that developer's country?

[Assistant] SELECT d.name AS developer_name, COUNT(pi.inventory_id) AS inventory_count FROM gaming_technology.developers d JOIN gaming_technology.player_inventory pi ON d.country IS NOT NULL GROUP BY d.name;

[User] Can you instead show the number of player inventory records per developer, grouped by country?

[Assistant] SELECT d.country, COUNT(pi.inventory_id) AS inventory_count FROM gaming_technology.developers d LEFT JOIN gaming_technology.player_inventory pi ON TRUE WHERE d.country IS NOT NULL GROUP BY d.country;

[User] List all pairs of hashtags created on the same calendar date, showing both tag names and the creation date.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2, DATE(h1.created_at) AS created_date
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON DATE(h1.created_at) = DATE(h2.created_at)
  AND h1.hashtag_id <> h2.hashtag_id;

[User] Also, only include each pair once by enforcing the first tag_name to be alphabetically before the second.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2, DATE(h1.created_at) AS created_date
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON DATE(h1.created_at) = DATE(h2.created_at)
  AND h1.tag_name < h2.tag_name;

[User] For each developer, show their name and the total number of achievements in all games they have developed.

[Assistant]
SELECT d.name AS developer_name, COUNT(a.achievement_id) AS total_achievements
FROM gaming_technology.developers d
JOIN gaming_technology.servers s ON d.developer_id = s.game_id -- There is no direct relationship, but assuming developer_id and game_id are connected
JOIN gaming_technology.achievements a ON s.game_id = a.game_id
GROUP BY d.developer_id, d.name;

[User] I think the join between developers and servers is not correct, because developer_id and game_id are different types. Could you try to just show the total number of achievements across all games, and their respective developers, if possible with the current tables?

[Assistant]
SELECT '-' AS developer_name, COUNT(a.achievement_id) AS total_achievements
FROM gaming_technology.achievements a;

[User] Can you instead list the total number of achievements available for each game_id?

[Assistant]
SELECT game_id, COUNT(achievement_id) AS total_achievements
FROM gaming_technology.achievements
GROUP BY game_id;

[User] What is the average overall rating grouped by review_source?

[Assistant]
SELECT review_source, AVG(rating_overall) AS avg_overall_rating, COUNT(*) AS review_count
FROM hospitality_technology.reviews
GROUP BY review_source;

[User] Actually, exclude sources with fewer than 10 reviews.

[Assistant]
SELECT review_source, AVG(rating_overall) AS avg_overall_rating, COUNT(*) AS review_count
FROM hospitality_technology.reviews
GROUP BY review_source
HAVING COUNT(*) >= 10;

[User] How many agents are currently active in each license state?

[Assistant]
SELECT license_state, COUNT(*) AS active_agent_count
FROM insurance.agents
WHERE status = 'Active'
GROUP BY license_state;

[User] How many appointments have a status of 'Cancelled'?

[Assistant] SELECT COUNT(*) FROM legal_services.appointments WHERE status = 'Cancelled';


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.text, from_address.text, to_address.text, value.numeric, gas_used.integer, gas_price.numeric, block_number.integer, timestamp.timestamp, input_data.text, status.text, nonce.integer )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
##Table Structure
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id 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) )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )
##Table Structure
CREATE TABLE 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)
)
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, 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.timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, game_id uuid NOT NULL, server_id uuid, start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb, PRIMARY KEY (session_id) )

[User] Show me all contracts deployed on the 'ethereum' network along with their deployer addresses and the count of transactions they've been involved in, sorted by transaction count in descending order.

[Assistant] SELECT c.contract_id, c.address, c.deployer_address, COUNT(t.transaction_id) AS transaction_count FROM web3.contracts c LEFT JOIN web3.transactions t ON c.address = t.to_address OR c.address = t.from_address WHERE c.network_id = 'ethereum' GROUP BY c.contract_id, c.address, c.deployer_address ORDER BY transaction_count DESC;

[User] Count the number of diagnoses for each unique diagnosis code.

[Assistant] SELECT diagnosis_code, COUNT(*) FROM healthcare.diagnoses GROUP BY diagnosis_code;

[User] Only show the diagnosis codes that have more than 10 entries.

[Assistant] SELECT diagnosis_code, COUNT(*) FROM healthcare.diagnoses GROUP BY diagnosis_code HAVING COUNT(*) > 10;

[User] List all agents whose commission rate is higher than their manager's commission rate, including the agent's full name, their commission rate, the manager's full name, and the manager's commission rate.

[Assistant] SELECT CONCAT(a.first_name, ' ', a.last_name) AS agent_full_name, a.commission_rate AS agent_commission_rate, CONCAT(m.first_name, ' ', m.last_name) AS manager_full_name, m.commission_rate AS manager_commission_rate FROM insurance.agents AS a JOIN insurance.agents AS m ON a.manager_id = m.agent_id WHERE a.commission_rate > m.commission_rate;

[User] Find all service locations that currently have no appointments scheduled. Display the location name and contact phone number.

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

[User] Find all pairs of transactions where both transactions have the same nonce and from_address, but different transaction_id. Show both transaction IDs, the shared from_address, shared nonce, and their block numbers.

[Assistant]
SELECT t1.transaction_id AS transaction_id_1, t2.transaction_id AS transaction_id_2, t1.from_address, t1.nonce, t1.block_number AS block_number_1, t2.block_number AS block_number_2
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.from_address = t2.from_address
 AND t1.nonce = t2.nonce
 AND t1.transaction_id < t2.transaction_id;

[User] What is the average score across all game sessions for each game? Include the game title and the average score.

[Assistant] SELECT T1.title, AVG(T2.score) FROM gaming_technology.games AS T1 JOIN gaming_technology.game_sessions AS T2 ON T1.game_id = T2.game_id GROUP BY T1.title;


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 financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
##Table Structure
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
##Table Structure
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE 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.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
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 legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id text, first_name text, last_name text, bar_number text, firm_id text, email text, phone text, specialization text, hire_date timestamp, is_partner boolean )
##Table Structure
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
##Table Structure
CREATE TABLE 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) )

[User] List each account number and the total quantity of shares traded through it.

[Assistant] SELECT T2.account_number, SUM(T1.quantity) FROM financial_services.trades AS T1 JOIN financial_services.accounts AS T2 ON T1.account_id = T2.account_id GROUP BY 1

[User] Only include accounts with total quantity traded greater than 1000, and order the results by total quantity descending.

[Assistant] SELECT T2.account_number, SUM(T1.quantity) AS total_traded_quantity FROM financial_services.trades AS T1 JOIN financial_services.accounts AS T2 ON T1.account_id = T2.account_id GROUP BY 1 HAVING SUM(T1.quantity) > 1000 ORDER BY total_traded_quantity DESC

[User] Show me all assets whose symbol starts with 'BTC' or 'ETH', along with their full names and types.

[Assistant] SELECT asset_id, name, symbol, type FROM trading_platform.assets WHERE symbol LIKE 'BTC%' OR symbol LIKE 'ETH%';

[User] Find all tokens on the 'BSC' chain in the latest snapshot where the individual holding `usd_value` is greater than $1,000,000. Show their symbol, exchange, balance, and USD value.

[Assistant]
WITH latest_snapshot AS (
  SELECT max(snapshot_time) as max_time
  FROM cex_token_balance
)
SELECT token_symbol, exchange, balance, usd_value
FROM cex_token_balance ctb
JOIN latest_snapshot ls ON ctb.snapshot_time = ls.max_time
WHERE chain = 'BSC' AND usd_value > 1000000.0;

[User] Retrieve all notifications with status 'failed' along with the citizen's full name and contact_phone for those notifications that occurred in the past 30 days.

[Assistant]
SELECT n.notification_id,
       n.sent_at,
       n.status,
       c.first_name || ' ' || c.last_name AS full_name,
       c.contact_phone
FROM government_services.notifications n
JOIN government_services.citizens c
  ON n.citizen_id = c.citizen_id
WHERE n.status = 'failed'
  AND n.sent_at >= NOW() - INTERVAL '30 days';

[User] List each insurance provider along with the number of distinct plan types they offer.

[Assistant]
SELECT insurance_provider, COUNT(DISTINCT plan_type) AS type_count
FROM healthcare.insurance_plans
GROUP BY insurance_provider;

[User] How many clients registered in each month of 2024? Provide the month (YYYY-MM) and the number of registrations.

[Assistant] SELECT TO_CHAR(date_registered, 'YYYY-MM') AS month, COUNT(*) AS registration_count FROM legal_services.clients WHERE date_registered BETWEEN '2024-01-01' AND '2024-12-31' GROUP BY month ORDER BY month;

[User] List the sender_user_id and the total number of messages they have sent that include media attachments, along with the conversation_id.

[Assistant]
SELECT sender_user_id, conversation_id, COUNT(*) AS media_message_count
FROM social_media.messages
WHERE media_url IS NOT NULL AND media_url <> ''
GROUP BY sender_user_id, conversation_id;

[User] Only include media attachments where media_type is 'video'.

[Assistant]
SELECT sender_user_id, conversation_id, COUNT(*) AS video_media_message_count
FROM social_media.messages
WHERE media_url IS NOT NULL AND media_url <> '' AND media_type = 'video'
GROUP BY sender_user_id, conversation_id;

[User] How many users registered in 2024?

[Assistant] SELECT COUNT(*) FROM trading_platform.users WHERE DATE_PART('year', created_at) = 2024;

[User] Count the total number of hashtags.

[Assistant] SELECT COUNT(*) FROM social_media.hashtags;