[User] List all claim documents of type 'POLICE_REPORT' uploaded in June 2024. Show document_id, claim_id, and file_name.

[Assistant]
SELECT document_id, claim_id, file_name
FROM insurance.claim_documents
WHERE document_type = 'POLICE_REPORT'
  AND uploaded_at >= '2024-06-01'::timestamp
  AND uploaded_at < '2024-07-01'::timestamp;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
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, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text PRIMARY KEY, previous_block_id text, timestamp timestamp, nonce int, merkle_root text, difficulty int )
CREATE TABLE blockchain.nodes ( node_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE blockchain.wallets ( wallet_id text PRIMARY KEY, user_id text, address_id text, private_key text )
CREATE TABLE blockchain.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE blockchain.smart_contracts ( contract_id character varying(64) NOT NULL, creator_address character varying(128) NOT NULL, code text NOT NULL, timestamp timestamp NOT NULL, PRIMARY KEY (contract_id) )

[User] Show me all smart contracts along with the email address of the user who owns the wallet corresponding to the contract's creator address.

[Assistant]
SELECT sc.contract_id, sc.creator_address, u.email
FROM blockchain.smart_contracts sc
JOIN blockchain.wallets w ON sc.creator_address = w.address_id
JOIN blockchain.users u ON w.user_id = u.user_id;

[User] Can you also include the contract deployment timestamp and the wallet_id?

[Assistant]
SELECT sc.contract_id, sc.creator_address, sc.timestamp, w.wallet_id, u.email
FROM blockchain.smart_contracts sc
JOIN blockchain.wallets w ON sc.creator_address = w.address_id
JOIN blockchain.users u ON w.user_id = u.user_id;

[User] Actually, only show contracts created after July 1st, 2023.

[Assistant]
SELECT sc.contract_id, sc.creator_address, sc.timestamp, w.wallet_id, u.email
FROM blockchain.smart_contracts sc
JOIN blockchain.wallets w ON sc.creator_address = w.address_id
JOIN blockchain.users u ON w.user_id = u.user_id
WHERE sc.timestamp > '2023-07-01';

[User] Sorry, I only want contracts where the user's email domain is 'gmail.com'.

[Assistant]
SELECT sc.contract_id, sc.creator_address, sc.timestamp, w.wallet_id, u.email
FROM blockchain.smart_contracts sc
JOIN blockchain.wallets w ON sc.creator_address = w.address_id
JOIN blockchain.users u ON w.user_id = u.user_id
WHERE sc.timestamp > '2023-07-01' AND u.email LIKE '%@gmail.com';


[User] Show me all policies that expired in the last 60 days, along with their product IDs and premium amounts.

[Assistant] SELECT policy_id, product_id, premium_amount, end_date FROM insurance.policies WHERE status = 'Expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days';

[User] Now include only policies that had a deductible of $1000 or more.

[Assistant] SELECT policy_id, product_id, premium_amount, deductible, end_date FROM insurance.policies WHERE status = 'Expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days' AND deductible >= 1000;

[User] I also want to see the count of such expired policies per product ID.

[Assistant] SELECT product_id, COUNT(policy_id) AS expired_policy_count FROM insurance.policies WHERE status = 'Expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days' AND deductible >= 1000 GROUP BY product_id;

[User] Finally, show me the average premium amount for these expired high-deductible policies grouped by product ID.

[Assistant] SELECT product_id, AVG(premium_amount) AS avg_premium FROM insurance.policies WHERE status = 'Expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days' AND deductible >= 1000 GROUP BY product_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)


[User] Show the first and last names of citizens who appear in both the appointments table and the payments table.

[Assistant] SELECT DISTINCT T1.first_name ,  T1.last_name FROM government_services.citizens AS T1 JOIN government_services.appointments AS T2 ON T1.citizen_id  =  T2.citizen_id JOIN government_services.payments AS T3 ON T1.citizen_id  =  T3.citizen_id

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id.text, national_id_number.text, first_name.text, last_name.text, date_of_birth.date, gender.text, primary_address.text, contact_email.text, contact_phone.text, registration_date.timestamp, is_verified.boolean )
CREATE TABLE government_services.payments ( payment_id.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )


[User] List all pairs of securities that are issued by the same issuer but trade on different exchanges. Show the ticker symbols and exchanges for both securities as symbol_a, exchange_a, symbol_b, exchange_b, and include issuer_name.

[Assistant] SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.issuer_name FROM financial_services.securities a JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.exchange <> b.exchange;

[User] Actually, restrict the result to only include pairs where both securities have non-null currency and sector.

