System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, 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 )

[User] Show me the first name, last name, and date of birth for all patients who are male.

[Assistant] SELECT first_name, last_name, date_of_birth FROM healthcare.patients WHERE gender = 'Male';

[User] Please also include their phone number, and sort the results by last name in ascending order.

[Assistant] SELECT first_name, last_name, date_of_birth, phone_number FROM healthcare.patients WHERE gender = 'Male' ORDER BY last_name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )

[User] List all guests who have made reservations for rooms located on floor 1 along with the property name and the room number.

[Assistant]
SELECT g.guest_id, g.first_name, g.last_name, r.property_id, ro.room_number
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
JOIN hospitality_technology.rooms ro ON r.room_id = ro.room_id
WHERE ro.floor = 1;

[User] Could you also include the type name of the room and filter to only show guests whose reservations are currently 'CheckedIn'?

[Assistant]
SELECT g.guest_id, g.first_name, g.last_name, r.property_id, ro.room_number, rt.type_name
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
JOIN hospitality_technology.rooms ro ON r.room_id = ro.room_id
JOIN hospitality_technology.room_types rt ON ro.room_type_id = rt.room_type_id
WHERE ro.floor = 1 AND r.status = 'CheckedIn';


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.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )

[User] List all beneficiaries who hold more than 25% of a policy, showing their beneficiary ID, full name, and contact information.

[Assistant]
SELECT beneficiary_id, first_name, last_name, contact_info
FROM insurance.policy_beneficiaries
WHERE percentage_share > 25;


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) )

[User] Can you show the total amount paid and number of payments per citizen in 2024?

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' GROUP BY citizen_id;

[User] Add a filter to only include payments with the status 'Succeeded'.

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' AND status = 'Succeeded' GROUP BY citizen_id;

[User] Now, only show those citizens who have paid more than 1000 in total.

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' AND status = 'Succeeded' GROUP BY citizen_id HAVING SUM(amount) > 1000;

[User] Show the result ordered by total_paid descending and limit to top 10 citizens.

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' AND status = 'Succeeded' GROUP BY citizen_id HAVING SUM(amount) > 1000 ORDER BY total_paid DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.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 )

[User] List the full name of patients who have prescriptions ending within the next 30 days, along with the medication ID and the prescription end date.

[Assistant] SELECT T1.first_name, T1.last_name, T2.medication_id, T2.end_date FROM healthcare.patients AS T1 INNER JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id WHERE T2.end_date IS NOT NULL AND T2.end_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days';

[User] Now, only include prescriptions where the quantity_dispensed is greater than 60.

[Assistant] SELECT T1.first_name, T1.last_name, T2.medication_id, T2.end_date FROM healthcare.patients AS T1 INNER JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id WHERE T2.end_date IS NOT NULL AND T2.end_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days' AND T2.quantity_dispensed > 60;

[User] Further filter these to only show patients whose first name starts with 'A'.

[Assistant] SELECT T1.first_name, T1.last_name, T2.medication_id, T2.end_date FROM healthcare.patients AS T1 INNER JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id WHERE T2.end_date IS NOT NULL AND T2.end_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days' AND T2.quantity_dispensed > 60 AND T1.first_name LIKE 'A%';

[User] Order the results by prescription end date ascending.

[Assistant] SELECT T1.first_name, T1.last_name, T2.medication_id, T2.end_date FROM healthcare.patients AS T1 INNER JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id WHERE T2.end_date IS NOT NULL AND T2.end_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days' AND T2.quantity_dispensed > 60 AND T1.first_name LIKE 'A%' ORDER BY T2.end_date ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )

[User] How many distinct tokens did smart money buy on the 'BSC' chain in 2023?

[Assistant]
SELECT COUNT(DISTINCT token_address) AS distinct_tokens_bought
FROM smart_money_token_inflow
WHERE type = 1
  AND chain = 'BSC'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') >= '2023-01-01'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') <= '2023-12-31';

[User] Can you break this down by narrative and show the count per narrative?

[Assistant]
SELECT narrative, COUNT(DISTINCT token_address) AS distinct_tokens_bought
FROM smart_money_token_inflow
WHERE type = 1
  AND chain = 'BSC'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') >= '2023-01-01'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') <= '2023-12-31'
GROUP BY narrative
ORDER BY distinct_tokens_bought 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 trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )

[User] List the names and symbols of all assets that have at least one associated metadata entry in the metadata table.

[Assistant] SELECT DISTINCT T1.name, T1.symbol FROM trading_platform.assets AS T1 JOIN trading_platform.metadata AS T2 ON T1.asset_id = T2.asset_id

