System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.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 text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.wallets (
    wallet_id 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 web3.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
##Table Structure
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )

[User] List all hashtags that have been used on posts created in the last 90 days. Show the tag_name and the date it was first used on a post within this period.

[Assistant] SELECT h.tag_name, MIN(p.created_at) AS first_use_date_in_period FROM social_media.posts AS p JOIN social_media.post_hashtags AS ph ON p.post_id = ph.post_id JOIN social_media.hashtags AS h ON ph.hashtag_id = h.hashtag_id WHERE p.created_at >= NOW() - INTERVAL '90 days' GROUP BY h.hashtag_id, h.tag_name;

[User] List all peers with their IP addresses who have not been seen in the last 7 days.

[Assistant]
SELECT peer_id, ip_address, port, last_seen
FROM trading_platform.peers
WHERE last_seen < NOW() - INTERVAL '7 days';

[User] List the username and email of users whose first wallet creation date is the same day as their user registration date.

[Assistant] SELECT u.username, u.email FROM web3.users u JOIN (SELECT user_id, MIN(created_at) as first_wallet_created_at FROM web3.wallets GROUP BY user_id) w ON u.user_id = w.user_id WHERE DATE(u.created_at) = DATE(w.first_wallet_created_at);

[User] Find all cases that were closed in the year 2022, showing their case name, case number, and date closed.

[Assistant] SELECT case_name, case_number, date_closed FROM legal_services.cases WHERE date_closed >= '2022-01-01' AND date_closed < '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
##Table Structure
CREATE TABLE gaming_technology.in_game_items ( item_id.uuid, game_id.uuid, item_name.text, item_type.text, description.text, rarity.text, cost_currency.text, cost_amount.numeric, attributes.jsonb )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text PRIMARY KEY, case_number text UNIQUE, 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 PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )
##Table Structure
CREATE TABLE 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.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )
##Table Structure
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
##Table Structure
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )

[User] Which users have received both a comment notification and a like notification? List the recipient_user_id and the total number of such users.

[Assistant]
SELECT COUNT(DISTINCT recipient_user_id) AS user_count
FROM (
  SELECT recipient_user_id
  FROM social_media.notifications
  WHERE notification_type = 'comment'
  INTERSECT
  SELECT recipient_user_id
  FROM social_media.notifications
  WHERE notification_type = 'like'
) AS users_with_both;

[User] Find pairs of items from the same game, where one item is of type 'Weapon' and the other is of type 'Consumable'. List the game ID, the name of the weapon, and the name of the consumable.

[Assistant] SELECT i1.game_id, i1.item_name AS weapon_name, i2.item_name AS consumable_name FROM gaming_technology.in_game_items i1 JOIN gaming_technology.in_game_items i2 ON i1.game_id = i2.game_id WHERE i1.item_type = 'Weapon' AND i2.item_type = 'Consumable' AND i1.item_id != i2.item_id;

[User] List the case_number, case_name, and the total amount invoiced for each case.

[Assistant]
SELECT ca.case_number, ca.case_name, SUM(i.total_amount) AS total_invoiced
FROM legal_services.cases ca
LEFT JOIN legal_services.invoices i ON ca.case_id = i.case_id
GROUP BY ca.case_number, ca.case_name;

[User] List each hashtag_id along with the total number of distinct posts it's linked to.

[Assistant]
SELECT hashtag_id, COUNT(DISTINCT post_id) AS post_count
FROM social_media.post_hashtags
GROUP BY hashtag_id;

[User] Retrieve pairs of likes where the same user liked two different posts. For each pair, show user_id, p1.post_id AS first_post_id, p2.post_id AS second_post_id, and the time difference in minutes between the two likes.

[Assistant]
SELECT p1.user_id,
       p1.post_id AS first_post_id,
       p2.post_id AS second_post_id,
       ABS(EXTRACT(EPOCH FROM (p1.created_at - p2.created_at)))/60 AS minutes_diff
FROM social_media.likes p1
JOIN social_media.likes p2
  ON p1.user_id = p2.user_id
  AND p1.post_id <> p2.post_id;

[User] Only include pairs where the time difference is less than 30 minutes.

[Assistant]
SELECT p1.user_id,
       p1.post_id AS first_post_id,
       p2.post_id AS second_post_id,
       ABS(EXTRACT(EPOCH FROM (p1.created_at - p2.created_at)))/60 AS minutes_diff