[Assistant] SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.issuer_name FROM financial_services.securities a JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.exchange <> b.exchange WHERE a.currency IS NOT NULL AND b.currency IS NOT NULL AND a.sector IS NOT NULL AND b.sector IS NOT NULL;

[User] I need only pairs where symbol_a is lexicographically less than symbol_b to avoid duplicate reversed pairs.

[Assistant] SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.issuer_name FROM financial_services.securities a JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.exchange <> b.exchange WHERE a.currency IS NOT NULL AND b.currency IS NOT NULL AND a.sector IS NOT NULL AND b.sector IS NOT NULL AND a.ticker_symbol < b.ticker_symbol;

[User] Now sort the result by issuer_name ascending, then by symbol_a.

[Assistant] SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.issuer_name FROM financial_services.securities a JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.exchange <> b.exchange WHERE a.currency IS NOT NULL AND b.currency IS NOT NULL AND a.sector IS NOT NULL AND b.sector IS NOT NULL AND a.ticker_symbol < b.ticker_symbol ORDER BY a.issuer_name ASC, a.ticker_symbol ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.securities ( security_id text, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )


[User] Show me a list of all notifications that are related to comments. Include the notification ID, the recipient user ID, and the target entity ID, which corresponds to the comment ID.

[Assistant] SELECT notification_id, recipient_user_id, target_entity_id FROM social_media.notifications WHERE target_entity_type = 'comment';

[User] Please expand that list to include the username of the notification recipient and the content of the comment that the notification is about.

[Assistant] SELECT n.notification_id, u.username, c.content FROM social_media.notifications n JOIN social_media.users u ON n.recipient_user_id = u.user_id JOIN social_media.comments c ON n.target_entity_id = c.comment_id WHERE n.target_entity_type = 'comment';

[User] Okay, filter this down to only show notifications where the comment content is not empty, and the notification type is either 'like' or 'comment'.

[Assistant] SELECT n.notification_id, u.username, c.content FROM social_media.notifications n JOIN social_media.users u ON n.recipient_user_id = u.user_id JOIN social_media.comments c ON n.target_entity_id = c.comment_id WHERE n.target_entity_type = 'comment' AND (c.content IS NOT NULL AND c.content != '') AND n.notification_type IN ('like', 'comment');

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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.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.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 )


[User] List all premium payments made after April 1, 2024, including the payment_id, policy_id, customer_id, and amount_paid.

[Assistant]
SELECT payment_id, policy_id, customer_id, amount_paid
FROM insurance.premium_payments
WHERE payment_date > '2024-04-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )


[User] What is the count of securities for each currency in the 'Energy' sector?

[Assistant] SELECT currency, COUNT(*) as security_count FROM financial_services.securities WHERE sector = 'Energy' GROUP BY currency;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.securities ( security_id character varying(64) NOT NULL, ticker_symbol character varying(20) NOT NULL UNIQUE, isin_code character varying(12) UNIQUE, cusip_code character varying(9) UNIQUE, security_name text NOT NULL, security_type character varying(50) NOT NULL, exchange character varying(50), currency character varying(3) NOT NULL, issuer_name character varying(255), sector character varying(100), last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (security_id) )


[User] List the post_id and the count of distinct hashtags associated with each post that has at least 3 hashtags.

[Assistant] SELECT ph.post_id, COUNT(DISTINCT ph.hashtag_id) AS hashtag_count FROM social_media.post_hashtags ph GROUP BY ph.post_id HAVING COUNT(DISTINCT ph.hashtag_id) >= 3;

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


[User] List all token symbols on the 'Ethereum' chain with a Realized Ratio greater than 0.9. Show the symbol and realized ratio.

[Assistant] SELECT token_symbol, realized_ratio FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9;

[User] Can you also include their current Price and Net Flow?

[Assistant] SELECT token_symbol, realized_ratio, price, net_flow FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9;

[User] Now, filter these results to only include tokens where the Net Flow is positive.

[Assistant] SELECT token_symbol, realized_ratio, price, net_flow FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9 AND net_flow > 0;

[User] Order the results by Net Flow descending and show the top 10.

[Assistant] SELECT token_symbol, realized_ratio, price, net_flow FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9 AND net_flow > 0 ORDER BY net_flow DESC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )


[User] Retrieve the top 5 players by the number of distinct achievements unlocked. Show player_id and distinct_unlocks.

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC
LIMIT 5;

[User] Now limit the results to players whose status is 'active'.

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE p.status = 'active'
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC
LIMIT 5;

[User] Sort the list by distinct_unlocks descending and then by player_id ascending.

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE p.status = 'active'
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC, p.player_id ASC
LIMIT 5;

[User] Finally, limit the output to the top 3 entries.

