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.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.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
##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.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 )
##Table Structure
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
##Table Structure
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid, player_id uuid, item_id uuid, quantity integer, acquired_at timestamp with time zone, instance_data jsonb )
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
##Table Structure
CREATE TABLE 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 )
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )
##Table Structure
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )

[User] List all unique peer ports that have been used at least once in the system.

[Assistant] SELECT DISTINCT port FROM trading_platform.peers ORDER BY port ASC;

[User] List pairs of smoking and non-smoking rooms on the same floor for each property, showing the property_id, floor, smoking room_number, and non_smoking room_number.

[Assistant]
SELECT r1.property_id,
       r1.floor,
       r1.room_number AS smoking_room,
       r2.room_number AS non_smoking_room
FROM hospitality_technology.rooms r1
JOIN hospitality_technology.rooms r2
  ON r1.property_id = r2.property_id
 AND r1.floor = r2.floor
 AND r1.is_smoking = TRUE
 AND r2.is_smoking = FALSE;

[User] Find cases where an address received tokens in one transfer and then sent tokens in another. List the receive transfer_id, the send transfer_id, the address, and both transfer values.

[Assistant]
SELECT recv.transfer_id AS receive_transfer_id,
       send.transfer_id AS send_transfer_id,
       recv.to_address AS address,
       recv.value       AS received_value,
       send.value       AS sent_value
FROM web3.token_transfers recv
JOIN web3.token_transfers send
  ON recv.to_address = send.from_address;

[User] Can you give me the total number of appointments grouped by status?

[Assistant]
SELECT status,
       COUNT(*) AS total_appointments
FROM healthcare.appointments
GROUP BY status;

[User] Filter the result to show only statuses with more than 50 appointments.

[Assistant]
SELECT status,
       COUNT(*) AS total_appointments
FROM healthcare.appointments
GROUP BY status
HAVING COUNT(*) > 50;

[User] List all trips for routes of type 'Express', showing the trip ID and route number.

[Assistant] SELECT T.trip_id, R.route_number FROM transportation.trips AS T JOIN transportation.routes AS R ON T.route_id = R.route_id WHERE R.type = 'Express';

[User] Show me all unique player IDs who have at least one item in their inventory with a quantity greater than 10.

[Assistant] SELECT DISTINCT player_id FROM gaming_technology.player_inventory WHERE quantity > 10;

[User] Which rooms on the 4th floor are non-smoking, along with their property IDs and type IDs?

[Assistant] SELECT room_id, property_id, room_number, room_type_id FROM hospitality_technology.rooms WHERE floor = 4 AND is_smoking = FALSE;

[User] Count the number of medical records created for each doctor, and list the doctor_id alongside their record count.

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

[User] Show me the subject and start times of all appointments along with the corresponding lawyer IDs for each client.

[Assistant] SELECT client_id, lawyer_id, subject, start_time FROM legal_services.appointments;

[User] For each employee who has verified documents, show their full name and the total number of documents they have verified with a status of 'Verified'.

[Assistant] SELECT e.full_name, COUNT(d.document_id) FROM government_services.documents d JOIN employees e ON d.verified_by_employee_id = e.employee_id WHERE d.verification_status = 'Verified' GROUP BY e.full_name;

[User] Can you list the names of agencies that do not have a parent agency assigned, ordered by their established date?

[Assistant]
SELECT agency_id, agency_name, established_date
FROM government_services.agencies
WHERE parent_agency_id IS NULL
ORDER BY established_date;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id varchar NOT NULL, status varchar NOT NULL, collection_type varchar NOT NULL, package_id varchar NOT NULL, previous_transaction varchar NOT NULL, display varchar NOT NULL, owner varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )

[User] List all wallet addresses holding NFTs for contract address '0xabcdef...'. Show the wallet address and amount held.

[Assistant] SELECT wallet_address, amount, token_id FROM nft_holders WHERE contract_address = '0xabcdef...';

[User] For these holders, include the token ID, NFT name, and rarity score.

[Assistant] SELECT nh.wallet_address, nh.amount, nh.token_id, nm.name, nm.rarity_score FROM nft_holders nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_address = '0xabcdef...';

[User] Only show NFTs with a rarity score above 80 and wallets holding more than 1 unit. Order by rarity score descending.

[Assistant] SELECT nh.wallet_address, nh.amount, nh.token_id, nm.name, nm.rarity_score FROM nft_holders nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_address = '0xabcdef...' AND nm.rarity_score > 80 AND CAST(nh.amount AS INTEGER) > 1 ORDER BY nm.rarity_score 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 gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )
##Table Structure
CREATE TABLE 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 )
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
##Table Structure
CREATE TABLE 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 insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
##Table Structure
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
##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.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.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 )