FROM social_media.likes p1
JOIN social_media.likes p2
  ON p1.user_id = p2.user_id
  AND p1.post_id <> p2.post_id
WHERE ABS(EXTRACT(EPOCH FROM (p1.created_at - p2.created_at)))/60 < 30;

[User] Show me the conversation ID and creation time for all conversations that are not group chats and have a recorded last message time.

[Assistant] SELECT conversation_id, created_at FROM social_media.conversations WHERE is_group_chat = FALSE AND last_message_at IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.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 )
##Table Structure
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )
##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.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text PRIMARY KEY, post_id text, hashtag_id text )
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 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 )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )

[User] Find token transfers that correspond directly to an event log (same transaction and log index). List the transfer ID, value, and the event name.

[Assistant] SELECT T1.transfer_id, T1.value, T2.event_name FROM web3.token_transfers AS T1 JOIN web3.events AS T2 ON T1.transaction_id = T2.transaction_id AND T1.log_index = T2.log_index;

[User] Show all rooms that are on floor 3.

[Assistant] SELECT room_id, property_id, room_number FROM hospitality_technology.rooms WHERE floor = 3;

[User] For these rooms, include the property name and room number.

[Assistant] SELECT r.room_number, p.property_name FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id WHERE r.floor = 3;

[User] Also, include the type name and current status for each room.

[Assistant] SELECT r.room_number, p.property_name, rt.type_name, r.status FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id JOIN hospitality_technology.room_types AS rt ON r.room_type_id = rt.room_type_id AND r.property_id = rt.property_id WHERE r.floor = 3;

[User] Show all reviews made by guests along with the guest_id, guest's reservation_id, and the related property's property_id and review_date.

[Assistant]
SELECT r.review_id, r.guest_id, r.reservation_id, r.property_id, r.review_date
FROM hospitality_technology.reviews r
INNER JOIN hospitality_technology.reservations res ON r.reservation_id = res.reservation_id;

[User] Show me all users who have never commented on any post.

[Assistant]
SELECT u.user_id, u.username
FROM social_media.users u
LEFT JOIN social_media.comments c ON u.user_id = c.user_id
WHERE c.comment_id IS NULL;

[User] List all wallet addresses and the amount of any unspent UTXOs linked to that address.

[Assistant] SELECT T1.address, T2.amount FROM wallets AS T1 JOIN utxos AS T2 ON T1.address = T2.address WHERE T2.spent = false;

[User] For each user, show their user ID and the total amount of unspent UTXOs across all their wallets.

[Assistant] SELECT T1.user_id, SUM(T2.amount) FROM wallets AS T1 JOIN utxos AS T2 ON T1.address = T2.address WHERE T2.spent = false GROUP BY T1.user_id;

[User] How many unique hashtags has each post been associated with? Please return post_id and unique_hashtag_count.

[Assistant]
SELECT post_id, COUNT(DISTINCT hashtag_id) AS unique_hashtag_count
FROM social_media.post_hashtags
GROUP BY post_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 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 )
##Table Structure
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE 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 )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
##Table Structure
CREATE TABLE social_media.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) )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] List properties where actual check-in occurred later than the scheduled check-in date. Show the property ID and the count of such reservations.

[Assistant] SELECT property_id, COUNT(*) FROM reservations WHERE actual_check_in_ts > check_in_date GROUP BY property_id;

[User] Now, only show properties where the delay happened for more than 5 reservations.

[Assistant] SELECT property_id, COUNT(*) FROM reservations WHERE actual_check_in_ts > check_in_date GROUP BY property_id HAVING COUNT(*) > 5;

[User] Find all agents with their managers where the agent's commission rate is above 0.10.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.agent_id AS manager_id,
       m.first_name || ' ' || m.last_name AS manager_name
FROM insurance.agents a
JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.commission_rate > 0.1;

[User] Exclude any pairs where the manager is not currently active.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.agent_id AS manager_id,
       m.first_name || ' ' || m.last_name AS manager_name
FROM insurance.agents a
JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.commission_rate > 0.1
  AND m.status = 'active';

[User] I need a list showing each patient along with their current primary insurance policy number and their immediately previous primary policy number.