[User] For these assets, also show the total count of metadata entries associated with each one.

[Assistant] SELECT T1.name, T1.symbol, COUNT(T2.metadata_id) AS metadata_count FROM trading_platform.assets AS T1 JOIN trading_platform.metadata AS T2 ON T1.asset_id = T2.asset_id GROUP BY T1.asset_id, T1.name, T1.symbol

[User] Now, filter the results to only show assets that have more than 2 metadata entries.

[Assistant] SELECT T1.name, T1.symbol, COUNT(T2.metadata_id) AS metadata_count FROM trading_platform.assets AS T1 JOIN trading_platform.metadata AS T2 ON T1.asset_id = T2.asset_id GROUP BY T1.asset_id, T1.name, T1.symbol HAVING COUNT(T2.metadata_id) > 2

[User] The previous query only shows assets with metadata. Please include *all* assets, showing 0 metadata entries for those that have none, and order the list by the metadata count in descending order.

[Assistant] SELECT T1.name, T1.symbol, COUNT(T2.metadata_id) AS metadata_count FROM trading_platform.assets AS T1 LEFT JOIN trading_platform.metadata AS T2 ON T1.asset_id = T2.asset_id GROUP BY T1.asset_id, T1.name, T1.symbol ORDER BY metadata_count DESC


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.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.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )

[User] Show me all conversations that have more than 10 messages, along with the group name and the usernames of their participants.

[Assistant]
SELECT c.conversation_id, c.group_name, u.username
FROM social_media.conversations c
JOIN social_media.messages m ON c.conversation_id = m.conversation_id
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
JOIN social_media.users u ON cp.user_id = u.user_id
GROUP BY c.conversation_id, c.group_name, u.username
HAVING COUNT(m.message_id) > 10;

[User] Instead, can you only show group chats where the group name contains 'Study' and list the time each participant joined?

[Assistant]
SELECT c.conversation_id, c.group_name, u.username, cp.joined_at
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
JOIN social_media.users u ON cp.user_id = u.user_id
WHERE c.is_group_chat = true AND c.group_name ILIKE '%Study%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )

[User] How many posts are marked with 'unlisted' visibility?

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.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 )

[User] List the latest version of each document (identified by case_id and document_name), showing the version number and its upload_timestamp.

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

[User] Actually, I also want to see the upload_timestamp of the previous version for each document.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version         AS latest_version,
       d_latest.upload_timestamp  AS latest_timestamp,
       d_prev.upload_timestamp    AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] Also, only include documents whose first version (version = 1) was uploaded in 2024.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version          AS latest_version,
       d_latest.upload_timestamp   AS latest_timestamp,
       d_prev.upload_timestamp     AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_first
  ON d_first.case_id = m.case_id
 AND d_first.document_name = m.document_name
 AND d_first.version = 1
 AND d_first.upload_timestamp >= '2024-01-01'
 AND d_first.upload_timestamp < '2025-01-01'
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] List patient pairs where the same patient has two distinct insurance plans. Show patient_id, the earlier plan_id as old_plan, the later plan_id as new_plan, and their effective dates.

[Assistant]
SELECT pi1.patient_id,
       pi1.plan_id AS old_plan,
       pi2.plan_id AS new_plan,
       pi1.effective_date AS old_effective_date,
       pi2.effective_date AS new_effective_date
FROM healthcare.patient_insurance pi1
JOIN healthcare.patient_insurance pi2
  ON pi1.patient_id = pi2.patient_id
 AND pi1.effective_date < pi2.effective_date;

[User] Now only include those changes where both policies are marked as primary.

[Assistant]
SELECT pi1.patient_id,
       pi1.plan_id AS old_plan,
       pi2.plan_id AS new_plan,
       pi1.effective_date AS old_effective_date,
       pi2.effective_date AS new_effective_date
FROM healthcare.patient_insurance pi1
JOIN healthcare.patient_insurance pi2
  ON pi1.patient_id = pi2.patient_id
 AND pi1.effective_date < pi2.effective_date
WHERE pi1.is_primary = TRUE
  AND pi2.is_primary = TRUE;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )
CREATE TABLE social_media.hashtags ( hashtag_id text PRIMARY KEY, tag_name text, created_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )

[User] I would like a list of unread notifications, showing the recipient's username, the sender's full name, the notification_type, and the creation timestamp.

[Assistant]
```sql
SELECT
  n.notification_id,
  recipient.username      AS recipient_username,
  sender.full_name        AS sender_full_name,
  n.notification_type,
  n.created_at
FROM social_media.notifications n
JOIN social_media.users recipient
  ON n.recipient_user_id = recipient.user_id
JOIN social_media.users sender
  ON n.sender_user_id = sender.user_id
WHERE n.read_at IS NULL;
```

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

