System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
##Table Structure
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
##Table Structure
CREATE TABLE healthcare.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)
)
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] For each booking, show the booking_id, seat_number, fare, and the city of the origin location for the trip that was booked.

[Assistant]
SELECT b.booking_id, b.seat_number, b.fare, orig.city AS origin_city
FROM transportation.bookings b
JOIN transportation.trips t ON b.trip_id = t.trip_id
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.locations orig ON r.origin_location_id = orig.location_id;

[User] Can you show me the name, city, and type for all locations that are in the same city but have different types?

[Assistant] SELECT l1.name, l1.city, l1.type FROM transportation.locations l1 JOIN transportation.locations l2 ON l1.city = l2.city AND l1.location_id <> l2.location_id AND l1.type <> l2.type;

[User] Please only include locations where the city is 'Chicago'.

[Assistant] SELECT l1.name, l1.city, l1.type FROM transportation.locations l1 JOIN transportation.locations l2 ON l1.city = l2.city AND l1.location_id <> l2.location_id AND l1.type <> l2.type WHERE l1.city = 'Chicago';

[User] Show me all pairs of plans offered by the same insurance provider but of different plan types, including the provider name, first plan ID and type, and second plan ID and type.

[Assistant]
SELECT a.insurance_provider,
       a.plan_id AS plan_id_1,
       a.plan_type AS type_1,
       b.plan_id AS plan_id_2,
       b.plan_type AS type_2
FROM healthcare.insurance_plans a
JOIN healthcare.insurance_plans b
  ON a.insurance_provider = b.insurance_provider
 AND a.plan_type <> b.plan_type
 AND a.plan_id < b.plan_id;

[User] Can you restrict this to only those providers that offer at least three distinct plan types?

[Assistant]
SELECT a.insurance_provider,
       a.plan_id AS plan_id_1,
       a.plan_type AS type_1,
       b.plan_id AS plan_id_2,
       b.plan_type AS type_2
FROM healthcare.insurance_plans a
JOIN healthcare.insurance_plans b
  ON a.insurance_provider = b.insurance_provider
 AND a.plan_type <> b.plan_type
 AND a.plan_id < b.plan_id
WHERE a.insurance_provider IN (
  SELECT insurance_provider
  FROM healthcare.insurance_plans
  GROUP BY insurance_provider
  HAVING COUNT(DISTINCT plan_type) >= 3
);

[User] Find agents whose commission_rate is higher than their manager's commission_rate. Show agent_id, agent first_name, agent last_name, commission_rate, manager_id, and the manager's commission_rate.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.commission_rate,
       a.manager_id,
       m.commission_rate AS manager_commission_rate
  FROM insurance.agents a
  JOIN insurance.agents m
    ON a.manager_id = m.agent_id
 WHERE a.commission_rate > m.commission_rate;

[User] Now restrict to agents hired before January 1, 2023.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.commission_rate,
       a.manager_id,
       m.commission_rate AS manager_commission_rate
  FROM insurance.agents a
  JOIN insurance.agents m
    ON a.manager_id = m.agent_id
 WHERE a.commission_rate > m.commission_rate
   AND a.hire_date < '2023-01-01';

[User] Find the diagnosis code and description for all non-chronic diagnoses for patient 'patient_789' made by doctor 'doctor_abc'.

[Assistant] SELECT diagnosis_code, description FROM healthcare.diagnoses WHERE patient_id = 'patient_789' AND doctor_id = 'doctor_abc' AND is_chronic = false;

[User] List all unique policies that have claim documents of type 'Claim Form'. For each, return the policy_number, start_date, end_date, and the document file_name.

[Assistant]
SELECT DISTINCT p.policy_number, p.start_date, p.end_date, cd.file_name
FROM insurance.policies p
JOIN insurance.claim_documents cd ON p.policy_id = cd.claim_id
WHERE cd.document_type = 'Claim Form';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)
##Table Structure
CREATE TABLE financial_services.transactions ( transaction_id text PRIMARY KEY, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
##Table Structure
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)

[User] For each fuel_type, can you calculate the total total_cost and the average total_cost from the fuel_logs table?

[Assistant]
SELECT fuel_type,
       SUM(total_cost) AS total_cost_sum,
       AVG(total_cost) AS average_cost
FROM transportation.fuel_logs
GROUP BY fuel_type;

[User] Please exclude any fuel_type with fewer than 5 fuel log entries.