[Assistant]
SELECT ci.patient_id,
       ci.policy_number AS current_policy,
       pi.policy_number AS previous_policy
FROM healthcare.patient_insurance ci
LEFT JOIN healthcare.patient_insurance pi
  ON ci.patient_id = pi.patient_id
  AND pi.is_primary = TRUE
  AND pi.effective_date < ci.effective_date
WHERE ci.is_primary = TRUE
  AND (ci.expiration_date IS NULL OR ci.expiration_date > CURRENT_DATE)
  AND pi.effective_date = (
      SELECT MAX(pii.effective_date)
      FROM healthcare.patient_insurance pii
      WHERE pii.patient_id = ci.patient_id
        AND pii.is_primary = TRUE
        AND pii.effective_date < ci.effective_date
  );

[User] Actually, I only want to include previous policies that have an expiration_date set.

[Assistant]
SELECT ci.patient_id,
       ci.policy_number AS current_policy,
       pi.policy_number AS previous_policy
FROM healthcare.patient_insurance ci
LEFT JOIN healthcare.patient_insurance pi
  ON ci.patient_id = pi.patient_id
  AND pi.is_primary = TRUE
  AND pi.expiration_date IS NOT NULL
  AND pi.effective_date = (
      SELECT MAX(pii.effective_date)
      FROM healthcare.patient_insurance pii
      WHERE pii.patient_id = ci.patient_id
        AND pii.is_primary = TRUE
        AND pii.expiration_date IS NOT NULL
        AND pii.effective_date < ci.effective_date
  )
WHERE ci.is_primary = TRUE
  AND (ci.expiration_date IS NULL OR ci.expiration_date > CURRENT_DATE);

[User] Show me each guest's reservation count and average stay length in days.

[Assistant]
SELECT guest_id,
       COUNT(*) AS reservation_count,
       AVG(check_out_date - check_in_date) AS avg_stay_days
FROM hospitality_technology.reservations
GROUP BY guest_id;

[User] Filter to only include guests with more than 3 reservations.

[Assistant]
SELECT guest_id,
       COUNT(*) AS reservation_count,
       AVG(check_out_date - check_in_date) AS avg_stay_days
FROM hospitality_technology.reservations
GROUP BY guest_id
HAVING COUNT(*) > 3;

[User] Also join this with a subquery to display the total amount paid per guest.

[Assistant]
SELECT s.guest_id,
       s.reservation_count,
       s.avg_stay_days,
       p.total_amount_paid
FROM (
  SELECT guest_id,
         COUNT(*) AS reservation_count,
         AVG(check_out_date - check_in_date) AS avg_stay_days
  FROM hospitality_technology.reservations
  GROUP BY guest_id
  HAVING COUNT(*) > 3
) s
JOIN (
  SELECT guest_id,
         SUM(amount_paid) AS total_amount_paid
  FROM hospitality_technology.reservations
  GROUP BY guest_id
) p
  ON s.guest_id = p.guest_id;

[User] List the full name (first name and last name) of all citizens who have uploaded documents whose expiry date is in the past.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name FROM government_services.citizens AS T1 INNER JOIN government_services.documents AS T2 ON T1.citizen_id = T2.citizen_id WHERE T2.expiry_date < CURRENT_DATE;

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

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

[User] List the medication IDs and names for all entries where the description is missing or empty.

[Assistant] SELECT medication_id, medication_name FROM healthcare.medications WHERE description IS NULL OR description = '';

[User] For those medications, please also show the manufacturer and sort the results by medication name in ascending order.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE description IS NULL OR description = '' ORDER BY medication_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 social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
##Table Structure
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.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 text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )
##Table Structure
CREATE TABLE 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.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] Find all hashtag IDs that have been used on the same posts as hashtag 'h1'.

[Assistant] SELECT DISTINCT ph2.hashtag_id FROM social_media.post_hashtags ph1 JOIN social_media.post_hashtags ph2 ON ph1.post_id = ph2.post_id WHERE ph1.hashtag_id = 'h1';

[User] Exclude the hashtag 'h1' itself from the results.

[Assistant] SELECT DISTINCT ph2.hashtag_id FROM social_media.post_hashtags ph1 JOIN social_media.post_hashtags ph2 ON ph1.post_id = ph2.post_id WHERE ph1.hashtag_id = 'h1' AND ph2.hashtag_id <> 'h1';