[Assistant]
```sql
SELECT
  n.notification_id,
  recipient.username      AS recipient_username,
  sender.full_name        AS sender_full_name,
  n.notification_type,
  n.created_at
FROM social_media.notifications n
JOIN social_media.users recipient
  ON n.recipient_user_id = recipient.user_id
JOIN social_media.users sender
  ON n.sender_user_id = sender.user_id
WHERE n.read_at IS NULL
  AND n.created_at >= NOW() - INTERVAL '7 days';
```

[User] And exclude any notifications of type 'follow'.

[Assistant]
```sql
SELECT
  n.notification_id,
  recipient.username      AS recipient_username,
  sender.full_name        AS sender_full_name,
  n.notification_type,
  n.created_at
FROM social_media.notifications n
JOIN social_media.users recipient
  ON n.recipient_user_id = recipient.user_id
JOIN social_media.users sender
  ON n.sender_user_id = sender.user_id
WHERE n.read_at IS NULL
  AND n.created_at >= NOW() - INTERVAL '7 days'
  AND n.notification_type <> 'follow';
```

[User] Also, order the results by creation time descending.

[Assistant]
```sql
SELECT
  n.notification_id,
  recipient.username      AS recipient_username,
  sender.full_name        AS sender_full_name,
  n.notification_type,
  n.created_at
FROM social_media.notifications n
JOIN social_media.users recipient
  ON n.recipient_user_id = recipient.user_id
JOIN social_media.users sender
  ON n.sender_user_id = sender.user_id
WHERE n.read_at IS NULL
  AND n.created_at >= NOW() - INTERVAL '7 days'
  AND n.notification_type <> 'follow'
ORDER BY n.created_at DESC;
```


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )

[User] List all smart money addresses that have a negative PNL but a positive Realized Ratio. Show the address, chain, PNL, and Realized Ratio.

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < 0 AND realized_ratio > 0

[User] Can you refine the results to only include addresses where the absolute value of PNL is greater than 1000?

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < -1000 AND realized_ratio > 0


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text PRIMARY KEY, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

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

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


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.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)
CREATE TABLE transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

[User] Show all maintenance logs including the vehicle ID, service date, service type, and cost.

[Assistant] SELECT vehicle_id, service_date, service_type, cost FROM transportation.maintenance_logs;

[User] Only include records where the service type is 'Repair'.

[Assistant] SELECT vehicle_id, service_date, service_type, cost FROM transportation.maintenance_logs WHERE service_type = 'Repair';

[User] Also include the mechanic's name and only show logs from the year 2022.

[Assistant] SELECT vehicle_id, service_date, service_type, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Repair' AND service_date >= '2022-01-01' AND service_date < '2023-01-01';

[User] Actually, show logs from 2023 instead of 2022.

[Assistant] SELECT vehicle_id, service_date, service_type, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Repair' AND service_date >= '2023-01-01' AND service_date < '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts (
    contract_id character varying(64) NOT NULL,  -- unique identifier for the contract
    address character varying(128) NOT NULL, -- address of the deployed contract
    abi text NOT NULL, -- application binary interface of the contract
    bytecode text NOT NULL, -- bytecode of the contract
    deployer_address character varying(128) NOT NULL, -- address of the deployer
    deployed_at timestamp NOT NULL, -- time when the contract was deployed
    network_id character varying(64) NOT NULL, -- identifier of the network where the contract is deployed
    status character varying(32) NOT NULL, -- status of the contract (e.g., active, deprecated)
    PRIMARY KEY (contract_id)
)
CREATE TABLE web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)

[User] List each transaction ID that includes token transfers, along with the distinct symbols of the tokens transferred in that transaction.

[Assistant] SELECT T1.transaction_id, STRING_AGG(DISTINCT T3.token_symbol, ', ') FROM web3.transactions AS T1 JOIN web3.token_transfers AS T2 ON T1.transaction_id = T2.transaction_id JOIN web3.tokens AS T3 ON T2.token_id = T3.token_id GROUP BY T1.transaction_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 project_fundraising_record ( id character varying(32) NOT NULL, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, top_3_coins text, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, market_cap double precision, volume_24h double precision, trend_rank bigint, token_num bigint )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL, chain character varying(128) NOT NULL, address character varying(128) NOT NULL, exchange character varying(512) NOT NULL, token_address character varying(128) NOT NULL, token_symbol character varying(512), balance numeric(38,10), usd_value numeric(38,14), price double precision )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )

[User] Which projects had fundraising rounds named 'Series A' in 2022, and what are their token symbols and current token prices from DEX pools?

[Assistant]
SELECT p.project_name, p.rounds_name, d.token_symbol, d.price
FROM project_fundraising_record p
JOIN token_dexpool_info d ON LOWER(p.project_name) = LOWER(d.token_name)
WHERE p.rounds_name = 'Series A' AND p.investment_date LIKE '2022%';

[User] Can you also include the chain of each token and order the results by token price descending?

[Assistant]
SELECT p.project_name, p.rounds_name, d.token_symbol, d.chain, d.price
FROM project_fundraising_record p
JOIN token_dexpool_info d ON LOWER(p.project_name) = LOWER(d.token_name)
WHERE p.rounds_name = 'Series A' AND p.investment_date LIKE '2022%'
ORDER BY d.price DESC;

[User] I only want to see projects where the fundraising amount exceeded $10,000,000.

[Assistant]
SELECT p.project_name, p.rounds_name, d.token_symbol, d.chain, d.price
FROM project_fundraising_record p
JOIN token_dexpool_info d ON LOWER(p.project_name) = LOWER(d.token_name)
WHERE p.rounds_name = 'Series A' AND p.investment_date LIKE '2022%'
  AND p.investment_value > 10000000
ORDER BY d.price DESC;

[User] I got empty results, maybe the join with project_name and token_name is too strict. Can you try joining where either project_name equals token_name or project_name is contained in token_name, in a case-insensitive way?

[Assistant]
SELECT p.project_name, p.rounds_name, d.token_symbol, d.chain, d.price
FROM project_fundraising_record p
JOIN token_dexpool_info d
  ON LOWER(p.project_name) = LOWER(d.token_name)
    OR LOWER(d.token_name) LIKE CONCAT('%', LOWER(p.project_name), '%')
WHERE p.rounds_name = 'Series A' AND p.investment_date LIKE '2022%'
  AND p.investment_value > 10000000
ORDER BY d.price DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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)
)

[User] List the usernames of users who have commented on posts that are not replies to other comments.

[Assistant] SELECT DISTINCT T2.username FROM social_media.comments AS T1 JOIN social_media.users AS T2 ON T1.user_id = T2.user_id WHERE T1.parent_comment_id IS NULL;

[User] Can you filter this to only include users who have made more than one such comment?

[Assistant] SELECT T2.username FROM social_media.comments AS T1 JOIN social_media.users AS T2 ON T1.user_id = T2.user_id WHERE T1.parent_comment_id IS NULL GROUP BY T2.username HAVING COUNT(T1.comment_id) > 1;

[User] Also, show the total count of these top-level comments for each user and order the results by the count descending.

[Assistant] SELECT T2.username, COUNT(T1.comment_id) AS top_level_comment_count FROM social_media.comments AS T1 JOIN social_media.users AS T2 ON T1.user_id = T2.user_id WHERE T1.parent_comment_id IS NULL GROUP BY T2.username HAVING COUNT(T1.comment_id) > 1 ORDER BY top_level_comment_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )

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

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

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

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


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.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )

[User] How many distinct users have uploaded claim documents of type 'ACCIDENT_REPORT'?

[Assistant] SELECT COUNT(DISTINCT uploaded_by) FROM insurance.claim_documents WHERE document_type = 'ACCIDENT_REPORT';


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.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )

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

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


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.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) )

[User] I need a report showing the count of servers grouped by their status.

[Assistant]
SELECT status, COUNT(*) AS server_count
FROM gaming_technology.servers
GROUP BY status;

[User] Actually, can you also compute each status’s percentage share of the total servers?

[Assistant]
SELECT
  status,
  COUNT(*) AS server_count,
  ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (), 2) AS percentage
FROM gaming_technology.servers
GROUP BY status;

[User] Now filter out any statuses that represent less than 5% of all servers.

[Assistant]
SELECT
  status,
  server_count,
  percentage
FROM (
  SELECT
    status,
    COUNT(*) AS server_count,
    ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (), 2) AS percentage
  FROM gaming_technology.servers
  GROUP BY status
) sub
WHERE percentage >= 5;

[User] Finally, order the results by percentage in descending order.

[Assistant]
SELECT
  status,
  server_count,
  percentage
FROM (
  SELECT
    status,
    COUNT(*) AS server_count,
    ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (), 2) AS percentage
  FROM gaming_technology.servers
  GROUP BY status
) sub
WHERE percentage >= 5
ORDER BY percentage 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, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )

[User] List all players who have unlocked achievements in the last 7 days, showing their username and the number of achievements unlocked.