[Assistant]
SELECT fuel_type,
       SUM(total_cost) AS total_cost_sum,
       AVG(total_cost) AS average_cost
FROM transportation.fuel_logs
GROUP BY fuel_type
HAVING COUNT(*) >= 5;

[User] Give me the total transaction amount and the total count of transactions per day for each currency.

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency;

[User] Exclude days where the summed amount is less than 50000.

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency
HAVING SUM(amount) >= 50000;

[User] Sort the results by the total_amount descending and limit to the top 5 records.

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency
HAVING SUM(amount) >= 50000
ORDER BY total_amount DESC
LIMIT 5;

[User] Show all pairs of patients who share the same email domain. Return patient1_id, patient2_id, and the shared domain, but do not pair a patient with themselves.

[Assistant] SELECT p1.patient_id AS patient1_id, p2.patient_id AS patient2_id, SUBSTRING(p1.email FROM POSITION('@' IN p1.email) + 1) AS shared_domain FROM healthcare.patients p1 JOIN healthcare.patients p2 ON SUBSTRING(p1.email FROM POSITION('@' IN p1.email) + 1) = SUBSTRING(p2.email FROM POSITION('@' IN p2.email) + 1) AND p1.patient_id <> p2.patient_id WHERE p1.email IS NOT NULL AND p2.email IS NOT NULL;

[User] Find the total amount paid for all premium payments made in the last 30 days.

[Assistant] SELECT SUM(amount_paid) FROM insurance.premium_payments WHERE payment_date >= CURRENT_DATE - INTERVAL '30 day';

[User] List all tokens with a total supply greater than 1,000,000.

[Assistant]
SELECT token_id, token_name, token_symbol, contract_address, total_supply
FROM web3.tokens
WHERE total_supply > 1000000;

[User] Can you also include the decimals for each token in the result?

[Assistant]
SELECT token_id, token_name, token_symbol, contract_address, total_supply, decimals
FROM web3.tokens
WHERE total_supply > 1000000;


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.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_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 trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )

[User] For each user, count the number of distinct smart contracts they have called. Return user_id, username, and contract_count, ordered by contract_count descending.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(DISTINCT tx.to_address) AS contract_count
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
JOIN web3.transactions tx ON w.address = tx.from_address
JOIN web3.contracts c ON tx.to_address = c.address
GROUP BY u.user_id, u.username
ORDER BY contract_count DESC;

[User] Count the total number of public posts.

[Assistant] SELECT COUNT(*) FROM social_media.posts WHERE visibility = 'public';

[User] Show me all payments made with a credit card (payment_method = 'credit_card') where the amount is greater than $500, including the reservation ID and payment timestamp.

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp FROM hospitality_technology.payments WHERE payment_method = 'credit_card' AND amount > 500 ORDER BY payment_timestamp DESC;

[User] Now, include only payments that were processed by staff members with ID starting with 'STAFF1' and show the card type used.

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp, card_type FROM hospitality_technology.payments WHERE payment_method = 'credit_card' AND amount > 500 AND staff_id_processed LIKE 'STAFF1%' ORDER BY payment_timestamp DESC;

[User] Show me pairs of wallets that belong to the same user, listing the wallet_id, user_id, address, and created_at for the earlier and later wallet in each pair.

[Assistant]
SELECT w1.user_id,
       w1.wallet_id AS earlier_wallet,
       w1.address AS earlier_address,
       w1.created_at AS earlier_created_at,
       w2.wallet_id AS later_wallet,
       w2.address AS later_address,
       w2.created_at AS later_created_at
FROM trading_platform.wallets w1
JOIN trading_platform.wallets w2
  ON w1.user_id = w2.user_id
 AND w1.created_at < w2.created_at;

[User] Now only include pairs where the later wallet was created more than 30 days after the earlier one.

[Assistant]
SELECT w1.user_id,
       w1.wallet_id AS earlier_wallet,
       w1.address AS earlier_address,
       w1.created_at AS earlier_created_at,
       w2.wallet_id AS later_wallet,
       w2.address AS later_address,
       w2.created_at AS later_created_at
FROM trading_platform.wallets w1
JOIN trading_platform.wallets w2
  ON w1.user_id = w2.user_id
 AND w2.created_at > w1.created_at + INTERVAL '30 days';

[User] Find all pairs of vehicles that have the same make and model but different fuel types. For each pair, display the first vehicle_id, the second vehicle_id, make, model, fuel_type of the first as fuel_type1 and of the second as fuel_type2.