[User] For each player, show the player_id and the count of inventory items they acquired with a quantity greater than 1.

[Assistant] SELECT player_id, COUNT(inventory_id) AS items_qty_gt_1_count FROM gaming_technology.player_inventory WHERE quantity > 1 GROUP BY player_id;

[User] List all pairs of citizens who registered on the same date. Include each citizen's full name and the shared registration date.

[Assistant]
SELECT c1.first_name || ' ' || c1.last_name AS full_name_1,
       c2.first_name || ' ' || c2.last_name AS full_name_2,
       DATE(c1.registration_date) AS registration_date
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON DATE(c1.registration_date) = DATE(c2.registration_date)
  AND c1.citizen_id < c2.citizen_id;

[User] How many beneficiaries are there for each relationship type in the policy_beneficiaries table?

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

[User] For each payment, list its payment_id, guest_id, payment_timestamp, and the next payment_id and next payment_timestamp made by the same guest.

[Assistant]
SELECT p.payment_id,
       p.guest_id,
       p.payment_timestamp,
       n.payment_id AS next_payment_id,
       n.payment_timestamp AS next_payment_timestamp
FROM hospitality_technology.payments p
LEFT JOIN hospitality_technology.payments n
  ON p.guest_id = n.guest_id
 AND n.payment_timestamp = (
       SELECT MIN(payment_timestamp)
       FROM hospitality_technology.payments
       WHERE guest_id = p.guest_id
         AND payment_timestamp > p.payment_timestamp
     );

[User] List all agents who have been terminated, showing their full name, agency name, and termination date.

[Assistant]
SELECT first_name, last_name, agency_name, termination_date
FROM insurance.agents
WHERE status <> 'Active';

[User] Find application IDs that have received notifications with both a 'Sent' status and a 'Failed' status.

[Assistant] SELECT application_id FROM government_services.notifications WHERE status IN ('Sent', 'Failed') GROUP BY application_id HAVING COUNT(DISTINCT status) = 2;

[User] List all wallet addresses that have the same private key as another wallet, showing the wallet_id, address, and the shared private_key.

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

[User] List the first name, last name, license number, and status for all drivers whose license expires in the next 6 months.

[Assistant]
SELECT
  first_name,
  last_name,
  license_number,
  status
FROM transportation.drivers
WHERE
  license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '6 month'
ORDER BY
  license_expiry_date;

[User] Now, count how many drivers from that list have an 'Active' status.

[Assistant]
SELECT
  COUNT(*)
FROM transportation.drivers
WHERE
  license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '6 month' AND status = 'Active';

[User] How many posts have been updated after they were created?

[Assistant]
SELECT COUNT(*) AS updated_post_count
FROM social_media.posts
WHERE updated_at IS NOT NULL AND updated_at > created_at;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )
##Table Structure
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, 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 )
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
##Table Structure
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
##Table Structure
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )
##Table Structure
CREATE TABLE government_services.payments ( payment_id.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
##Table Structure
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
##Table Structure
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
##Table Structure
CREATE TABLE 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)
)
##Table Structure
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )

[User] For each payment method, show the total number of completed payments and the total amount paid.

[Assistant] SELECT payment_method, COUNT(*) AS completed_count, SUM(amount) AS total_paid FROM government_services.payments WHERE status = 'Completed' GROUP BY payment_method;

[User] List all users with private profiles who have disabled push notifications, including their user_id and email_notifications_enabled status.

[Assistant]
SELECT user_id,
       email_notifications_enabled
FROM social_media.user_settings
WHERE private_profile = true
  AND push_notifications_enabled = false;

[User] List the application ID, submitted date, and assigned employee ID for all applications that are currently in 'Processing' status and were submitted before January 1st, 2024.

[Assistant] SELECT application_id, submitted_at, assigned_employee_id FROM government_services.applications WHERE status = 'Processing' AND submitted_at < '2024-01-01';

[User] List the usernames and countries for players who are located in a country where at least one developer is also registered.

[Assistant] SELECT username, country_code FROM gaming_technology.players WHERE country_code IN (SELECT country FROM gaming_technology.developers);

[User] Find the service locations that are not accessible and located in the state of 'California'. List their name, address, and city.

[Assistant] SELECT location_name ,  address ,  city FROM government_services.service_locations WHERE is_accessible = false AND state = 'California'

[User] List all pairs of users who registered within one day of each other, including their user IDs, usernames, and the difference in registration time.

[Assistant] SELECT u1.user_id AS user_id_1, u1.username AS username_1, u2.user_id AS user_id_2, u2.username AS username_2, ABS(EXTRACT(EPOCH FROM (u1.created_at - u2.created_at))/3600) AS hours_difference FROM web3.users u1 JOIN web3.users u2 ON u1.user_id < u2.user_id AND ABS(u1.created_at - u2.created_at) <= INTERVAL '1 day';