[Assistant]
SELECT p.username, COUNT(pa.achievement_id) AS unlocked_count
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE pa.unlocked_at >= NOW() - INTERVAL '7 days'
GROUP BY p.username;

[User] Also include the date of their most recent unlock as last_unlocked.

[Assistant]
SELECT p.username, COUNT(pa.achievement_id) AS unlocked_count, MAX(pa.unlocked_at) AS last_unlocked
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE pa.unlocked_at >= NOW() - INTERVAL '7 days'
GROUP BY p.username;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text, previous_block_id text, timestamp timestamp, nonce integer, merkle_root text, difficulty integer )

[User] Show me the block with the earliest timestamp and its corresponding previous block's difficulty level.

[Assistant]
SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty
FROM blockchain.blocks b1
LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id
ORDER BY b1.timestamp ASC
LIMIT 1;

[User] Now show me the same information but for the 5 earliest blocks instead of just one.

[Assistant]
SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty
FROM blockchain.blocks b1
LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id
ORDER BY b1.timestamp ASC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text, previous_block_id text, timestamp timestamp, nonce integer, merkle_root text, difficulty integer )
CREATE TABLE blockchain.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction
    sender_address character varying(128) NOT NULL, -- address of the sender
    receiver_address character varying(128) NOT NULL, -- address of the receiver
    amount numeric(38,14) NOT NULL, -- amount transferred
    timestamp timestamp NOT NULL, -- time when the transaction was created
    signature text NOT NULL, -- digital signature of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE blockchain.addresses ( address_id text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, PRIMARY KEY (user_id) )

[User] Show me the average transaction amount per block, along with the block timestamp.

[Assistant] SELECT b.block_id, b.timestamp as block_timestamp, AVG(t.amount) as avg_transaction_amount FROM blockchain.blocks b JOIN blockchain.transactions t ON b.block_id = t.block_id GROUP BY b.block_id, b.timestamp ORDER BY b.timestamp;

[User] Now filter this to only show blocks with more than 10 transactions.

[Assistant] SELECT b.block_id, b.timestamp as block_timestamp, AVG(t.amount) as avg_transaction_amount, COUNT(*) as transaction_count FROM blockchain.blocks b JOIN blockchain.transactions t ON b.block_id = t.block_id GROUP BY b.block_id, b.timestamp HAVING COUNT(*) > 10 ORDER BY b.timestamp;

[User] Can you also include the difficulty level of these blocks?

[Assistant] SELECT b.block_id, b.timestamp as block_timestamp, b.difficulty, AVG(t.amount) as avg_transaction_amount, COUNT(*) as transaction_count FROM blockchain.blocks b JOIN blockchain.transactions t ON b.block_id = t.block_id GROUP BY b.block_id, b.timestamp, b.difficulty HAVING COUNT(*) > 10 ORDER BY b.timestamp;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )

[User] Show me all room types with 'King' in the bed_type field, along with their property IDs and base rates.

[Assistant] SELECT room_type_id, property_id, type_name, bed_type, base_rate FROM hospitality_technology.room_types WHERE bed_type LIKE '%King%';

[User] Now, join this with the guests table to show only room types from properties where the guest's country code is 'USA' and the guest is a loyalty member.

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.type_name, rt.bed_type, rt.base_rate FROM hospitality_technology.room_types rt JOIN hospitality_technology.guests g ON rt.property_id = g.property_id WHERE rt.bed_type LIKE '%King%' AND g.country_code = 'USA' AND g.loyalty_member_id IS NOT NULL;

[User] The query is missing the max occupancy. Can you include that as well?

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.type_name, rt.bed_type, rt.base_rate, rt.max_occupancy FROM hospitality_technology.room_types rt JOIN hospitality_technology.guests g ON rt.property_id = g.property_id WHERE rt.bed_type LIKE '%King%' AND g.country_code = 'USA' AND g.loyalty_member_id IS NOT NULL;

[User] Actually, I need to see only room types with a base rate below $300, and order them by max occupancy in descending order.

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.type_name, rt.bed_type, rt.base_rate, rt.max_occupancy FROM hospitality_technology.room_types rt JOIN hospitality_technology.guests g ON rt.property_id = g.property_id WHERE rt.bed_type LIKE '%King%' AND g.country_code = 'USA' AND g.loyalty_member_id IS NOT NULL AND rt.base_rate < 300 ORDER BY rt.max_occupancy DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )

[User] List all appointments that took place at 'Central Office', showing appointment_id, client_id, and subject.

[Assistant] SELECT appointment_id, client_id, subject FROM legal_services.appointments WHERE location = 'Central Office';