[User] Now only include those hashtags that have co-occurred with 'h1' at least twice.

[Assistant] SELECT ph2.hashtag_id, COUNT(*) AS co_occurrence_count FROM social_media.post_hashtags ph1 JOIN social_media.post_hashtags ph2 ON ph1.post_id = ph2.post_id WHERE ph1.hashtag_id = 'h1' AND ph2.hashtag_id <> 'h1' GROUP BY ph2.hashtag_id HAVING COUNT(*) >= 2;

[User] List the reference_number and status for all applications assigned to employee 'emp200', along with the submitted_at date of each application.

[Assistant] SELECT reference_number, status, submitted_at FROM government_services.applications WHERE assigned_employee_id = 'emp200';

[User] Show only those applications that have status 'Pending' and were submitted after January 1, 2024.

[Assistant] SELECT reference_number, status, submitted_at FROM government_services.applications WHERE assigned_employee_id = 'emp200' AND status = 'Pending' AND submitted_at > '2024-01-01';

[User] List the names of all insurance providers who offer at least one plan of type 'EPO'.

[Assistant]
SELECT DISTINCT insurance_provider
FROM healthcare.insurance_plans
WHERE plan_type = 'EPO';

[User] List all users who have never followed anyone, showing their username, full name, email, and account creation date.

[Assistant]
SELECT u.username,
       u.full_name,
       u.email,
       u.created_at
FROM social_media.users AS u
LEFT JOIN social_media.follows AS f
  ON u.user_id = f.follower_user_id
WHERE f.follow_id IS NULL;

[User] Show me a list pairing each medication name with the record_id of any medical record whose treatment_plan mentions that medication.

[Assistant]
SELECT m.medication_name, mr.record_id
FROM healthcare.medications m
JOIN healthcare.medical_records mr
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%';

[User] Also, include the medication's manufacturer and the record's doctor_id.

[Assistant]
SELECT m.medication_name, m.manufacturer, mr.record_id, mr.doctor_id
FROM healthcare.medications m
JOIN healthcare.medical_records mr
  ON mr.treatment_plan ILIKE '%' || m.medication_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 social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
##Table Structure
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id character varying(64) NOT NULL, follower_user_id character varying(64) NOT NULL, following_user_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (follow_id), CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )

[User] Show me the make and model of vehicles along with the route number and description for routes where the vehicle's capacity is 60 or less.

[Assistant]
SELECT v.make, v.model, r.route_number, r.description
FROM transportation.vehicles v
JOIN transportation.routes r ON v.depot_id IS NOT NULL
WHERE v.capacity <= 60;

[User] Include only the routes where the distance is greater than 100 kilometers, and sort by distance descending.

[Assistant]
SELECT v.make, v.model, r.route_number, r.description, r.distance_km
FROM transportation.vehicles v
JOIN transportation.routes r ON v.depot_id IS NOT NULL
WHERE v.capacity <= 60 AND r.distance_km > 100
ORDER BY r.distance_km DESC;

[User] Which five users have the most followers? Show the following_user_id and the number of followers each has.

[Assistant]
SELECT following_user_id, COUNT(follower_user_id) AS follower_count
FROM social_media.follows
GROUP BY following_user_id
ORDER BY follower_count DESC
LIMIT 5;

[User] List each insurance product's name and type, along with the number of active policies and the total premium_amount collected for those policies. Only include products that have at least one active policy.

[Assistant]
SELECT p.product_name,
       p.product_type,
       COUNT(pl.policy_id) AS active_policy_count,
       SUM(pl.premium_amount) AS total_premium
FROM insurance.insurance_products p
JOIN insurance.policies pl ON p.product_id = pl.product_id
WHERE pl.status = 'Active'
GROUP BY p.product_name, p.product_type
HAVING COUNT(pl.policy_id) > 0;

[User] Can you list the names of achievements and the length of their descriptions? Show the ones with the longest descriptions first.

[Assistant] SELECT name, LENGTH(description) AS description_length FROM achievements ORDER BY description_length DESC LIMIT 10;

[User] For these achievements, can you also show the title of the game they belong to?

[Assistant] SELECT a.name, LENGTH(a.description) AS description_length, g.name AS game_title FROM achievements AS a JOIN games AS g ON a.game_id = g.game_id ORDER BY description_length DESC LIMIT 10;