[User] How many projects raised funds in 2023?

[Assistant]
SELECT COUNT(*) AS project_count
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%';

[User] Also provide the average investment_value for these projects.

[Assistant]
SELECT COUNT(*) AS project_count, AVG(investment_value) AS avg_investment
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%';

[User] For each service ID, show the average and maximum payment amount for payments made in the last 90 days.

[Assistant] SELECT service_id, AVG(amount), MAX(amount) FROM government_services.payments WHERE payment_timestamp >= NOW() - INTERVAL '90 days' GROUP BY service_id;

[User] Count the number of group conversations created after '2024-05-01'.

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE is_group_chat = true AND created_at > '2024-05-01'

[User] List all time entries that do not have a description, including the entry ID, date worked, hours spent, and the first and last name of the lawyer who recorded the entry.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.description IS NULL OR te.description = '';

[User] Count the number of comments that have been updated since they were first created.

[Assistant] SELECT COUNT(*) FROM social_media.comments WHERE updated_at > created_at;

[User] Show the top 5 narratives by 24h volume, displaying narrative and volume_24h.

[Assistant] SELECT narrative, volume_24h FROM narrative_info ORDER BY volume_24h DESC LIMIT 5;

[User] How many unique patients have been diagnosed with code_type 'ICD-10'?

[Assistant] SELECT COUNT(DISTINCT patient_id) FROM healthcare.diagnoses WHERE code_type = 'ICD-10';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.notifications (
    notification_id 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)
)
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )
##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.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )
##Table Structure
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id text, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )
##Table Structure
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##Table Structure
CREATE TABLE 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] How many unread notifications are there with the type 'mention'?

[Assistant] SELECT COUNT(*) FROM social_media.notifications WHERE read_at IS NULL AND notification_type = 'mention';

[User] List all documents, including their name and upload timestamp, along with the first and last name of the client associated with the case they belong to.

[Assistant] SELECT d.document_name, d.upload_timestamp, c.first_name AS client_first_name, c.last_name AS client_last_name FROM documents AS d JOIN cases AS cs ON d.case_id = cs.case_id JOIN clients AS c ON cs.client_id = c.client_id;

[User] How many hashtags were created in each month of 2024?

[Assistant]
SELECT date_trunc('month', created_at) AS month, COUNT(*) AS count
FROM social_media.hashtags
WHERE created_at >= '2024-01-01'
  AND created_at < '2025-01-01'
GROUP BY month
ORDER BY month;

[User] List all pairs of wallets that were created within 10 minutes of each other, showing both wallet IDs, the user_id, and both creation timestamps.

[Assistant]
SELECT
  w1.wallet_id AS wallet1_id,
  w2.wallet_id AS wallet2_id,
  w1.user_id,
  w1.created_at AS created_at1,
  w2.created_at AS created_at2
FROM web3.wallets w1
JOIN web3.wallets w2
  ON w1.user_id = w2.user_id
  AND w1.wallet_id < w2.wallet_id
  AND ABS(EXTRACT(EPOCH FROM (w1.created_at - w2.created_at))) <= 600;

[User] What is the average ROI for all smart money addresses on the Binance chain?

[Assistant] SELECT AVG(roi) FROM smart_money_profit WHERE chain = 'Binance';

[User] Find any two claims made by the same customer on the same day. Return customer_id, the two claim IDs, and the incident date.

[Assistant]
SELECT c1.customer_id,
       c1.claim_id AS claim1_id,
       c2.claim_id AS claim2_id,
       DATE(c1.incident_date) AS incident_date
FROM insurance.claims c1
JOIN insurance.claims c2
  ON c1.customer_id = c2.customer_id
 AND DATE(c1.incident_date) = DATE(c2.incident_date)
 AND c1.claim_id < c2.claim_id;

[User] Show me all appointments with their subjects and the names of the lawyers who handled them.

[Assistant]
SELECT a.appointment_id, a.subject, l.first_name, l.last_name
FROM legal_services.appointments a
JOIN legal_services.lawyers l ON a.lawyer_id = l.lawyer_id;

[User] How many time entries were recorded on each date? List the date and the count of entries for that date, ordered by date.

[Assistant] SELECT date_worked, COUNT(*) AS entry_count FROM legal_services.time_entries GROUP BY date_worked ORDER BY date_worked;

[User] For each patient, show the total number of diagnoses they have received, along with their patient ID and the ID of their latest diagnosis. Join with the diagnoses table.

[Assistant]
SELECT patient_id, COUNT(diagnosis_id) AS diagnosis_count, MAX(diagnosis_id) AS latest_diagnosis_id
FROM healthcare.diagnoses
GROUP BY patient_id;