[User] Actually, can you also include the lawyer_id in the results?

[Assistant] SELECT appointment_id, client_id, lawyer_id, subject FROM legal_services.appointments WHERE location = 'Central Office';

[User] Also, only show those appointments with status 'Completed'.

[Assistant] SELECT appointment_id, client_id, lawyer_id, subject FROM legal_services.appointments WHERE location = 'Central Office' AND status = 'Completed';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )

[User] For each location, count the total number of appointments scheduled. Show the location name and the count.

[Assistant] SELECT T2.location_name, COUNT(T1.appointment_id) FROM government_services.appointments AS T1 JOIN locations AS T2 ON T1.location_id = T2.location_id GROUP BY T2.location_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)

[User] List all rooms that are currently marked as 'OutOfOrder' or 'Maintenance'. Show their room number and current status.

[Assistant] SELECT room_number, status FROM hospitality_technology.rooms WHERE status IN ('OutOfOrder', 'Maintenance');

[User] Add the property ID and floor number for these rooms, and sort the results by property ID then floor.

[Assistant] SELECT property_id, floor, room_number, status FROM hospitality_technology.rooms WHERE status IN ('OutOfOrder', 'Maintenance') ORDER BY property_id, floor;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.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 )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )

[User] Which clients have at least one open case, and what are the names and numbers of those cases?

[Assistant]
SELECT c.first_name, c.last_name, cs.case_name, cs.case_number
FROM legal_services.clients c
JOIN legal_services.cases cs ON c.client_id = cs.client_id
WHERE cs.status = 'Open';


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.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )

[User] For each agency offering more than 5 active services, list the agency_name, jurisdiction_level, and the count of active services. Order the results by the count in descending order.

[Assistant]
SELECT a.agency_name,
       a.jurisdiction_level,
       COUNT(s.service_id) AS active_service_count
FROM government_services.agencies a
JOIN government_services.services s
  ON a.agency_id = s.agency_id
WHERE s.is_active = TRUE
GROUP BY a.agency_name, a.jurisdiction_level
HAVING COUNT(s.service_id) > 5
ORDER BY active_service_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )
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.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id 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 )

[User] Please provide each follow relationship, including the follower's username, the followed user's username, and the follow creation timestamp.

[Assistant]
SELECT
  u1.username AS follower_username,
  u2.username AS following_username,
  f.created_at AS follow_date
FROM
  social_media.follows f
  JOIN social_media.users u1 ON f.follower_user_id = u1.user_id
  JOIN social_media.users u2 ON f.following_user_id = u2.user_id;

[User] Actually, I only want follows from the last month and order by the follow date descending.

[Assistant]
SELECT
  u1.username AS follower_username,
  u2.username AS following_username,
  f.created_at AS follow_date
FROM
  social_media.follows f
  JOIN social_media.users u1 ON f.follower_user_id = u1.user_id
  JOIN social_media.users u2 ON f.following_user_id = u2.user_id
WHERE
  f.created_at >= now() - INTERVAL '1 month'
ORDER BY
  f.created_at DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )

[User] Find all pairs of token transfers where one transfer's sender and recipient are swapped with another transfer's sender and recipient, showing both transfer IDs.

[Assistant]
SELECT t1.from_address AS sender,
       t1.to_address   AS recipient,
       t1.transfer_id  AS transfer1_id,
       t2.transfer_id  AS transfer2_id