[Assistant]
SELECT p.player_id, COUNT(DISTINCT pa.achievement_id) AS distinct_unlocks
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE p.status = 'active'
GROUP BY p.player_id
ORDER BY distinct_unlocks DESC, p.player_id ASC
LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )


[User] How many distinct ports have been used by peers in the system?

[Assistant]
SELECT COUNT(DISTINCT port) AS distinct_port_count
FROM trading_platform.peers;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] What is the average interest rate for auto loans (loan_type = 'Auto') with a principal amount between $20,000 and $50,000?

[Assistant] SELECT AVG(interest_rate) AS average_interest_rate FROM financial_services.loans WHERE loan_type = 'Auto' AND principal_amount BETWEEN 20000 AND 50000

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.loans ( loan_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL UNIQUE, loan_type character varying(50) NOT NULL, principal_amount numeric(19, 4) NOT NULL, current_principal_balance numeric(19, 4) NOT NULL, interest_rate numeric(6, 4) NOT NULL, term_months integer NOT NULL, origination_date date NOT NULL, maturity_date date NOT NULL, monthly_payment numeric(12, 4), collateral_description text, status character varying(32) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id) )


[User] Show me the top 3 narratives by 24-hour trading volume, along with their 1-hour and 24-hour price change percentages.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_1h, price_change_percentage_24h FROM narrative_info ORDER BY volume_24h DESC LIMIT 3;

[User] Actually, I only want narratives with a positive 7-day price change percentage.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_1h, price_change_percentage_24h FROM narrative_info WHERE price_change_percentage_7d > 0 ORDER BY volume_24h DESC LIMIT 3;

[User] Can you also include the market cap for these narratives?

[Assistant] SELECT narrative, volume_24h, price_change_percentage_1h, price_change_percentage_24h, market_cap FROM narrative_info WHERE price_change_percentage_7d > 0 ORDER BY volume_24h DESC LIMIT 3;

[User] Now order the results by market cap instead of trading volume.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_1h, price_change_percentage_24h, market_cap FROM narrative_info WHERE price_change_percentage_7d > 0 ORDER BY market_cap DESC LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
 "CREATE TABLE narrative_info (",
    "narrative character varying(512) NOT NULL, -- the id of narrative",
    "top_3_coins text, -- the top 3 tokens in the narrative",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative",
    "price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative",
    "market_cap double precision, -- the market cap of the narrative",
    "volume_24h double precision, -- the trade volume of the narrative",
    "trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative",
    "token_num bigint, -- total token number in the narrative",
    ",PRIMARY KEY (narrative));"


[User] Show me the total fuel cost for each trip along with the trip's route number and the type of the route.

[Assistant]
SELECT t.trip_id, r.route_number, r.type, SUM(f.total_cost) AS total_fuel_cost
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY t.trip_id, r.route_number, r.type;

[User] Modify the query to only include trips on routes of type 'Express', and show results ordered by total fuel cost descending.

[Assistant]
SELECT t.trip_id, r.route_number, r.type, SUM(f.total_cost) AS total_fuel_cost
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
WHERE r.type = 'Express'
GROUP BY t.trip_id, r.route_number, r.type
ORDER BY total_fuel_cost DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
CREATE TABLE transportation.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 )


[User] What is the average interest rate for loans of type 'Mortgage'?

[Assistant] SELECT AVG(interest_rate) FROM financial_services.loans WHERE loan_type = 'Mortgage'

[User] Refine this to only include loans with status 'Active'.

[Assistant] SELECT AVG(interest_rate) FROM financial_services.loans WHERE loan_type = 'Mortgage' AND status = 'Active'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )


[User] Show me the top 5 projects by valuation that completed fundraising rounds in the last 3 months, along with their narrative information if available.

[Assistant] SELECT pfr.project_name, pfr.valuation, pfr.rounds_name, pfr.investment_date, ni.narrative, ni.trend_rank FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name LEFT JOIN narrative_info ni ON tbi.narrative = ni.narrative WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) ORDER BY pfr.valuation DESC LIMIT 5;

[User] Can you also include the 24-hour trading volume for these projects' narratives and filter to only include projects with valuation over $50 million?

[Assistant] SELECT pfr.project_name, pfr.valuation, pfr.rounds_name, pfr.investment_date, ni.narrative, ni.trend_rank, ni.volume_24h FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name LEFT JOIN narrative_info ni ON tbi.narrative = ni.narrative WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND pfr.valuation > 50000000 ORDER BY pfr.valuation DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, token_address character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, highest_price_24h double precision, lowest_price_24h double precision, market_cap double precision, market_cap_rank bigint, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank bigint )
 "CREATE TABLE narrative_info (",
    "narrative character varying(512) NOT NULL, -- the id of narrative",
    "top_3_coins text, -- the top 3 tokens in the narrative",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative",
    "price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative",
    "market_cap double precision, -- the market cap of the narrative",
    "volume_24h double precision, -- the trade volume of the narrative",
    "trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative",
    "token_num bigint, -- total token number in the narrative",
    ",PRIMARY KEY (narrative));"

CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL, chain character varying(128) NOT NULL, address character varying(128) NOT NULL, exchange character varying(512) NOT NULL, token_address character varying(128) NOT NULL, token_symbol character varying(512), balance numeric(38,10), usd_value numeric(38,14), price double precision )
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )


[User] Find all patients who have insurance plans with group numbers, showing their patient IDs and the count of such plans per patient, ordered by count in descending order.

[Assistant]
SELECT patient_id, COUNT(*) AS group_plan_count
FROM healthcare.patient_insurance
WHERE group_number IS NOT NULL
GROUP BY patient_id
ORDER BY group_plan_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List each item's name, type, and rarity, along with the currency in which it can be purchased and its cost.

[Assistant] SELECT item_name, item_type, rarity, cost_currency, cost_amount FROM gaming_technology.in_game_items;

[User] Show only the items that have a cost greater than 0 and a non-null cost_currency.

[Assistant] SELECT item_name, item_type, rarity, cost_currency, cost_amount FROM gaming_technology.in_game_items WHERE cost_amount > 0 AND cost_currency IS NOT NULL;

[User] I got an error about null values in cost_amount, could you make the query handle those cases?

[Assistant] SELECT item_name, item_type, rarity, cost_currency, cost_amount FROM gaming_technology.in_game_items WHERE cost_currency IS NOT NULL AND cost_amount IS NOT NULL AND cost_amount > 0;

[User] Finally, could you sort the results by cost_amount from highest to lowest?

[Assistant] SELECT item_name, item_type, rarity, cost_currency, cost_amount FROM gaming_technology.in_game_items WHERE cost_currency IS NOT NULL AND cost_amount IS NOT NULL AND cost_amount > 0 ORDER BY cost_amount DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)


[User] List each genre and the number of games in that genre.

[Assistant]
SELECT genre,
       COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY genre;

[User] Now filter to only include genres with more than 5 games.

[Assistant]
SELECT genre,
       COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY genre
HAVING COUNT(*) > 5;

[User] Exclude entries where genre is NULL.

[Assistant]
SELECT genre,
       COUNT(*) AS game_count
FROM gaming_technology.games
WHERE genre IS NOT NULL
GROUP BY genre
HAVING COUNT(*) > 5;

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

[Assistant]
SELECT genre,
       COUNT(*) AS game_count
FROM gaming_technology.games
WHERE genre IS NOT NULL
GROUP BY genre
HAVING COUNT(*) > 5
ORDER BY game_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)


[User] Show me all insurance plans that have more than 3 patients enrolled as their primary insurance, along with the provider name and count of patients, sorted by patient count in descending order.

[Assistant] SELECT ip.insurance_provider, COUNT(pi.patient_id) AS patient_count FROM healthcare.insurance_plans ip JOIN healthcare.patient_insurance pi ON ip.plan_id = pi.plan_id WHERE pi.is_primary = true GROUP BY ip.insurance_provider HAVING COUNT(pi.patient_id) > 3 ORDER BY patient_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
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, 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 character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] Show me all accounts (account_id, account_number, account_type, balance, currency) for customers whose status is 'VIP'.

[Assistant] SELECT a.account_id, a.account_number, a.account_type, a.balance, a.currency FROM financial_services.accounts AS a JOIN financial_services.customers AS c ON a.customer_id = c.customer_id WHERE c.status = 'VIP';

[User] Also include the customer's email and the date they were created.

[Assistant] SELECT a.account_id, a.account_number, a.account_type, a.balance, a.currency, c.email, c.created_at FROM financial_services.accounts AS a JOIN financial_services.customers AS c ON a.customer_id = c.customer_id WHERE c.status = 'VIP';

[User] Filter the results to only include accounts opened before 2023-01-01.

[Assistant] SELECT a.account_id, a.account_number, a.account_type, a.balance, a.currency, c.email, c.created_at FROM financial_services.accounts AS a JOIN financial_services.customers AS c ON a.customer_id = c.customer_id WHERE c.status = 'VIP' AND a.opened_date < '2023-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, account_number character varying(128) NOT NULL UNIQUE, account_type character varying(50) NOT NULL, balance numeric(19, 4) NOT NULL DEFAULT 0.00, currency character varying(3) NOT NULL, opened_date date NOT NULL, status character varying(32) NOT NULL, interest_rate numeric(5, 4), last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) )