[User] Also, please only include achievements that are not hidden.

[Assistant] SELECT a.name, LENGTH(a.description) AS description_length, g.name AS game_title FROM achievements AS a JOIN games AS g ON a.game_id = g.game_id WHERE a.hidden = FALSE ORDER BY description_length DESC LIMIT 10;

[User] List pairs of token transfers within the same transaction and for the same token_id where the transfer values are different. Show the transaction ID, token ID, and both transfer IDs and their values.

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


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.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
##Table Structure
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
##Table Structure
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
##Table Structure
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )

[User] Show the invoice_id and total hours logged for each invoice.

[Assistant] SELECT invoice_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE invoice_id IS NOT NULL GROUP BY invoice_id;

[User] Only include invoices with more than 10 total hours.

[Assistant] SELECT invoice_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE invoice_id IS NOT NULL GROUP BY invoice_id HAVING SUM(hours_spent) > 10;

[User] Show the names and types of all assets whose symbol is exactly 3 characters long.

[Assistant] SELECT name, type, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3;

[User] Also, I want to order the results alphabetically by asset name.

[Assistant] SELECT name, type, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3 ORDER BY name ASC;

[User] Actually, can you only show assets of type 'token' in the result?

[Assistant] SELECT name, type, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3 AND type = 'token' ORDER BY name ASC;

[User] Now, just return the asset name and symbol for these tokens, sorted by symbol descending.

[Assistant] SELECT name, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3 AND type = 'token' ORDER BY symbol DESC;

[User] List all pairs of lawyers who share the same last name but have different first names. Show the first name, last name, and lawyer ID for both lawyers in each pair.

[Assistant] SELECT l1.first_name AS lawyer1_first_name, l1.last_name AS lawyer1_last_name, l1.lawyer_id AS lawyer1_id, l2.first_name AS lawyer2_first_name, l2.last_name AS lawyer2_last_name, l2.lawyer_id AS lawyer2_id FROM legal_services.lawyers AS l1 JOIN legal_services.lawyers AS l2 ON l1.last_name = l2.last_name AND l1.lawyer_id < l2.lawyer_id WHERE l1.first_name <> l2.first_name;

[User] For each staff member who delivered at least one service order, show their staff_id_delivered and the total revenue (sum of total_price) of orders they delivered.

[Assistant]
SELECT staff_id_delivered, SUM(total_price) AS total_revenue
FROM hospitality_technology.service_orders
WHERE staff_id_delivered IS NOT NULL
GROUP BY staff_id_delivered;

[User] Show me the product ID, name, and description for insurance products where the description contains the word 'policy'.

[Assistant] SELECT product_id, product_name, description FROM insurance.insurance_products WHERE description LIKE '%policy%';

[User] Add the product type and base premium to the output for these products.

[Assistant] SELECT product_id, product_name, description, product_type, base_premium FROM insurance.insurance_products WHERE description LIKE '%policy%';

[User] Show the top 5 contracts by number of events emitted, including contract_id and event_count.

[Assistant]
SELECT contract_id,
       COUNT(event_id) AS event_count
FROM web3.events
GROUP BY contract_id
ORDER BY event_count DESC
LIMIT 5;

[User] Actually, include the earliest and latest emitted_at timestamps for those contracts.

[Assistant]
SELECT contract_id,
       COUNT(event_id) AS event_count,
       MIN(emitted_at) AS first_event,
       MAX(emitted_at) AS last_event
FROM web3.events
GROUP BY contract_id
ORDER BY event_count DESC
LIMIT 5;

[User] Could you list each player and the title of the games for which they have acquired items?

[Assistant] SELECT DISTINCT pi.player_id, g.title FROM gaming_technology.player_inventory pi JOIN gaming_technology.games g ON pi.item_id = g.game_id;

[User] Filter this list to only include acquisitions made after January 1st, 2023.

[Assistant] SELECT DISTINCT pi.player_id, g.title FROM gaming_technology.player_inventory pi JOIN gaming_technology.games g ON pi.item_id = g.game_id WHERE pi.acquired_at >= '2023-01-01';

[User] For these player and game combinations, can you also show the total quantity of items they acquired for that specific game?