[Assistant] SELECT v1.vehicle_id AS vehicle1_id, v2.vehicle_id AS vehicle2_id, v1.make, v1.model, v1.fuel_type AS fuel_type1, v2.fuel_type AS fuel_type2 FROM transportation.vehicles v1 JOIN transportation.vehicles v2 ON v1.make = v2.make AND v1.model = v2.model AND v1.vehicle_id < v2.vehicle_id AND v1.fuel_type <> v2.fuel_type;

[User] Show a list of all routes including their route number, type, distance in km, and estimated duration in minutes.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes;

[User] Filter this list to only show routes of type 'Express'.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes
WHERE
  type = 'Express';

[User] Sort the results by distance in descending order and limit to the top 5.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes
WHERE
  type = 'Express'
ORDER BY
  distance_km DESC
LIMIT 5;

[User] Add the description and a column 'duration_per_km' showing the duration per kilometer.

[Assistant]
SELECT
  route_number,
  type,
  description,
  distance_km,
  estimated_duration_minutes,
  CAST(estimated_duration_minutes AS NUMERIC) / NULLIF(distance_km, 0) AS duration_per_km
FROM transportation.routes
WHERE
  type = 'Express'
ORDER BY
  distance_km DESC
LIMIT 5;

[User] How many customers were created in 2023?

[Assistant]
SELECT COUNT(*)
FROM insurance.customers
WHERE EXTRACT(YEAR FROM created_at) = 2023;


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.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.utxos ( utxo_id character varying(64) NOT NULL, transaction_id character varying(64) NOT NULL, output_index integer NOT NULL, address character varying(128) NOT NULL, amount numeric(38,14) NOT NULL, spent boolean NOT NULL, PRIMARY KEY (utxo_id) )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, status character varying(32) NOT NULL, reviewed_at timestamp NOT NULL, PRIMARY KEY (kyc_audit_id) )
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
CREATE TABLE trading_platform.notifications ( notification_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, message text NOT NULL, sent_at timestamp NOT NULL, read_at timestamp, PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE blockchain.addresses ( address_id character varying(128) NOT NULL, public_key text NOT NULL, balance numeric(38,14) NOT NULL, PRIMARY KEY (address_id) )
##Table Structure
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.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 government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )

[User] How many DApps have names that start with the letter 'A'?

[Assistant]
SELECT COUNT(*) AS dapp_count
FROM trading_platform.dapps
WHERE name LIKE 'A%';

[User] List all address IDs and their corresponding public keys from the addresses table.

[Assistant] SELECT address_id, public_key FROM blockchain.addresses;

[User] Now, filter these results to only include addresses where the balance is greater than 5000.

[Assistant] SELECT address_id, public_key, balance FROM blockchain.addresses WHERE balance > 5000;

[User] Can you tell me how many addresses satisfy this condition?

[Assistant] SELECT COUNT(*) FROM blockchain.addresses WHERE balance > 5000;

[User] What is the average balance for these addresses that have a balance greater than 5000?

[Assistant] SELECT AVG(balance) FROM blockchain.addresses WHERE balance > 5000;

[User] Show me all users who have commented on a post and have also liked any comment on that same post. I want their user IDs and the corresponding post IDs.

[Assistant]
SELECT DISTINCT c.user_id, c.post_id
FROM social_media.comments c
JOIN social_media.likes l ON l.comment_id IS NOT NULL AND l.post_id = c.post_id AND l.user_id = c.user_id

[User] Can you also include the comment content that was liked and the time the like was created?

[Assistant]
SELECT DISTINCT c.user_id, c.post_id, c2.content AS liked_comment_content, l.created_at AS like_created_at
FROM social_media.comments c
JOIN social_media.likes l ON l.comment_id IS NOT NULL AND l.post_id = c.post_id AND l.user_id = c.user_id
JOIN social_media.comments c2 ON c2.comment_id = l.comment_id

[User] Find pairs of active services within the same category provided by the same agency, where one service has an average processing time more than double the other's. Display the agency ID, category, the first service name and its processing time, and the second service name and its processing time.

[Assistant] SELECT s1.agency_id, s1.category, s1.service_name AS service1_name, s1.average_processing_time_days AS service1_processing_time_days, s2.service_name AS service2_name, s2.average_processing_time_days AS service2_processing_time_days FROM government_services.services AS s1 JOIN government_services.services AS s2 ON s1.agency_id = s2.agency_id AND s1.category = s2.category AND s1.service_id < s2.service_id WHERE s1.is_active = TRUE AND s2.is_active = TRUE AND s1.average_processing_time_days IS NOT NULL AND s2.average_processing_time_days IS NOT NULL AND (s1.average_processing_time_days > 2 * s2.average_processing_time_days OR s2.average_processing_time_days > 2 * s1.average_processing_time_days);

[User] What is the average price of services grouped by category? Display category and average_price.

[Assistant] SELECT category, AVG(price) AS average_price FROM hospitality_technology.services GROUP BY category;

[User] Only include categories where the average_price is above 100 and order by average_price descending.

[Assistant] SELECT category, AVG(price) AS average_price FROM hospitality_technology.services GROUP BY category HAVING AVG(price) > 100 ORDER BY average_price 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 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)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
##Table Structure
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )
##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 )
##Table Structure
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )

[User] Get a list of appointment_id, start_time, and invoice_number for appointments that have a related invoice.

[Assistant]
SELECT a.appointment_id,
       a.start_time,
       i.invoice_number
FROM legal_services.appointments a
JOIN legal_services.invoices i
  ON a.case_id = i.case_id;

[User] Also include only appointments that are completed and invoices that are fully paid (status 'Paid').

[Assistant]
SELECT a.appointment_id,
       a.start_time,
       i.invoice_number
FROM legal_services.appointments a
JOIN legal_services.invoices i
  ON a.case_id = i.case_id
WHERE a.status = 'Completed'
  AND i.status = 'Paid';

[User] Show me all policies along with the date and amount of their most recent premium payment.

[Assistant]
SELECT p.policy_id, p.policy_number, pp.payment_date AS most_recent_payment_date, pp.amount_paid AS most_recent_payment_amount
FROM insurance.policies p
JOIN LATERAL (
  SELECT payment_date, amount_paid
  FROM insurance.premium_payments
  WHERE policy_id = p.policy_id
  ORDER BY payment_date DESC
  LIMIT 1
) pp ON TRUE;

[User] Actually, only show policies where the most recent payment was made in 2024.

[Assistant]
SELECT p.policy_id, p.policy_number, pp.payment_date AS most_recent_payment_date, pp.amount_paid AS most_recent_payment_amount
FROM insurance.policies p
JOIN LATERAL (
  SELECT payment_date, amount_paid
  FROM insurance.premium_payments
  WHERE policy_id = p.policy_id
  ORDER BY payment_date DESC
  LIMIT 1
) pp ON TRUE
WHERE EXTRACT(YEAR FROM pp.payment_date) = 2024;

[User] List all transactions that include an event with the name 'Transfer', showing the transaction ID, the event name, and the transaction's value.

[Assistant] SELECT t.transaction_id, e.event_name, t.value FROM web3.transactions AS t JOIN web3.events AS e ON t.transaction_id = e.transaction_id WHERE e.event_name = 'Transfer';

[User] How many distinct addresses achieved a realized_ratio higher than 0.9 last month?

[Assistant] SELECT COUNT(DISTINCT address) FROM smart_money_profit WHERE realized_ratio > 0.9;

[User] Can you also break down the count by chain?

[Assistant] SELECT chain, COUNT(DISTINCT address) AS address_count FROM smart_money_profit WHERE realized_ratio > 0.9 GROUP BY chain;

[User] I want to list pairs of games published by the same publisher but on different platforms. Include both game titles, their platforms, and the publisher_id.

[Assistant]
SELECT g1.publisher_id, g1.title AS title1, g1.platform AS platform1, g2.title AS title2, g2.platform AS platform2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.platform <> g2.platform;

[User] Exclude games released before 2020. Only pair games from 2020 onwards.

[Assistant]
SELECT g1.publisher_id, g1.title AS title1, g1.platform AS platform1, g2.title AS title2, g2.platform AS platform2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.platform <> g2.platform
WHERE g1.release_date >= '2020-01-01' AND g2.release_date >= '2020-01-01';

[User] List the name and location ID for all locations where the postal code is missing.

[Assistant] SELECT name, location_id FROM transportation.locations WHERE postal_code IS NULL;

[User] Also include the city and order the results by city ascending.

[Assistant] SELECT name, location_id, city FROM transportation.locations WHERE postal_code IS NULL ORDER BY city ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
##Table Structure
CREATE TABLE 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 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 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)
)
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, 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.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
##Table Structure
CREATE TABLE financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)