[User] Find all patients who have both an emergency contact and a phone number, and show their full names along with the emergency contact name and phone number, sorted by last name.

[Assistant] SELECT CONCAT(first_name, ' ', last_name) AS patient_full_name, emergency_contact_name, emergency_contact_phone FROM healthcare.patients WHERE emergency_contact_name IS NOT NULL AND phone_number IS NOT NULL ORDER BY last_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )


[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;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 )


[User] What is the total count of game sessions recorded?

[Assistant] SELECT count(*) FROM gaming_technology.game_sessions;

[User] Now, only count sessions that lasted longer than 1 hour.

[Assistant] SELECT count(*) FROM gaming_technology.game_sessions WHERE duration_seconds > 3600;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)


[User] How many applications are currently pending review? Please group the results by assigned_employee_id.

[Assistant] SELECT assigned_employee_id, COUNT(*) AS pending_applications FROM government_services.applications WHERE status = 'Pending' GROUP BY assigned_employee_id;

[User] I got some assigned_employee_id values as NULL. Can you exclude those from the result?

[Assistant] SELECT assigned_employee_id, COUNT(*) AS pending_applications FROM government_services.applications WHERE status = 'Pending' AND assigned_employee_id IS NOT NULL GROUP BY assigned_employee_id;

[User] Now, show only employees who have more than 3 pending applications.

[Assistant] SELECT assigned_employee_id, COUNT(*) AS pending_applications FROM government_services.applications WHERE status = 'Pending' AND assigned_employee_id IS NOT NULL GROUP BY assigned_employee_id HAVING COUNT(*) > 3;

[User] Order the results by the count of pending applications in descending order.

[Assistant] SELECT assigned_employee_id, COUNT(*) AS pending_applications FROM government_services.applications WHERE status = 'Pending' AND assigned_employee_id IS NOT NULL GROUP BY assigned_employee_id HAVING COUNT(*) > 3 ORDER BY pending_applications DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 )


[User] List all servers that are currently online. Show their name, region, current player count, and maximum player capacity.

[Assistant] SELECT server_name, region, current_players, max_players FROM gaming_technology.servers WHERE status = 'online';

[User] Filter the list to only include servers with a player utilization ratio (current_players / max_players) above 0.8.

[Assistant] SELECT server_name, region, current_players, max_players FROM gaming_technology.servers WHERE status = 'online' AND max_players > 0 AND (CAST(current_players AS NUMERIC) / max_players) > 0.8;

[User] Also, exclude any servers where the maximum player capacity is less than 50.

[Assistant] SELECT server_name, region, current_players, max_players FROM gaming_technology.servers WHERE status = 'online' AND max_players >= 50 AND (CAST(current_players AS NUMERIC) / max_players) > 0.8;

[User] Finally, order the results by player utilization ratio in descending order and limit the output to the top 10 servers.

[Assistant] SELECT server_name, region, current_players, max_players FROM gaming_technology.servers WHERE status = 'online' AND max_players >= 50 AND (CAST(current_players AS NUMERIC) / max_players) > 0.8 ORDER BY (CAST(current_players AS NUMERIC) / max_players) DESC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )


[User] Show me all invoice numbers together with the client IDs and related case IDs for invoices issued after March 1st, 2024.

[Assistant] SELECT invoice_number, client_id, case_id FROM legal_services.invoices WHERE issue_date > '2024-03-01';

[User] I only want to include invoices that have a total_amount greater than 5000. Can you update the query?

[Assistant] SELECT invoice_number, client_id, case_id FROM legal_services.invoices WHERE issue_date > '2024-03-01' AND total_amount > 5000;

[User] Add the invoice status to the result, and only show invoices where the status is either 'Overdue' or 'Partially Paid'.

[Assistant] SELECT invoice_number, client_id, case_id, status FROM legal_services.invoices WHERE issue_date > '2024-03-01' AND total_amount > 5000 AND status IN ('Overdue', 'Partially Paid');

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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)
)


[User] Show me all nodes that haven't been seen in the last 24 hours.

[Assistant]
SELECT node_id,
       ip_address,
       port,
       last_seen
FROM blockchain.nodes
WHERE last_seen < NOW() - INTERVAL '24 hours';

[User] Okay, include also the number of hours since they were last seen.

[Assistant]
SELECT node_id,
       ip_address,
       port,
       last_seen,
       EXTRACT(EPOCH FROM (NOW() - last_seen)) / 3600 AS hours_since_last_seen
FROM blockchain.nodes
WHERE last_seen < NOW() - INTERVAL '24 hours';

[User] Now filter to only those with more than 48 hours since last seen and order by hours_since_last_seen descending.