[Assistant] SELECT pi.player_id, g.title, SUM(pi.quantity) AS total_quantity_for_game FROM gaming_technology.player_inventory pi JOIN gaming_technology.games g ON pi.item_id = g.game_id WHERE pi.acquired_at >= '2023-01-01' GROUP BY pi.player_id, g.title;

[User] How many patients are there in each gender category?

[Assistant]
SELECT gender, COUNT(*) AS patient_count
FROM healthcare.patients
GROUP BY gender;

[User] Now only include genders with more than 100 patients.

[Assistant]
SELECT gender, COUNT(*) AS patient_count
FROM healthcare.patients
GROUP BY gender
HAVING COUNT(*) > 100;


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.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.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text PRIMARY KEY, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##Table Structure
CREATE TABLE 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) )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] Show me all pairs of routes where both routes have the same origin_location_id but different destination_location_id values. For each pair, display the first route's route_number, the second route's route_number, and their origin_location_id.

[Assistant]
SELECT r1.route_number AS first_route_number, r2.route_number AS second_route_number, r1.origin_location_id
FROM transportation.routes r1
JOIN transportation.routes r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id <> r2.route_id
  AND r1.destination_location_id <> r2.destination_location_id;

[User] Now, restrict this to only include pairs where the route type of both routes is 'Express', and order the result by first_route_number ascending.

[Assistant]
SELECT r1.route_number AS first_route_number, r2.route_number AS second_route_number, r1.origin_location_id
FROM transportation.routes r1
JOIN transportation.routes r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id <> r2.route_id
  AND r1.destination_location_id <> r2.destination_location_id
WHERE r1.type = 'Express' AND r2.type = 'Express'
ORDER BY first_route_number ASC;

[User] Show all law firms along with their phone numbers, sorted by the founding date from oldest to newest.

[Assistant]
SELECT firm_id, firm_name, phone, founded_date
FROM legal_services.law_firms
ORDER BY founded_date ASC;

[User] Actually, can you only include law firms that have a managing partner assigned?

[Assistant]
SELECT firm_id, firm_name, phone, founded_date
FROM legal_services.law_firms
WHERE managing_partner_id IS NOT NULL AND managing_partner_id <> ''
ORDER BY founded_date ASC;

[User] Also, show their website if available.

[Assistant]
SELECT firm_id, firm_name, phone, founded_date, website
FROM legal_services.law_firms
WHERE managing_partner_id IS NOT NULL AND managing_partner_id <> ''
ORDER BY founded_date ASC;

[User] Show the full names and contact emails of all citizens who have made a payment for an application that is currently in 'Pending' status.

[Assistant]
SELECT DISTINCT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.applications a ON p.application_id = a.application_id
WHERE a.status = 'Pending';

[User] Show me all insurance plans that have the word 'Managed' in their plan_name, including the plan_id, plan_name, and insurance_provider.

[Assistant]
SELECT plan_id, plan_name, insurance_provider
FROM healthcare.insurance_plans
WHERE plan_name ILIKE '%Managed%';

[User] Now, only include plans where the plan type is 'PPO'.

[Assistant]
SELECT plan_id, plan_name, insurance_provider
FROM healthcare.insurance_plans
WHERE plan_name ILIKE '%Managed%'
  AND plan_type = 'PPO';

[User] For each chain, show the total token_amount and usd_value for selling transactions (type=2).

[Assistant]
SELECT chain, SUM(token_amount) AS total_sold_amount, SUM(usd_value) AS total_sold_usd_value
FROM smart_money_token_inflow
WHERE type = 2
GROUP BY chain;

[User] Can you break down these results further by narrative as well?

[Assistant]
SELECT chain, narrative, SUM(token_amount) AS total_sold_amount, SUM(usd_value) AS total_sold_usd_value
FROM smart_money_token_inflow
WHERE type = 2
GROUP BY chain, narrative;

[User] Retrieve all pairs of medications that share the same generic_name but have different NDC codes. Show the first medication's ID, name, the second medication's ID, name, and the shared generic_name.

[Assistant] SELECT m1.medication_id AS med1_id, m1.medication_name AS med1_name, m2.medication_id AS med2_id, m2.medication_name AS med2_name, m1.generic_name FROM healthcare.medications m1 JOIN healthcare.medications m2 ON m1.generic_name = m2.generic_name AND m1.ndc_code <> m2.ndc_code WHERE m1.medication_id < m2.medication_id;