FROM web3.token_transfers t1
JOIN web3.token_transfers t2
  ON t1.from_address = t2.to_address
 AND t1.to_address   = t2.from_address
 AND t1.transfer_id < t2.transfer_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 manufacturing.components (
    component_id character varying(64) NOT NULL, -- unique identifier for the component
    part_number character varying(100) NOT NULL UNIQUE, -- manufacturer-specific part number
    component_name character varying(255) NOT NULL, -- descriptive name (e.g., Landing Gear Strut, Wing Spar)
    description text, -- detailed description
    material_id character varying(64), -- FK linking to the material used
    supplier_id character varying(64), -- FK linking to the supplier
    weight_kg numeric(10,3), -- weight of the component in kg
    cost_usd numeric(12,2), -- cost of the component in USD
    criticality_level character varying(20), -- e.g., 'High', 'Medium', 'Low'
    PRIMARY KEY (component_id)
)
CREATE TABLE manufacturing.materials (
    material_id character varying(64) NOT NULL,  -- unique identifier for the material
    material_name character varying(128) NOT NULL, -- common name (e.g., Titanium Alloy Grade 5, Carbon Fiber Prepreg)
    specification character varying(255), -- specification standard (e.g., AMS 4928)
    description text, -- detailed description of properties
    density_kg_m3 numeric(10, 4), -- density in kg per cubic meter
    tensile_strength_mpa integer, -- tensile strength in Megapascals
    PRIMARY KEY (material_id)
)
CREATE TABLE manufacturing.assembly_lines (
    line_id character varying(64) NOT NULL, -- unique identifier for the assembly line
    line_name character varying(128) NOT NULL, -- name of the line (e.g., Fuselage Assembly Line 1)
    location_building character varying(100), -- building where the line is located
    location_area character varying(100), -- specific area within the building
    aircraft_model_id character varying(64), -- FK to the primary aircraft model built on this line
    capacity_units_per_month integer, -- theoretical maximum output per month
    status character varying(50) NOT NULL, -- e.g., 'Active', 'Maintenance', 'Idle'
    PRIMARY KEY (line_id)
)
CREATE TABLE manufacturing.component_inventory (
    inventory_record_id character varying(64) NOT NULL, -- unique ID for this inventory record/batch
    component_id character varying(64) NOT NULL, -- FK to the component
    quantity integer NOT NULL, -- number of units of this component in stock for this batch
    location_warehouse character varying(100), -- warehouse identifier
    location_bin character varying(100), -- specific bin or shelf location
    received_date timestamp NOT NULL, -- when this batch was received
    expiry_date date, -- expiry date if applicable (e.g., for sealants, adhesives)
    batch_number character varying(100), -- supplier batch number
    last_updated timestamp NOT NULL, -- timestamp of the last update to this record
    PRIMARY KEY (inventory_record_id)
)

[User] 我想查询某个特定组件ID的详细信息，包括组件名称、材料名称、材料密度以及供应商ID，同时还需要知道该组件在哪个装配线上的飞机型号ID。

[Assistant]
SELECT c.component_id, c.component_name, m.material_name, m.density_kg_m3, c.supplier_id, al.aircraft_model_id
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
JOIN manufacturing.component_inventory ci ON c.component_id = ci.component_id
JOIN manufacturing.assembly_lines al ON ci.location_warehouse = al.location_building
WHERE c.component_id = 'specific_component_id';

[User] 如果我想只显示材料密度大于3000 kg/m3的记录，应该怎么修改？

[Assistant]
SELECT c.component_id, c.component_name, m.material_name, m.density_kg_m3, c.supplier_id, al.aircraft_model_id
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
JOIN manufacturing.component_inventory ci ON c.component_id = ci.component_id
JOIN manufacturing.assembly_lines al ON ci.location_warehouse = al.location_building
WHERE c.component_id = 'specific_component_id' AND m.density_kg_m3 > 3000;

[User] 能否再加上一个条件，只显示装配线状态为'Active'的记录？

[Assistant]
SELECT c.component_id, c.component_name, m.material_name, m.density_kg_m3, c.supplier_id, al.aircraft_model_id
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
JOIN manufacturing.component_inventory ci ON c.component_id = ci.component_id
JOIN manufacturing.assembly_lines al ON ci.location_warehouse = al.location_building
WHERE c.component_id = 'specific_component_id' AND m.density_kg_m3 > 3000 AND al.status = 'Active';

[User] 最后，请按材料密度从高到低对结果进行排序。

[Assistant]
SELECT c.component_id, c.component_name, m.material_name, m.density_kg_m3, c.supplier_id, al.aircraft_model_id
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
JOIN manufacturing.component_inventory ci ON c.component_id = ci.component_id
JOIN manufacturing.assembly_lines al ON ci.location_warehouse = al.location_building
WHERE c.component_id = 'specific_component_id' AND m.density_kg_m3 > 3000 AND al.status = 'Active'
ORDER BY m.density_kg_m3 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.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )

[User] List all pairs of achievements unlocked by the same player, showing player_id, achievement1, and achievement2.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS achievement1,
       pa2.achievement_id AS achievement2
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa1.unlocked_at < pa2.unlocked_at;

[User] Now include only pairs where the second achievement was unlocked within 7 days of the first.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS achievement1,
       pa2.achievement_id AS achievement2
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa1.unlocked_at < pa2.unlocked_at
 AND pa2.unlocked_at <= pa1.unlocked_at + INTERVAL '7 days';


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.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)

[User] Find all wallets that were created by users with IDs starting with 'user_' and show their addresses along with creation timestamps.

[Assistant] SELECT address, created_at FROM web3.wallets WHERE user_id LIKE 'user_%';


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 PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

[User] Provide a list of passengers including their passenger_id, first_name, last_name, phone_number, and the total number of bookings they have made. Sort the result by booking count in descending order.