[User] List the patient_id and policy_number for all policies belonging to patients who have more than one insurance policy record in the system.

[Assistant] SELECT DISTINCT T1.patient_id, T1.policy_number FROM healthcare.patient_insurance AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.patient_id = T2.patient_id WHERE T1.patient_insurance_id <> T2.patient_insurance_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.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 )
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.trades ( trade_id text, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
##Table Structure
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
##Table Structure
// db.createCollection('stations')
// Optional: Add unique index: db.stations.createIndex({ station_id: 1 }, { unique: true })
{
  _id: ObjectId(), // Auto-generated MongoDB ID
  station_id: "station_xyz", // String (unique identifier, corresponds to SQL PK)
  station_name: "Grand Central Terminal", // String
  city: "New York", // String
  state_province: "NY", // String
  country_code: "USA", // String
  address: "89 E 42nd St, New York, NY 10017", // String
  timezone: "America/New_York", // String
  number_of_platforms: 44, // Int32
  created_at: ISODate("2023-01-15T10:00:00Z"), // Date
  last_updated_at: ISODate("2023-10-28T15:30:00Z") // Date
}
// db.createCollection('trains')
// Optional: db.trains.createIndex({ train_id: 1 }, { unique: true })
// Optional: db.trains.createIndex({ train_number: 1 }, { unique: true })
{
  _id: ObjectId(),
  train_id: "train_789", // String (unique)
  train_number: "Acela 2151", // String (unique)
  model: "Siemens Velaro", // String
  manufacturer: "Siemens", // String
  year_manufactured: 2010, // Int32
  capacity: 304, // Int32
  status: "Active", // String ('Active', 'Maintenance', 'Retired')
  last_maintenance_date: ISODate("2023-09-15"), // Date (Date part only relevant)
  next_maintenance_date: ISODate("2024-03-15") // Date (Date part only relevant)
}
// db.createCollection('bookings')
// Optional: db.bookings.createIndex({ booking_id: 1 }, { unique: true })
// Optional: db.bookings.createIndex({ passenger_id: 1 })
// Optional: db.bookings.createIndex({ schedule_id: 1 })
{
  _id: ObjectId(),
  booking_id: "book_zyx", // String (unique)
  passenger_id: "pass_pqr", // String (references passengers.passenger_id)
  schedule_id: "sched_1122", // String (references schedules.schedule_id)
  booking_datetime: ISODate("2024-04-15T14:30:00Z"), // Date
  status: "Confirmed", // String ('Confirmed', 'Cancelled', 'Pending')
  total_price: 150.75, // Decimal128 or Double
  currency_code: "USD", // String
  special_requests: "Wheelchair assistance required at origin" // String
}
// db.createCollection('staff')
// Optional: db.staff.createIndex({ staff_id: 1 }, { unique: true })
// Optional: db.staff.createIndex({ employee_number: 1 }, { unique: true })
// Optional: db.staff.createIndex({ contact_email: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  staff_id: "staff_mno", // String (unique)
  first_name: "Bob", // String
  last_name: "Jones", // String
  role: "Conductor", // String
  primary_station_id: null, // String (references stations.station_id, nullable)
  employee_number: "E12345", // String (unique)
  hire_date: ISODate("2018-06-01"), // Date
  contact_email: "bob.jones@example-rail.com", // String (unique, sparse)
  contact_phone: "+15559876543", // String
  is_active: true // Boolean
}
##Table Structure
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, 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.hashtags ( hashtag_id text PRIMARY KEY, tag_name text, created_at timestamp )

[User] For each claim, show the corresponding product_type of the insurance product for the related policy.

[Assistant]
SELECT cl.claim_id, ip.product_type
FROM insurance.claims cl
JOIN insurance.policies p ON cl.policy_id = p.policy_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id;

[User] Sorry, there is no policies table, I got an error. Can you try joining claims to insurance_products another way?

[Assistant]
-- Unable to join directly since there is no 'policies' table connecting claims to insurance_products. If policy_id equals product_id, you may try:
SELECT claim_id, policy_id, product_type
FROM insurance.claims
JOIN insurance.insurance_products ON claims.policy_id = insurance_products.product_id;

[User] For each account status, what is the total quantity of securities traded?

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

[User] For each vehicle, find the vehicle acquired immediately before it in the same depot. Show current vehicle_id, acquisition_date, previous_vehicle_id, and previous_acquisition_date.

[Assistant]
SELECT v.vehicle_id,
       v.acquisition_date,
       prev.vehicle_id AS previous_vehicle_id,
       prev.acquisition_date AS previous_acquisition_date