[Assistant]
SELECT node_id,
       ip_address,
       port,
       last_seen,
       EXTRACT(EPOCH FROM (NOW() - last_seen)) / 3600 AS hours_since_last_seen
FROM blockchain.nodes
WHERE last_seen < NOW() - INTERVAL '48 hours'
ORDER BY hours_since_last_seen DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.nodes ( node_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (node_id) )


[User] List all developers founded before the year 2000, showing their name, country, and the year they were founded.

[Assistant] SELECT name, country, founded_year FROM gaming_technology.developers WHERE founded_year < 2000;

[User] Could you also include the website for these developers?

[Assistant] SELECT name, country, founded_year, website FROM gaming_technology.developers WHERE founded_year < 2000;

[User] Now, only include developers located in 'USA', 'Canada', or 'Mexico'.

[Assistant] SELECT name, country, founded_year, website FROM gaming_technology.developers WHERE founded_year < 2000 AND country IN ('USA', 'Canada', 'Mexico');

[User] Finally, order the results by country ascending and then by founded year ascending.

[Assistant] SELECT name, country, founded_year, website FROM gaming_technology.developers WHERE founded_year < 2000 AND country IN ('USA', 'Canada', 'Mexico') ORDER BY country ASC, founded_year ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )


[User] List all agents along with their manager's first and last name for agents whose status is 'active'.

[Assistant]
SELECT a.agent_id,
       a.first_name AS agent_first_name,
       a.last_name AS agent_last_name,
       m.agent_id AS manager_id,
       m.first_name AS manager_first_name,
       m.last_name AS manager_last_name
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.status = 'active';

[User] Only include agents hired after January 1st, 2020.

[Assistant]
SELECT a.agent_id,
       a.first_name AS agent_first_name,
       a.last_name AS agent_last_name,
       m.agent_id AS manager_id,
       m.first_name AS manager_first_name,
       m.last_name AS manager_last_name
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.status = 'active'
  AND a.hire_date > '2020-01-01';

[User] Also order the results by the agent's last name in ascending order.

[Assistant]
SELECT a.agent_id,
       a.first_name AS agent_first_name,
       a.last_name AS agent_last_name,
       m.agent_id AS manager_id,
       m.first_name AS manager_first_name,
       m.last_name AS manager_last_name
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.status = 'active'
  AND a.hire_date > '2020-01-01'
ORDER BY a.last_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 )


[User] For the 'DeFi' narrative, what is the average ROI and the total net inflow (usd_value where type=1) from smart money token inflow?

[Assistant]
SELECT AVG(sm.roi) AS avg_roi, SUM(smt.usd_value) AS total_net_inflow
FROM smart_money_token_inflow smt
JOIN smart_money_profit sm ON smt.chain = sm.chain
WHERE smt.narrative = 'DeFi' AND smt.type = 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE cex_token_balance ( snapshot_time text, chain text, address text, exchange text, token_address text, token_symbol text, balance numeric, usd_value numeric, price numeric )
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 )
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )


[User] List all depots (location type 'Depot') and the number of vehicles assigned to each. Include the depot name and city.

[Assistant] SELECT T1.name ,  T1.city ,  COUNT(T2.vehicle_id) FROM transportation.locations AS T1 LEFT JOIN transportation.vehicles AS T2 ON T1.location_id  =  T2.depot_id WHERE T1.type  =  'Depot' GROUP BY T1.location_id ,  T1.name ,  T1.city

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers (
    driver_id character varying(64) NOT NULL,  -- unique identifier for the driver
    employee_id character varying(64) NOT NULL UNIQUE, -- employee reference number
    first_name character varying(128) NOT NULL, -- driver's first name
    last_name character varying(128) NOT NULL, -- driver's last name
    license_number character varying(64) NOT NULL UNIQUE, -- driving license number
    license_expiry_date date NOT NULL, -- expiry date of the license
    contact_number character varying(32), -- phone number
    email character varying(128) UNIQUE, -- email address
    hire_date date NOT NULL, -- date the driver was hired
    status character varying(32) NOT NULL, -- e.g., Active, On Leave, Terminated
    PRIMARY KEY (driver_id)
)
CREATE TABLE transportation.routes (
    route_id character varying(64) NOT NULL,  -- unique identifier for the route
    route_number character varying(32) NOT NULL UNIQUE, -- public-facing route number/name
    description text, -- description of the route
    origin_location_id character varying(64) NOT NULL, -- identifier of the starting location
    destination_location_id character varying(64) NOT NULL, -- identifier of the ending location
    distance_km numeric(10, 2), -- estimated distance in kilometers
    estimated_duration_minutes integer, -- estimated travel time in minutes
    type character varying(32) NOT NULL, -- e.g., City Bus, Intercity Train, Cargo Delivery
    PRIMARY KEY (route_id)
)
CREATE TABLE transportation.locations (
    location_id character varying(64) NOT NULL,  -- unique identifier for the location
    name character varying(255) NOT NULL, -- name of the location (e.g., Central Station, Depot Alpha, Pier 7)
    type character varying(64) NOT NULL, -- e.g., Station, Stop, Depot, Port, Airport, Customer Address
    address_line1 character varying(255), -- street address
    city character varying(128), -- city name
    state_province character varying(128), -- state or province
    postal_code character varying(32), -- postal code
    country character varying(64) NOT NULL, -- country name
    latitude numeric(9, 6), -- geographic latitude
    longitude numeric(9, 6), -- geographic longitude
    timezone character varying(64), -- IANA timezone name (e.g., America/New_York)
    PRIMARY KEY (location_id)
)
CREATE TABLE transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)