[Assistant]
SELECT p.passenger_id,
       p.first_name,
       p.last_name,
       p.phone_number,
       COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id,
         p.first_name,
         p.last_name,
         p.phone_number
ORDER BY booking_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.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 )

[User] Show me all appointments that have both a non-null location and notes, along with their appointment_id, client_id, lawyer_id, and start_time.

[Assistant] SELECT appointment_id, client_id, lawyer_id, start_time FROM legal_services.appointments WHERE location IS NOT NULL AND notes IS NOT NULL;

[User] Can you only include those appointments where the status is 'Completed'?

[Assistant] SELECT appointment_id, client_id, lawyer_id, start_time FROM legal_services.appointments WHERE location IS NOT NULL AND notes IS NOT NULL AND status = 'Completed';

[User] Also, sort the results by start_time descending.

[Assistant] SELECT appointment_id, client_id, lawyer_id, start_time FROM legal_services.appointments WHERE location IS NOT NULL AND notes IS NOT NULL AND status = 'Completed' ORDER BY start_time DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- hashed social security number (or national ID)
    address text NOT NULL, -- customer's primary address
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL,
    email character varying(128) UNIQUE, -- customer's email address
    phone_number character varying(32),
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of customer record creation
    status character varying(32) NOT NULL, -- e.g., Active, Inactive, Pending Verification
    risk_profile character varying(50), -- e.g., Low, Medium, High
    PRIMARY KEY (customer_id)
)
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
CREATE TABLE financial_services.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    PRIMARY KEY (transaction_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id)
)
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)
CREATE TABLE financial_services.trades (
    trade_id character varying(64) NOT NULL, -- unique identifier for the trade
    account_id character varying(64) NOT NULL, -- investment account executing the trade
    security_id character varying(64) NOT NULL, -- security being traded
    order_id character varying(64), -- related order ID if applicable
    trade_type character varying(10) NOT NULL, -- 'Buy' or 'Sell'
    quantity numeric(19, 8) NOT NULL, -- number of units traded
    price_per_unit numeric(19, 8) NOT NULL, -- price per unit of the security
    total_amount numeric(19, 4) NOT NULL, -- total value of the trade (quantity * price)
    commission numeric(10, 4), -- commission fee charged for the trade
    trade_timestamp timestamp NOT NULL, -- exact time the trade was executed
    settlement_date date, -- date the trade settles
    status character varying(32) NOT NULL, -- e.g., Executed, Settled, Cancelled
    execution_venue character varying(100), -- where the trade was executed
    PRIMARY KEY (trade_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
CREATE TABLE financial_services.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
CREATE TABLE financial_services.loans (
    loan_id character varying(64) NOT NULL, -- unique identifier for the loan, could be same as account_id
    account_id character varying(64) NOT NULL UNIQUE, -- link to the general account record
    loan_type character varying(50) NOT NULL, -- e.g., Mortgage, Personal, Auto, Student
    principal_amount numeric(19, 4) NOT NULL, -- original loan amount
    current_principal_balance numeric(19, 4) NOT NULL, -- remaining principal
    interest_rate numeric(6, 4) NOT NULL, -- annual interest rate
    term_months integer NOT NULL, -- loan term in months
    origination_date date NOT NULL, -- date the loan was disbursed
    maturity_date date NOT NULL, -- date the loan is due to be fully repaid
    monthly_payment numeric(12, 4), -- scheduled monthly payment amount
    collateral_description text, -- description of collateral, if secured loan
    status character varying(32) NOT NULL, -- e.g., Active, Paid Off, Defaulted
    PRIMARY KEY (loan_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id)
)

[User] Show me all active accounts with a balance greater than 2000.

[Assistant]
SELECT account_id, account_number, customer_id, account_type, balance, currency
FROM financial_services.accounts
WHERE status = 'Open' AND balance > 2000;

[User] Add the opened date and last updated timestamp to the output, and order the result by balance descending.

[Assistant]
SELECT account_id, account_number, customer_id, account_type, balance, currency, opened_date, last_updated_at
FROM financial_services.accounts
WHERE status = 'Open' AND balance > 2000
ORDER BY balance DESC;

[User] I only want to see accounts opened in the last 12 months. Can you add that filter?

[Assistant]
SELECT account_id, account_number, customer_id, account_type, balance, currency, opened_date, last_updated_at
FROM financial_services.accounts
WHERE status = 'Open'
  AND balance > 2000
  AND opened_date >= CURRENT_DATE - INTERVAL '12 months'
ORDER BY balance DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.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 )

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

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