FROM transportation.vehicles v
LEFT JOIN transportation.vehicles prev
  ON v.depot_id = prev.depot_id
  AND prev.acquisition_date = (
    SELECT MAX(acquisition_date)
    FROM transportation.vehicles
    WHERE depot_id = v.depot_id
      AND acquisition_date < v.acquisition_date
  );

[User] Which five license states have the highest count of active agents? Return the license_state and agent_count.

[Assistant]
SELECT license_state,
       COUNT(*) AS agent_count
FROM insurance.agents
WHERE status = 'Active'
GROUP BY license_state
ORDER BY agent_count DESC
LIMIT 5;

[User] Can you help me count the total number of active staff members in the database?

[Assistant] db.staff.countDocuments({ is_active: true });

[User] Count the number of posts that have received at least one comment.

[Assistant] SELECT COUNT(DISTINCT post_id) FROM social_media.comments


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.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 trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.trades ( trade_id.text, order_id.text, buyer_id.text, seller_id.text, asset_id.text, quantity.numeric, price.numeric, traded_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp )
##Table Structure
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
##Table Structure
CREATE TABLE 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) )
##Table Structure
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
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 )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id.text, policy_id.text, customer_id.text, first_name.text, last_name.text, relationship.text, percentage_share.numeric, contact_info.text, added_at.timestamp )
##Table Structure
CREATE TABLE 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 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) )

[User] For each user, find the previous user by registration time. List current user_id and username, previous user_id and username, and the time difference in minutes between their registrations.

[Assistant]
SELECT u.user_id AS current_user_id,
       u.username AS current_username,
       p.user_id AS previous_user_id,
       p.username AS previous_username,
       EXTRACT(EPOCH FROM (u.created_at - p.created_at)) / 60 AS diff_minutes
FROM web3.users u
JOIN web3.users p
  ON p.created_at = (
    SELECT MAX(created_at)
    FROM web3.users
    WHERE created_at < u.created_at
  )
ORDER BY u.created_at;

[User] List all unspent UTXOs with an amount greater than 10.

[Assistant] SELECT utxo_id, transaction_id, address, amount FROM utxos WHERE spent = FALSE AND amount > 10;

[User] Find for each category the service with the highest standard_fee and the service with the lowest standard_fee. Display the category, highest_fee_service, and lowest_fee_service.

[Assistant]
SELECT m.category,
       s_max.service_name AS highest_fee_service,
       s_min.service_name AS lowest_fee_service
FROM (
  SELECT category,
         MAX(standard_fee) AS max_fee,
         MIN(standard_fee) AS min_fee
  FROM government_services.services
  GROUP BY category
) m
JOIN government_services.services s_max
  ON s_max.category = m.category
  AND s_max.standard_fee = m.max_fee
JOIN government_services.services s_min
  ON s_min.category = m.category
  AND s_min.standard_fee = m.min_fee;

[User] Get all pairs of locations in the same city, showing both location IDs, names, and the shared city.

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

[User] List the names of manufacturers that produce at least one medication with a description and at least one medication without a description.

[Assistant] SELECT DISTINCT manufacturer FROM healthcare.medications m1 WHERE manufacturer IS NOT NULL AND EXISTS (SELECT 1 FROM healthcare.medications m2 WHERE m2.manufacturer = m1.manufacturer AND m2.description IS NOT NULL) AND EXISTS (SELECT 1 FROM healthcare.medications m3 WHERE m3.manufacturer = m1.manufacturer AND m3.description IS NULL);

[User] Find parent agencies and the number of direct child agencies they have. List the parent agency name and the count of their children.

[Assistant] SELECT T1.agency_name, COUNT(T2.agency_id) FROM government_services.agencies AS T1 JOIN government_services.agencies AS T2 ON T1.agency_id = T2.parent_agency_id GROUP BY T1.agency_name ORDER BY COUNT(T2.agency_id) DESC;

[User] Count the number of claim documents for each distinct MIME type.

[Assistant] SELECT mime_type, COUNT(*) FROM insurance.claim_documents GROUP BY mime_type

[User] Which employees share the same department with at least one other employee? Please show the employee ID, full name, and department.

[Assistant]
SELECT e1.employee_id, e1.first_name || ' ' || e1.last_name AS full_name, e1.department
FROM government_services.employees e1
WHERE e1.department IS NOT NULL AND EXISTS (
    SELECT 1 FROM government_services.employees e2
    WHERE e2.department = e1.department AND e2.employee_id <> e1.employee_id
);

[User] Find all pairs of node IDs that share the same IP address but operate on different ports.

[Assistant] SELECT a.node_id AS node1, b.node_id AS node2, a.ip_address, a.port AS port1, b.port AS port2 FROM blockchain.nodes a JOIN blockchain.nodes b ON a.ip_address = b.ip_address AND a.node_id < b.node_id AND a.port <> b.port;


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.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id.text, policy_id.text, customer_id.text, first_name.text, last_name.text, relationship.text, percentage_share.numeric, contact_info.text, added_at.timestamp )
##Table Structure
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.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.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )
##Table Structure
CREATE TABLE blockchain.wallets ( wallet_id.text, user_id.text, address_id.text, private_key.text )
##Table Structure
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
##Table Structure
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )

[User] Count the number of documents for each unique document type.

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

[User] For each relationship type among policy beneficiaries, show the average percentage_share and the count of unique beneficiaries. Please order the results with the highest average percentage_share first.

[Assistant]
SELECT relationship, AVG(percentage_share) AS avg_percentage_share, COUNT(DISTINCT beneficiary_id) AS beneficiary_count
FROM insurance.policy_beneficiaries
GROUP BY relationship
ORDER BY avg_percentage_share DESC;

[User] Find pairs of users who have different usernames but share the same username length. List both user IDs, usernames, and the shared username length.

[Assistant] SELECT u1.user_id, u1.username AS user1_username, u2.user_id, u2.username AS user2_username, LENGTH(u1.username) AS username_length FROM web3.users u1 JOIN web3.users u2 ON LENGTH(u1.username) = LENGTH(u2.username) AND u1.user_id < u2.user_id WHERE u1.username <> u2.username;

[User] List all DApps along with the number of metadata entries linked to each, even if the DApp has no linked metadata.

[Assistant]
SELECT d.name, d.url, COUNT(m.metadata_id) AS metadata_count
FROM trading_platform.dapps d
LEFT JOIN trading_platform.metadata m ON d.dapp_id = m.asset_id
GROUP BY d.dapp_id, d.name, d.url;

[User] Calculate the total number of drivers for each status.

[Assistant]
SELECT status,
       COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status;

[User] Now only include statuses with more than 10 drivers.

[Assistant]
SELECT status,
       COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) > 10;

[User] Show the IDs and registration dates of all verified citizens who could be eligible for at least one active service. Display the citizen ID and registration date.

[Assistant]
SELECT DISTINCT c.citizen_id, c.registration_date
FROM government_services.citizens c
JOIN government_services.services s ON s.is_active = true
WHERE c.is_verified = true;

[User] What is the total number of wallets recorded?

[Assistant] SELECT COUNT(*) FROM web3.wallets;

[User] Can you show me the number of wallets created on each distinct date?

[Assistant] SELECT DATE(created_at), COUNT(*) FROM web3.wallets GROUP BY DATE(created_at);

[User] Find the total number of distinct lawyers and distinct documents in the database.

[Assistant] SELECT (SELECT COUNT(DISTINCT lawyer_id) FROM legal_services.lawyers) AS distinct_lawyer_count, (SELECT COUNT(DISTINCT document_id) FROM legal_services.documents) AS distinct_document_count;

[User] Show me all wallet addresses that belong to user_id 'U12345'.

[Assistant] SELECT address_id FROM blockchain.wallets WHERE user_id = 'U12345';

[User] Now join this with another table to show the private_key for these addresses.

[Assistant] SELECT w.address_id, w.private_key FROM blockchain.wallets w WHERE w.user_id = 'U12345';

[User] List the full names of citizens who have uploaded documents with a verification status of 'Pending' and the type of document they uploaded.

[Assistant] SELECT T1.first_name, T1.last_name, T2.document_type FROM government_services.citizens AS T1 JOIN government_services.documents AS T2 ON T1.citizen_id = T2.citizen_id WHERE T2.verification_status = 'Pending';

[User] List the location name and contact phone number for all service locations situated in the city of 'New York'.

[Assistant] SELECT location_name, contact_phone FROM government_services.service_locations WHERE city = 'New York';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
##Table Structure
CREATE TABLE insurance.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 healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.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.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##Table Structure
CREATE TABLE social_media.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
Use Hashes. Key pattern: 'inv:<inventory_record_id>'. Example: HSET inv:INVREC500 component_id "component:WINGBOLT" quantity 5000 location_warehouse "WH3" batch_number "BCH778899" ... Consider Sorted Set by expiry date: ZADD component_expiry:<component_id> <expiry_timestamp> <inventory_record_id>.
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
##Table Structure
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
##Table Structure
CREATE TABLE social_media.users ( user_id.text, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )
##Table Structure
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )

[User] List all active products with a base premium exceeding 1500 that were created after January 1, 2023, including their product name, type, and base premium. Order the results by creation date ascending.

[Assistant] SELECT product_name, product_type, base_premium FROM insurance.insurance_products WHERE is_active = TRUE AND base_premium > 1500 AND created_at >= '2023-01-01' ORDER BY created_at ASC;

[User] What is the total amount paid and number of payments grouped by payment_method for payments between January 1, 2023 and December 31, 2023?

[Assistant]
SELECT payment_method,
       COUNT(*) AS payment_count,
       SUM(amount_paid) AS total_amount
FROM insurance.premium_payments
WHERE payment_date::date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY payment_method;

[User] Show me all insurance plans where the website includes 'secure'.

[Assistant] SELECT * FROM healthcare.insurance_plans WHERE website ILIKE '%secure%';

[User] How many likes have been received by public posts, grouped by media_type? Please show media_type and the count of likes for each.

[Assistant]
SELECT p.media_type,
       COUNT(l.like_id) AS like_count
FROM social_media.posts p
JOIN social_media.likes l
  ON p.post_id = l.post_id
WHERE p.visibility = 'public'
GROUP BY p.media_type
ORDER BY like_count DESC;

[User] Can you help me fetch the inventory records for components stored in a specific warehouse, along with their expiry dates?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Can you filter this to show only records for a specific component ID?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] What if I want to exclude records with quantities below a certain threshold, like 100?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES
# Note: Filtering by quantity would require additional scripting or client-side processing as Redis does not support direct filtering on hash field values.

[User] Can you also sort the results by expiry date in descending order?

[Assistant]
HGETALL inv:<inventory_record_id>
ZREVRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Provide the count of transfers for each token_id.

[Assistant]
SELECT token_id,
       COUNT(*) AS transfer_count
FROM web3.token_transfers
GROUP BY token_id;

[User] Actually, also include the total transferred value for each token_id.

[Assistant]
SELECT token_id,
       COUNT(*) AS transfer_count,
       SUM(value) AS total_transferred_value
FROM web3.token_transfers
GROUP BY token_id;

[User] List the names of service locations that have had more than 10 appointments with a status of 'Cancelled'.

[Assistant] SELECT T2.location_name FROM government_services.appointments AS T1 JOIN government_services.service_locations AS T2 ON T1.location_id = T2.location_id WHERE T1.status = 'Cancelled' GROUP BY T2.location_name HAVING count(T1.appointment_id) > 10

[User] How many users were registered in each month of 2024?

[Assistant]
SELECT date_trunc('month', created_at) AS month, COUNT(*) AS user_count
FROM social_media.users
WHERE created_at >= '2024-01-01'
  AND created_at < '2025-01-01'
GROUP BY month
ORDER BY month;

[User] List the number of cases for each case type that are currently marked as 'Open'.

[Assistant] SELECT case_type, COUNT(*) FROM legal_services.cases WHERE status = 'Open' GROUP BY case_type;

[User] Show all wallet addresses together with the private key, sorted from the most recent to oldest creation date.

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

[User] Actually, could you also include the user_id for each wallet in the result?

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

[User] Show all appointments that have 'follow-up' mentioned in the notes field.

[Assistant] SELECT * FROM healthcare.appointments WHERE notes LIKE '%follow-up%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
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.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
##Table Structure
CREATE TABLE 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)
)
##Table Structure
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
##Table Structure
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )

[User] Provide a list of all log entries recorded since the start of 2024, including the user ID, action, and the exact time the log occurred.

[Assistant] SELECT user_id, action, logged_at FROM logs WHERE logged_at >= '2024-01-01';

[User] Find all staff members who are managers and list their direct reports. Show the manager's first name, last name, and the direct report's first name, last name, and position.

[Assistant] SELECT m.first_name AS manager_first_name, m.last_name AS manager_last_name, s.first_name AS report_first_name, s.last_name AS report_last_name, s.position AS report_position FROM hospitality_technology.staff s JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id WHERE m.position = 'Manager';

[User] How many users have their profile pictures set and also have written a bio?

[Assistant]
SELECT COUNT(*) AS user_count
FROM social_media.users
WHERE profile_picture_url IS NOT NULL AND profile_picture_url <> ''
  AND bio IS NOT NULL AND bio <> '';

[User] How many comments does each post have? Return post_id and comment_count for posts with more than 5 comments.

[Assistant]
SELECT post_id,
       COUNT(*) AS comment_count
FROM social_media.comments
GROUP BY post_id
HAVING COUNT(*) > 5;

[User] List all pairs of transactions within the same block where the from_address of one transaction is the to_address of another transaction. Show both transaction_ids, the block_number, from_address, and to_address.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.block_number, t1.from_address, t1.to_address
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.block_number = t2.block_number
  AND t1.from_address = t2.to_address
  AND t1.to_address = t2.from_address;

[User] How many hashtags are currently stored in the hashtags table?

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

[User] For each notification, list its notification_id, message_subject, and the message_subject of the notification it relates to (assuming related_entity_type = 'notification').

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id;