[User] Which department has the highest number of employees currently employed?

[Assistant] SELECT department FROM government_services.employees WHERE termination_date IS NULL GROUP BY department ORDER BY COUNT(*) DESC LIMIT 1;

[User] List each patient and the total number of chronic diagnoses they have received, as well as the number of distinct doctors who have made those diagnoses.

[Assistant] SELECT patient_id, COUNT(*) AS chronic_diagnoses_count, COUNT(DISTINCT doctor_id) AS distinct_doctors FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY patient_id;

[User] Only include patients who have received diagnoses recorded as 'Active' status.

[Assistant] SELECT patient_id, COUNT(*) AS chronic_diagnoses_count, COUNT(DISTINCT doctor_id) AS distinct_doctors FROM healthcare.diagnoses WHERE is_chronic = TRUE AND status = 'Active' GROUP BY patient_id;

[User] List each doctor and how many prescriptions they have written, sorted by the highest count first.

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

[User] Calculate the average quantity for orders based on their status.

[Assistant] SELECT status, AVG(quantity) FROM trading_platform.orders GROUP BY status;

[User] List each citizen's first and last name along with the first and last name of another citizen who shares the same last name. Show each pair only once.

[Assistant]
SELECT c1.first_name || ' ' || c1.last_name AS citizen_name,
       c2.first_name || ' ' || c2.last_name AS other_citizen_name
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.last_name = c2.last_name
 AND c1.citizen_id < c2.citizen_id;

[User] Show me the total principal amount for each loan type, along with the count of loans and average monthly payment, but only for loans originated in the last 5 years.

[Assistant] SELECT loan_type, SUM(principal_amount) AS total_principal, COUNT(loan_id) AS loan_count, AVG(monthly_payment) AS avg_monthly_payment FROM financial_services.loans WHERE origination_date >= CURRENT_DATE - INTERVAL '5 years' GROUP BY loan_type;

[User] Find all policies that were cancelled due to 'Non-payment'. Show the policy number, cancellation date, and premium amount for these policies.

[Assistant] SELECT policy_number ,  cancellation_date ,  premium_amount FROM insurance.policies WHERE status = 'Cancelled' AND cancellation_reason = 'Non-payment'


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.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)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
##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 )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE 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.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )

[User] Retrieve the most recent log entry for each user, including action and logged_at.

[Assistant]
SELECT l1.user_id,
       l1.action,
       l1.logged_at
FROM trading_platform.logs l1
WHERE l1.logged_at = (
  SELECT MAX(l2.logged_at)
  FROM trading_platform.logs l2
  WHERE l2.user_id = l1.user_id
);

[User] What is the average number of appointments assigned per employee for each job title?

[Assistant] SELECT e.job_title, CAST(COUNT(a.appointment_id) AS REAL) / COUNT(DISTINCT e.employee_id) AS average_appointments_per_employee FROM government_services.employees e LEFT JOIN government_services.appointments a ON e.employee_id = a.employee_id GROUP BY e.job_title;

[User] Provide a count of diagnoses for each status, grouped by the code type.

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

[User] Filter this result to only show code types where the total number of diagnoses across all statuses for that code type is greater than 50.

[Assistant] SELECT code_type, status, COUNT(*) FROM healthcare.diagnoses GROUP BY code_type, status HAVING code_type IN (SELECT code_type FROM healthcare.diagnoses GROUP BY code_type HAVING COUNT(*) > 50);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text PRIMARY KEY, 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 text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, 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 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 web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id text PRIMARY KEY, from_address text, to_address text, value numeric, gas_used int, gas_price numeric, block_number int, timestamp timestamp, input_data text, status text, nonce int )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id.text, token_id.text, from_address.text, to_address.text, value.numeric, transaction_id.text, log_index.integer )
CREATE TABLE web3.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE web3.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
##Table Structure
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] List all token transfers with a value greater than 1000000. Show transfer ID, token ID, from address, to address, and value.

[Assistant]
SELECT
  transfer_id,
  token_id,
  from_address,
  to_address,
  value
FROM web3.token_transfers
WHERE
  value > 1000000;

[User] Now, only show transfers for token ID '0xabc...xyz'.

[Assistant]
SELECT
  transfer_id,
  token_id,
  from_address,
  to_address,
  value
FROM web3.token_transfers
WHERE
  value > 1000000
  AND token_id = '0xabc...xyz';

[User] Find all patients who have never received any diagnoses. Show patient ID, first_name, and last_name.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name
FROM healthcare.patients p
LEFT JOIN healthcare.diagnoses d
  ON p.patient_id = d.patient_id
WHERE d.diagnosis_id IS NULL;

[User] Only include those who have had at least one appointment.

[Assistant]
SELECT DISTINCT p.patient_id,
                p.first_name,
                p.last_name
FROM healthcare.patients p
JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
LEFT JOIN healthcare.diagnoses d
  ON p.patient_id = d.patient_id
WHERE d.diagnosis_id IS NULL;

[User] List all room types with their type name, base rate, and the name of the property they belong to.

[Assistant]
SELECT rt.room_type_id, rt.type_name, rt.base_rate, p.property_name
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id;

[User] Find all failed transactions along with the token transfers involved in those transactions, showing the transaction details and token information.

[Assistant] SELECT t.transaction_id, t.from_address, t.to_address, t.status, tt.transfer_id, tt.token_id, tt.value, tk.token_name, tk.token_symbol FROM web3.transactions t JOIN web3.token_transfers tt ON t.transaction_id = tt.transaction_id JOIN web3.tokens tk ON tt.token_id = tk.token_id WHERE t.status = 'failed';

[User] Which citizens have submitted more than two applications? Provide their full name and the total number of applications.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name,
       COUNT(*) AS application_count
FROM government_services.citizens c
JOIN government_services.applications a
  ON c.citizen_id = a.citizen_id
GROUP BY c.citizen_id, c.first_name, c.last_name
HAVING COUNT(*) > 2;

[User] Find all currently employed staff whose managers are no longer employed. Show the employee's full name, hire date, the manager's full name, and the manager's termination_date.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, e.hire_date, m.first_name || ' ' || m.last_name AS manager_name, m.termination_date FROM government_services.employees e JOIN government_services.employees m ON e.manager_employee_id = m.employee_id WHERE e.termination_date IS NULL AND m.termination_date IS NOT NULL;

[User] How many distinct relationships are listed for policy beneficiaries?

[Assistant] SELECT COUNT(DISTINCT relationship) FROM insurance.policy_beneficiaries;


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 blockchain.nodes ( node_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (node_id) )
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.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 text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
##Table Structure
CREATE TABLE 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 web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )

[User] List each port along with the count of distinct IP addresses observed on that port.

[Assistant] SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count FROM blockchain.nodes GROUP BY port;

[User] Only include ports that have more than 3 unique IP addresses.

[Assistant] SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count FROM blockchain.nodes GROUP BY port HAVING COUNT(DISTINCT ip_address) > 3;

[User] Also include the latest last_seen timestamp for each of these ports.

[Assistant] SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count, MAX(last_seen) AS last_seen_latest FROM blockchain.nodes GROUP BY port HAVING COUNT(DISTINCT ip_address) > 3;

[User] List the name and symbol for all assets that do not have a corresponding entry with the key 'website' in the metadata table.

[Assistant] SELECT T1.name , T1.symbol FROM trading_platform.assets AS T1 LEFT JOIN trading_platform.metadata AS T2 ON T1.asset_id  =  T2.asset_id AND T2.key  =  'website' WHERE T2.metadata_id IS NULL

[User] Count the number of followers for each user and show those users who have more than 100 followers, ordering by follower_count descending.

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

[User] List all pairs of hashtags that were created on the same date. Show both tag names and the creation date.

[Assistant]
SELECT a.tag_name AS tag1, b.tag_name AS tag2, a.created_at::date AS created_date
FROM social_media.hashtags a
JOIN social_media.hashtags b
  ON a.created_at::date = b.created_at::date
  AND a.hashtag_id < b.hashtag_id;

[User] Actually, only include pairs where both tag names start with the letter 'S'.

[Assistant]
SELECT a.tag_name AS tag1, b.tag_name AS tag2, a.created_at::date AS created_date
FROM social_media.hashtags a
JOIN social_media.hashtags b
  ON a.created_at::date = b.created_at::date
  AND a.hashtag_id < b.hashtag_id
WHERE a.tag_name LIKE 'S%'
  AND b.tag_name LIKE 'S%';

[User] Find all pairs of tokens that have the same contract_address but different token_symbols. Show both token_ids, each token's symbol, and the shared contract_address.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)
##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)
)

[User] Count the number of posts that have a media URL but no textual content.