[User] List all appointments showing the appointment ID, the citizen's full name, and the name of the service associated with the appointment.

[Assistant]
SELECT appt.appointment_id, c.first_name || ' ' || c.last_name AS citizen_full_name, s.service_id AS service_id
FROM government_services.appointments appt
JOIN government_services.citizens c ON appt.citizen_id = c.citizen_id
JOIN government_services.applications app ON app.citizen_id = c.citizen_id AND app.service_id = appt.service_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id.text, national_id_number.text, first_name.text, last_name.text, date_of_birth.date, gender.text, primary_address.text, contact_email.text, contact_phone.text, registration_date.timestamp, is_verified.boolean )
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )


[User] I would like to list each appointment along with any associated medical record's chief complaint, including the appointment_id, appointment_time, and chief_complaint. Include appointments even if there's no medical record.

[Assistant]
SELECT a.appointment_id, a.appointment_time, mr.chief_complaint
FROM healthcare.appointments a
LEFT JOIN healthcare.medical_records mr ON a.appointment_id = mr.appointment_id;

[User] Actually, only include appointments with status = 'Completed' and where the chief_complaint contains the word 'fever'.

[Assistant]
SELECT a.appointment_id, a.appointment_time, mr.chief_complaint
FROM healthcare.appointments a
LEFT JOIN healthcare.medical_records mr ON a.appointment_id = mr.appointment_id
WHERE a.status = 'Completed'
  AND mr.chief_complaint ILIKE '%fever%';

[User] Also, order the results by appointment_time ascending and limit to the first 10 rows.

[Assistant]
SELECT a.appointment_id, a.appointment_time, mr.chief_complaint
FROM healthcare.appointments a
LEFT JOIN healthcare.medical_records mr ON a.appointment_id = mr.appointment_id
WHERE a.status = 'Completed'
  AND mr.chief_complaint ILIKE '%fever%'
ORDER BY a.appointment_time ASC
LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )


[User] Find the top 3 drivers by their average number of passengers per trip, including driver_id, first_name, last_name, and avg_passengers, ordered by avg_passengers descending.

[Assistant]
SELECT d.driver_id,
       d.first_name,
       d.last_name,
       AVG(t.passenger_count) AS avg_passengers
FROM transportation.drivers d
JOIN transportation.trips t ON d.driver_id = t.driver_id
GROUP BY d.driver_id, d.first_name, d.last_name
ORDER BY avg_passengers DESC
LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.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.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )


[User] Show me the top 5 users who have the highest total trade volume (quantity * price) as buyers, along with their email addresses and the number of distinct assets they traded.

[Assistant] SELECT u.user_id, u.email, COUNT(DISTINCT t.asset_id) AS distinct_assets_traded, SUM(t.quantity * t.price) AS total_trade_volume FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id GROUP BY u.user_id, u.email ORDER BY total_trade_volume DESC LIMIT 5;

[User] Now modify the query to include only trades that happened in the last 30 days and show the average trade price for each buyer.

[Assistant] SELECT u.user_id, u.email, COUNT(DISTINCT t.asset_id) AS distinct_assets_traded, SUM(t.quantity * t.price) AS total_trade_volume, AVG(t.price) AS average_trade_price FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id WHERE t.traded_at >= NOW() - INTERVAL '30 days' GROUP BY u.user_id, u.email ORDER BY total_trade_volume DESC LIMIT 5;

[User] Actually, I want to see the top 5 buyers by total trade volume who also have wallets, and include their wallet addresses.

[Assistant] SELECT u.user_id, u.email, w.address AS wallet_address, SUM(t.quantity * t.price) AS total_trade_volume FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id JOIN trading_platform.orders o ON t.order_id = o.order_id JOIN trading_platform.utxos w ON o.wallet_id = w.address WHERE w.spent = false GROUP BY u.user_id, u.email, w.address ORDER BY total_trade_volume DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text, transaction_id text, output_index integer, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text, user_id text, status text, reviewed_at timestamp )


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