[User] Only include notifications with status = 'Sent'.

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id
WHERE n.status = 'Sent';

[User] How many lawyers who are partners were hired in each year? Show the hire year and the count.

[Assistant] SELECT strftime('%Y', hire_date) AS hire_year ,  count(lawyer_id) FROM legal_services.lawyers WHERE is_partner  =  true GROUP BY hire_year

[User] List the application_id and the number of notifications with status 'Pending' for each application.

[Assistant]
SELECT application_id, COUNT(*) AS pending_notification_count
FROM government_services.notifications
WHERE status = 'Pending'
GROUP BY application_id;

[User] Show all addresses that made their last trade in 2024, including their chain and profit.

[Assistant] SELECT address, chain, profit FROM smart_money_profit WHERE last_trade_time LIKE '2024%';


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.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.maintenance_logs ( log_id text, vehicle_id text, service_date date, odometer_reading integer, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )
##Table Structure
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)
##Table Structure
CREATE TABLE financial_services.loans ( loan_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL UNIQUE, loan_type character varying(50) NOT NULL, principal_amount numeric(19, 4) NOT NULL, current_principal_balance numeric(19, 4) NOT NULL, interest_rate numeric(6, 4) NOT NULL, term_months integer NOT NULL, origination_date date NOT NULL, maturity_date date NOT NULL, monthly_payment numeric(12, 4), collateral_description text, status character varying(32) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id) )
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
##Table Structure
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.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) )
##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 )
##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.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.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) )

[User] For each trip, can you show the trip_id, number of passengers, and the make and model of the assigned vehicle?

[Assistant]
SELECT b.trip_id, COUNT(b.passenger_id) AS passenger_count, v.make, v.model
FROM transportation.bookings b
JOIN transportation.vehicles v ON b.trip_id IN (
    SELECT DISTINCT trip_id FROM transportation.fuel_logs WHERE vehicle_id = v.vehicle_id
)
GROUP BY b.trip_id, v.make, v.model;

[User] Find pairs of users who registered on the same weekday but in different years. List the user ID and registration date for both users, and the weekday name.

[Assistant] SELECT u1.user_id, u1.created_at AS user1_created_at, u2.user_id, u2.created_at AS user2_created_at, TO_CHAR(u1.created_at, 'Day') AS registration_weekday FROM web3.users u1 JOIN web3.users u2 ON TO_CHAR(u1.created_at, 'Day') = TO_CHAR(u2.created_at, 'Day') AND EXTRACT(YEAR FROM u1.created_at) <> EXTRACT(YEAR FROM u2.created_at) AND u1.user_id < u2.user_id ORDER BY TO_CHAR(u1.created_at, 'D'), u1.created_at;

[User] Show me all patients who have non-primary insurance plans with expiration dates within the next 60 days, along with their policy numbers and subscriber names.

[Assistant] SELECT patient_id, policy_number, subscriber_name FROM healthcare.patient_insurance WHERE is_primary = false AND expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '60 days');

[User] List all auto loans (loan_id, principal_amount, interest_rate) where the current principal balance is less than 40% of the original principal amount, along with the account_id and the difference between principal_amount and current_principal_balance.

[Assistant] SELECT loan_id, principal_amount, interest_rate, account_id, (principal_amount - current_principal_balance) AS amount_paid FROM financial_services.loans WHERE loan_type = 'Auto' AND current_principal_balance < (0.4 * principal_amount);

[User] Show me each department in each property, along with the total number of available services and their combined price.

[Assistant] SELECT property_id, department, COUNT(*) AS service_count, SUM(price) AS total_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, department;

[User] I want to see the number of 'buy' and 'sell' orders for each asset, along with the asset_id.

[Assistant] SELECT asset_id, order_type, COUNT(*) AS order_count FROM trading_platform.orders GROUP BY asset_id, order_type;

[User] Can you also show the average price for 'buy' and 'sell' orders for each asset?

[Assistant] SELECT asset_id, order_type, COUNT(*) AS order_count, AVG(price) AS avg_price FROM trading_platform.orders GROUP BY asset_id, order_type;

[User] Find any two policies for the same customer whose coverage dates overlap. Return the customer ID, both policy numbers, and their start and end dates.

[Assistant]
SELECT p1.customer_id,
       p1.policy_number AS policy1_number,
       p1.start_date   AS policy1_start,
       p1.end_date     AS policy1_end,
       p2.policy_number AS policy2_number,
       p2.start_date   AS policy2_start,
       p2.end_date     AS policy2_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.policy_id   <  p2.policy_id
 AND p1.start_date  <= p2.end_date
 AND p2.start_date  <= p1.end_date;

[User] Count the number of assets for each asset type.

[Assistant] SELECT type, COUNT(*) FROM trading_platform.assets GROUP BY type;