[Assistant] SELECT COUNT(*) FROM social_media.posts AS T1 WHERE T1.media_url IS NOT NULL AND (T1.content IS NULL OR T1.content = '');

[User] For each distinct deployer address, how many contracts have they deployed and what is the most recent deployment time? Please show deployer_address, contract_count, and latest_deployed_at.

[Assistant]
SELECT deployer_address, COUNT(*) AS contract_count, MAX(deployed_at) AS latest_deployed_at
FROM web3.contracts
GROUP BY deployer_address;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
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 gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
##Table Structure
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
##Table Structure
CREATE TABLE 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) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_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.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.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 )

[User] List all notifications of type 'like' where the target_entity_type is 'post'. For each notification, return notification_id, sender_user_id, target_entity_id (as post_id), and the notification creation time.

[Assistant]
SELECT notification_id, sender_user_id, target_entity_id AS post_id, created_at
FROM social_media.notifications
WHERE notification_type = 'like'
  AND target_entity_type = 'post';

[User] Also include the content of the liked post in the result.

[Assistant]
SELECT n.notification_id,
       n.sender_user_id,
       n.target_entity_id AS post_id,
       p.content,
       n.created_at
FROM social_media.notifications n
JOIN social_media.posts p
  ON p.post_id = n.target_entity_id
WHERE n.notification_type = 'like'
  AND n.target_entity_type = 'post';

[User] Find all pairs of developers in the same country but founded in different years. Show each developer's name, their founded_year, and the shared country.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.country, d1.founded_year AS founded1, d2.founded_year AS founded2
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
  AND d1.developer_id < d2.developer_id
  AND d1.founded_year <> d2.founded_year;

[User] Now show only those pairs where the difference in their founded_year is at least 10 years.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.country, d1.founded_year AS founded1, d2.founded_year AS founded2, ABS(d1.founded_year - d2.founded_year) AS year_diff
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
  AND d1.developer_id < d2.developer_id
WHERE ABS(d1.founded_year - d2.founded_year) >= 10;

[User] Show me the total number of appointments grouped by each unique duration in minutes. Include only durations with more than 5 appointments.

[Assistant]
SELECT duration_minutes, COUNT(*) AS appointment_count
FROM healthcare.appointments
GROUP BY duration_minutes
HAVING COUNT(*) > 5;

[User] Can you also show, for each of these durations, the earliest and latest appointment_time?

[Assistant]
SELECT duration_minutes, COUNT(*) AS appointment_count,
       MIN(appointment_time) AS earliest_appointment,
       MAX(appointment_time) AS latest_appointment
FROM healthcare.appointments
GROUP BY duration_minutes
HAVING COUNT(*) > 5;

[User] For each chain, show the total number of smart money addresses and the count of addresses with positive profit.

[Assistant] SELECT chain, COUNT(address) AS total_addresses, COUNT(CASE WHEN profit > 0 THEN address END) AS positive_profit_addresses FROM smart_money_profit GROUP BY chain

[User] Filter the results to only include chains where the total number of addresses is greater than 100. Also, include the percentage of addresses with positive profit for each chain.

[Assistant] SELECT chain, COUNT(address) AS total_addresses, COUNT(CASE WHEN profit > 0 THEN address END) AS positive_profit_addresses, CAST(COUNT(CASE WHEN profit > 0 THEN address END) AS REAL) * 100 / COUNT(address) AS positive_profit_percentage FROM smart_money_profit GROUP BY chain HAVING COUNT(address) > 100

[User] Show me all case numbers along with the firm_name of the law firm where the lead lawyer is the managing partner.

[Assistant]
SELECT c.case_number, l.firm_name
FROM legal_services.cases c
JOIN legal_services.law_firms l
  ON c.lead_lawyer_id = l.managing_partner_id;

[User] Now only include cases with status 'Closed' and show the date_closed as well.

[Assistant]
SELECT c.case_number, l.firm_name, c.date_closed
FROM legal_services.cases c
JOIN legal_services.law_firms l
  ON c.lead_lawyer_id = l.managing_partner_id
WHERE c.status = 'Closed';

[User] For each property in the 'USA' country, list the property name and the total count of services that cost more than 50.

[Assistant] SELECT T1.property_name, COUNT(T2.service_id) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.services AS T2 ON T1.property_id = T2.property_id WHERE T1.country_code = 'USA' AND T2.price > 50 GROUP BY T1.property_name;