[Assistant] SELECT t1.type_name, t2.property_name, t1.base_rate FROM hospitality_technology.room_types AS t1 JOIN hospitality_technology.properties AS t2 ON t1.property_id = t2.property_id

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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 )


[User] 特定の職種の従業員情報を取得したいです。従業員ID、名前、職種、雇用日を表示してください。

[Assistant]
db.employees.find(
    { job_title: '<specific_job_title>' },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用日が2020年1月1日以降の従業員だけに絞り込むことはできますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') }
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用ステータスが「Active」の従業員だけをさらに条件に加えられますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] スキル認定情報も結果に含めてください。

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, skill_certifications: 1, _id: 0 }
).sort({ hire_date: -1 })

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Collection 'assembly_steps'. Document structure: { _id: <ObjectId (or step_id)>, step_id: String, line_id: String (reference), step_number: NumberInt, step_name: String, description: String, standard_duration_hours: Decimal128, required_skill_level: String, workstation: String }. Required: step_id, line_id, step_number, step_name. Index on line_id, step_number.
Collection 'employees'. Document structure: { _id: <ObjectId (or employee_id)>, employee_id: String, first_name: String, last_name: String, job_title: String, skill_certifications: [String], hire_date: ISODate, assigned_line_id: String (reference, optional), employment_status: String, supervisor_employee_id: String (reference, optional) }. Required: employee_id, first_name, last_name, job_title, hire_date, employment_status.


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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )


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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id character varying(64) NOT NULL, previous_block_id character varying(64), timestamp timestamp NOT NULL, nonce integer NOT NULL, merkle_root character varying(128) NOT NULL, difficulty integer NOT NULL, PRIMARY KEY (block_id) )


[User] Find all DApps that have been interacted with by users who have wallets with more than 1000 in their order quantities.

[Assistant] SELECT DISTINCT d.dapp_id, d.name, d.description FROM trading_platform.dapps d JOIN trading_platform.orders o ON d.dapp_id = o.dapp_id JOIN trading_platform.wallets w ON o.wallet_id = w.wallet_id WHERE o.quantity > 1000;

[User] I notice the query is missing the join condition for DApp interactions. Also, can you modify it to show the count of such users per DApp?

[Assistant] SELECT d.dapp_id, d.name, COUNT(DISTINCT o.user_id) AS user_count FROM trading_platform.dapps d JOIN trading_platform.orders o ON d.dapp_id = o.dapp_id JOIN trading_platform.wallets w ON o.wallet_id = w.wallet_id WHERE o.quantity > 1000 GROUP BY d.dapp_id, d.name;

[User] Now filter these results to only show DApps with more than 5 such users.

[Assistant] SELECT d.dapp_id, d.name, COUNT(DISTINCT o.user_id) AS user_count FROM trading_platform.dapps d JOIN trading_platform.orders o ON d.dapp_id = o.dapp_id JOIN trading_platform.wallets w ON o.wallet_id = w.wallet_id WHERE o.quantity > 1000 GROUP BY d.dapp_id, d.name HAVING COUNT(DISTINCT o.user_id) > 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] For each appointment, show the appointment ID, the associated citizen's full name, and the document types they have uploaded for that appointment's application.

[Assistant]
SELECT a.appointment_id, c.first_name || ' ' || c.last_name AS citizen_full_name, d.document_type
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.documents d ON d.citizen_id = c.citizen_id
WHERE d.application_id IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )


[User] How many players are registered for each country? Return the country_code and the player count.

[Assistant] SELECT country_code, COUNT(*) AS player_count FROM gaming_technology.players GROUP BY country_code;

[User] I only want to see countries where there are at least 3 players. Please also order the result by player_count descending.

[Assistant] SELECT country_code, COUNT(*) AS player_count FROM gaming_technology.players GROUP BY country_code HAVING COUNT(*) >= 3 ORDER BY player_count DESC;

[User] Remove countries where the country_code is NULL.

[Assistant] SELECT country_code, COUNT(*) AS player_count FROM gaming_technology.players WHERE country_code IS NOT NULL GROUP BY country_code HAVING COUNT(*) >= 3 ORDER BY player_count DESC;

[User] Please also include the earliest registration_date for each country.

[Assistant] SELECT country_code, COUNT(*) AS player_count, MIN(registration_date) AS earliest_registration FROM gaming_technology.players WHERE country_code IS NOT NULL GROUP BY country_code HAVING COUNT(*) >= 3 ORDER BY player_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )