System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
CREATE TABLE social_media.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] How many users have verified profiles and private profiles enabled?

[Assistant]
SELECT COUNT(*)
FROM social_media.users u
JOIN social_media.user_settings s ON u.user_id = s.user_id
WHERE u.is_verified = true AND s.private_profile = true;

[User] Can you show me the usernames instead of just the count?

[Assistant]
SELECT u.username
FROM social_media.users u
JOIN social_media.user_settings s ON u.user_id = s.user_id
WHERE u.is_verified = true AND s.private_profile = true;

[User] Only show those users who have push notifications enabled as well.

[Assistant]
SELECT u.username
FROM social_media.users u
JOIN social_media.user_settings s ON u.user_id = s.user_id
WHERE u.is_verified = true AND s.private_profile = true AND s.push_notifications_enabled = true;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text, 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.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.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] List each verified user's username and their total number of public posts.

[Assistant]
SELECT u.username, COUNT(p.post_id) AS post_count
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id AND p.visibility = 'public'
WHERE u.is_verified = true
GROUP BY u.username;

[User] Now include only posts created in the last 30 days.

[Assistant]
SELECT u.username, COUNT(p.post_id) AS post_count
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
  AND p.visibility = 'public'
  AND p.created_at >= current_date - INTERVAL '30 days'
WHERE u.is_verified = true
GROUP BY u.username;

[User] Also include the date of their most recent post.

[Assistant]
SELECT u.username, COUNT(p.post_id) AS post_count, MAX(p.created_at) AS latest_post_date
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
  AND p.visibility = 'public'
  AND p.created_at >= current_date - INTERVAL '30 days'
WHERE u.is_verified = true
GROUP BY u.username;

[User] Sort the results by the post count descending and limit to 10.

[Assistant]
SELECT u.username, COUNT(p.post_id) AS post_count, MAX(p.created_at) AS latest_post_date
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
  AND p.visibility = 'public'
  AND p.created_at >= current_date - INTERVAL '30 days'
WHERE u.is_verified = true
GROUP BY u.username
ORDER BY post_count DESC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )

[User] List all claims that have at least one document of type 'INVOICE', including the claim ID, incident date, estimated loss, and the document's file name.

[Assistant]
SELECT c.claim_id, c.incident_date, c.estimated_loss, d.file_name
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.document_type = 'INVOICE';

[User] Also show the file size in bytes and the uploaded date for each document.

[Assistant]
SELECT c.claim_id, c.incident_date, c.estimated_loss, d.file_name, d.file_size_bytes, d.uploaded_at
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.document_type = 'INVOICE';

[User] Actually, just show the claims where the document file size is greater than 100,000 bytes.

[Assistant]
SELECT c.claim_id, c.incident_date, c.estimated_loss, d.file_name, d.file_size_bytes, d.uploaded_at
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.document_type = 'INVOICE'
  AND d.file_size_bytes > 100000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.fuel_logs ( fuel_log_id 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] Identify all instances where a vehicle's odometer_reading decreased compared to its previous fuel log entry.

[Assistant]
SELECT curr.vehicle_id,
       prev.fuel_log_id   AS previous_log_id,
       prev.odometer_reading AS previous_reading,
       curr.fuel_log_id   AS current_log_id,
       curr.odometer_reading AS current_reading
FROM transportation.fuel_logs AS curr
JOIN transportation.fuel_logs AS prev
  ON curr.vehicle_id = prev.vehicle_id
  AND curr.log_timestamp > prev.log_timestamp
  AND NOT EXISTS (
    SELECT 1
    FROM transportation.fuel_logs AS mid
    WHERE mid.vehicle_id = curr.vehicle_id
      AND mid.log_timestamp > prev.log_timestamp
      AND mid.log_timestamp < curr.log_timestamp
  )
WHERE curr.odometer_reading < prev.odometer_reading;

[User] Only show decreases greater than 100 miles.

[Assistant]
SELECT curr.vehicle_id,
       prev.fuel_log_id   AS previous_log_id,
       prev.odometer_reading AS previous_reading,
       curr.fuel_log_id   AS current_log_id,
       curr.odometer_reading AS current_reading
FROM transportation.fuel_logs AS curr
JOIN transportation.fuel_logs AS prev
  ON curr.vehicle_id = prev.vehicle_id
  AND curr.log_timestamp > prev.log_timestamp
  AND NOT EXISTS (
    SELECT 1
    FROM transportation.fuel_logs AS mid
    WHERE mid.vehicle_id = curr.vehicle_id
      AND mid.log_timestamp > prev.log_timestamp
      AND mid.log_timestamp < curr.log_timestamp
  )
WHERE prev.odometer_reading - curr.odometer_reading > 100;

[User] Sort the results by the magnitude of the decrease in descending order.

[Assistant]
SELECT curr.vehicle_id,
       prev.fuel_log_id   AS previous_log_id,
       prev.odometer_reading AS previous_reading,
       curr.fuel_log_id   AS current_log_id,
       curr.odometer_reading AS current_reading,
       (prev.odometer_reading - curr.odometer_reading) AS decrease_amount
FROM transportation.fuel_logs AS curr
JOIN transportation.fuel_logs AS prev
  ON curr.vehicle_id = prev.vehicle_id
  AND curr.log_timestamp > prev.log_timestamp
  AND NOT EXISTS (
    SELECT 1
    FROM transportation.fuel_logs AS mid
    WHERE mid.vehicle_id = curr.vehicle_id
      AND mid.log_timestamp > prev.log_timestamp
      AND mid.log_timestamp < curr.log_timestamp
  )
WHERE prev.odometer_reading - curr.odometer_reading > 100
ORDER BY decrease_amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )

[User] For Avalanche tokens, show me the token `tick`, `creator`, and `max_supply` from the `token_info_avalanche` table.

[Assistant] SELECT tick, creator, max_supply FROM token_info_avalanche

[User] Now, for each of these ticks, calculate the total transfer volume (`amt`) from the `token_activities_avalanche` table over the last 30 days.

[Assistant] SELECT T1.tick, T2.creator, T2.max_supply, SUM(T1.amt) AS total_volume FROM token_activities_avalanche AS T1 JOIN token_info_avalanche AS T2 ON T1.tick = T2.tick WHERE T1.block_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30' DAY GROUP BY T1.tick, T2.creator, T2.max_supply

[User] Filter the results to only include ticks where the `total_volume` is greater than 10000.

[Assistant] SELECT T1.tick, T2.creator, T2.max_supply, SUM(T1.amt) AS total_volume FROM token_activities_avalanche AS T1 JOIN token_info_avalanche AS T2 ON T1.tick = T2.tick WHERE T1.block_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30' DAY GROUP BY T1.tick, T2.creator, T2.max_supply HAVING SUM(T1.amt) > 10000


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
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 )
  "CREATE TABLE smart_money_token_inflow (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token",
    "usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token",
    "avg_price numeric(38,6), -- the average cost price of user spent on this token",
    "type int, -- the direction of the trade on this token. 1 means buying, 2 means selling",
    "address_amount integer, -- the amount of the user bought this token",
    "narrative character varying(100), -- the category or narrative of the token",
    "chain character varying(100), -- the chain that the token resides",
    ",PRIMARY KEY (token_address, chain)",

[User] Compute the average realized_ratio and average pnl for smart money token performance grouped by chain.

[Assistant]
SELECT chain, AVG(realized_ratio) AS avg_realized_ratio, AVG(pnl) AS avg_pnl
FROM smart_money_token_performance
GROUP BY chain;

[User] Show only the chains where the average pnl is greater than 10000.

[Assistant]
SELECT chain, AVG(realized_ratio) AS avg_realized_ratio, AVG(pnl) AS avg_pnl
FROM smart_money_token_performance
GROUP BY chain
HAVING AVG(pnl) > 10000;


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
// Use Hashes to store station details. Key format: station:<station_id>
// Example:
// HSET station:station_xyz station_id "station_xyz" station_name "Grand Central Terminal" city "New York" state_province "NY" country_code "USA" address "89 E 42nd St..." timezone "America/New_York" number_of_platforms 44 created_at "2023-01-15T10:00:00Z" last_updated_at "2023-10-28T15:30:00Z"

// To quickly find stations by city (optional index):
// SADD stations:city:NewYork station:station_xyz
// Use Hashes for platform details. Key format: platform:<platform_id>
// HSET platform:plat_123 platform_id "plat_123" station_id "station_xyz" platform_number "1A" track_number "T1" status "Operational" length_meters 250.50 accessible 1

// To link platforms to stations (optional):
// SADD station:station_xyz:platforms platform:plat_123 platform:plat_456
// Use Hashes for train details. Key format: train:<train_id>
// HSET train:train_789 train_id "train_789" train_number "Acela 2151" model "Siemens Velaro" ... status "Active" ...

// To find train by train_number (optional index):
// SET train_number:"Acela 2151" train:train_789
// Use Hashes for car details. Key format: car:<car_id>
// HSET car:car_abc car_id "car_abc" train_id "train_789" car_number "C3" car_type "Passenger" class "Business" capacity 60 features "WiFi,Power Outlet"

// To link cars to trains (optional):
// SADD train:train_789:cars car:car_abc car:car_def
// Use Hashes for route details. Key format: route:<route_id>
// HSET route:route_ne_corr route_id "route_ne_corr" route_name "Northeast Corridor" ... origin_station_id "station_bos" ... is_active 1
// Use Hashes for details. Key format: route_station:<route_station_id>
// HSET route_station:rs_ne_1 route_station_id "rs_ne_1" route_id "route_ne_corr" station_id "station_bos" sequence_order 1 ...

// To find stops for a route, use a Sorted Set (score by sequence_order):
// ZADD route:route_ne_corr:stops 1 route_station:rs_ne_1
// ZADD route:route_ne_corr:stops 2 route_station:rs_ne_2
// Use Hashes for passenger details. Key format: passenger:<passenger_id>
// HSET passenger:pass_pqr passenger_id "pass_pqr" first_name "Alice" last_name "Smith" email "alice.smith@example.com" ...

// To find passenger by email (optional index):
// SET passenger_email:"alice.smith@example.com" passenger:pass_pqr
// Use Hashes for booking details. Key format: booking:<booking_id>
// HSET booking:book_zyx booking_id "book_zyx" passenger_id "pass_pqr" schedule_id "sched_1122" ... status "Confirmed" ...

// To link bookings to passengers/schedules (optional):
// SADD passenger:pass_pqr:bookings booking:book_zyx
// SADD schedule:sched_1122:bookings booking:book_zyx
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...

// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b

[User] 能否帮我统计特定车站(station_id 为 'station_xyz')的所有平台数量？

[Assistant] SCARD station:station_xyz:platforms


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.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 distinct patient IDs who have received a diagnosis from a doctor with 'Cardiology' specialty.

[Assistant] SELECT DISTINCT T1.patient_id FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id WHERE T2.specialty = 'Cardiology';

[User] For these patients, also show their primary insurance policy number.

[Assistant] SELECT DISTINCT T1.patient_id, T3.policy_number FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id JOIN healthcare.patient_insurance AS T3 ON T1.patient_id = T3.patient_id WHERE T2.specialty = 'Cardiology' AND T3.is_primary = true;

[User] Only include patients whose 'Cardiology' diagnosis was made in the last year.

[Assistant] SELECT DISTINCT T1.patient_id, T3.policy_number FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id JOIN healthcare.patient_insurance AS T3 ON T1.patient_id = T3.patient_id WHERE T2.specialty = 'Cardiology' AND T3.is_primary = true AND T1.diagnosis_date >= date('now', '-1 year');


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] Get a list of users who have both read and unread notifications. For each user, show their user_id, the count of unread notifications as unread_count, and the count of read notifications as read_count.

[Assistant]
SELECT unread.user_id, unread.unread_count, read_counts.read_count
FROM (
  SELECT user_id, COUNT(*) AS unread_count
  FROM trading_platform.notifications
  WHERE read_at IS NULL
  GROUP BY user_id
) AS unread
JOIN (
  SELECT user_id, COUNT(*) AS read_count
  FROM trading_platform.notifications
  WHERE read_at IS NOT NULL
  GROUP BY user_id
) AS read_counts
ON unread.user_id = read_counts.user_id;

[User] Actually, I want to filter to only include those users whose unread_count is at least 3.

[Assistant]
SELECT unread.user_id, unread.unread_count, read_counts.read_count
FROM (
  SELECT user_id, COUNT(*) AS unread_count
  FROM trading_platform.notifications
  WHERE read_at IS NULL
  GROUP BY user_id
  HAVING COUNT(*) >= 3
) AS unread
JOIN (
  SELECT user_id, COUNT(*) AS read_count
  FROM trading_platform.notifications
  WHERE read_at IS NOT NULL
  GROUP BY user_id
) AS read_counts
ON unread.user_id = read_counts.user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.developers (
    developer_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the developer studio
    name character varying(150) NOT NULL UNIQUE, -- name of the development studio
    country character varying(100), -- country where the studio is based
    founded_year integer, -- year the studio was founded
    website character varying(255), -- developer's official website
    created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (developer_id)
)
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
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] Show me all in-game items with the word 'Sword' in their name along with the total number of sessions in those games.

[Assistant]
SELECT i.item_id, i.item_name, COUNT(s.session_id) AS session_count
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.game_sessions s ON i.game_id = s.game_id
WHERE i.item_name ILIKE '%Sword%'
GROUP BY i.item_id, i.item_name;

[User] Please also display the average score for sessions in each item’s game.

[Assistant]
SELECT i.item_id, i.item_name, COUNT(s.session_id) AS session_count, AVG(s.score) AS avg_score
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.game_sessions s ON i.game_id = s.game_id
WHERE i.item_name ILIKE '%Sword%'
GROUP BY i.item_id, i.item_name;

[User] I'm getting incorrect averages, maybe due to sessions without a score. Could you ensure that only non-null scores are included in the average calculation?

[Assistant]
SELECT i.item_id, i.item_name, COUNT(s.session_id) AS session_count, AVG(s.score) FILTER (WHERE s.score IS NOT NULL) AS avg_score
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.game_sessions s ON i.game_id = s.game_id
WHERE i.item_name ILIKE '%Sword%'
GROUP BY i.item_id, i.item_name;

[User] Also show the rarity of each item and only include those where avg_score is at least 200.

[Assistant]
SELECT i.item_id, i.item_name, i.rarity, COUNT(s.session_id) AS session_count, AVG(s.score) FILTER (WHERE s.score IS NOT NULL) AS avg_score
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.game_sessions s ON i.game_id = s.game_id
WHERE i.item_name ILIKE '%Sword%'
GROUP BY i.item_id, i.item_name, i.rarity
HAVING AVG(s.score) FILTER (WHERE s.score IS NOT NULL) >= 200;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )

[User] Show all routes where the estimated duration is at least 120 minutes including their route number, type, and origin and destination location IDs.

[Assistant]
SELECT route_number, type, origin_location_id, destination_location_id
FROM transportation.routes
WHERE estimated_duration_minutes >= 120;

[User] Can you also include the distance in kilometers in the result?

[Assistant]
SELECT route_number, type, origin_location_id, destination_location_id, distance_km
FROM transportation.routes
WHERE estimated_duration_minutes >= 120;

[User] I would like to see the results ordered by distance in descending order.

[Assistant]
SELECT route_number, type, origin_location_id, destination_location_id, distance_km
FROM transportation.routes
WHERE estimated_duration_minutes >= 120
ORDER BY distance_km DESC;

[User] Actually, please only show routes where the type is 'Intercity'.

[Assistant]
SELECT route_number, type, origin_location_id, destination_location_id, distance_km
FROM transportation.routes
WHERE estimated_duration_minutes >= 120 AND type = 'Intercity'
ORDER BY distance_km DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )

[User] List all top-level comments, showing their ID, post ID, user ID, and content.

[Assistant] SELECT comment_id, post_id, user_id, content FROM social_media.comments WHERE parent_comment_id IS NULL;

[User] From those, show only the ones made after June 1st, 2024.

[Assistant] SELECT comment_id, post_id, user_id, content FROM social_media.comments WHERE parent_comment_id IS NULL AND created_at > '2024-06-01';

[User] Now, for these top-level comments, can you list any replies they have received, showing the reply's ID, content, and the user ID of the reply author?

[Assistant] SELECT c.comment_id AS top_level_comment_id, r.comment_id AS reply_id, r.content AS reply_content, r.user_id AS reply_user_id FROM social_media.comments c JOIN social_media.comments r ON c.comment_id = r.parent_comment_id WHERE c.parent_comment_id IS NULL AND c.created_at > '2024-06-01';


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

[User] Find users who followed at least two different people on the same calendar day. For each such user, list their ID, the IDs of the two people they followed, and the creation times of those two follow events.

[Assistant] SELECT f1.follower_user_id, f1.following_user_id AS followed_user_1_id, f2.following_user_id AS followed_user_2_id, f1.created_at AS follow_1_created_at, f2.created_at AS follow_2_created_at FROM social_media.follows AS f1 JOIN social_media.follows AS f2 ON f1.follower_user_id = f2.follower_user_id WHERE f1.following_user_id != f2.following_user_id AND DATE(f1.created_at) = DATE(f2.created_at);

[User] Also, only include pairs of follows where the two follow events happened within 30 minutes of each other on that same day.

[Assistant] SELECT f1.follower_user_id, f1.following_user_id AS followed_user_1_id, f2.following_user_id AS followed_user_2_id, f1.created_at AS follow_1_created_at, f2.created_at AS follow_2_created_at FROM social_media.follows AS f1 JOIN social_media.follows AS f2 ON f1.follower_user_id = f2.follower_user_id WHERE f1.following_user_id != f2.following_user_id AND DATE(f1.created_at) = DATE(f2.created_at) AND ABS(EXTRACT(EPOCH FROM (f1.created_at - f2.created_at))) <= 1800;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_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 (property_id) )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )

[User] Get each staff member who delivered service orders in the last month and the count of orders they delivered.

[Assistant]
SELECT s.staff_id,
       s.first_name,
       s.last_name,
       COUNT(so.order_id) AS delivered_orders
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.staff s ON so.staff_id_delivered = s.staff_id
WHERE so.delivery_timestamp >= date_trunc('month', current_date) - INTERVAL '1 month'
  AND so.delivery_timestamp < date_trunc('month', current_date)
GROUP BY s.staff_id, s.first_name, s.last_name;

[User] Actually, only include staff who delivered more than 5 orders and order the result by delivered_orders descending.

[Assistant]
SELECT s.staff_id,
       s.first_name,
       s.last_name,
       COUNT(so.order_id) AS delivered_orders
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.staff s ON so.staff_id_delivered = s.staff_id
WHERE so.delivery_timestamp >= date_trunc('month', current_date) - INTERVAL '1 month'
  AND so.delivery_timestamp < date_trunc('month', current_date)
GROUP BY s.staff_id, s.first_name, s.last_name
HAVING COUNT(so.order_id) > 5
ORDER BY delivered_orders DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )

[User] For each reservation, find the next reservation made by the same guest and calculate the gap in days between them.

[Assistant] select r1.reservation_id as current_reservation_id, r2.reservation_id as next_reservation_id, r2.check_in_date - r1.check_out_date as gap_days from hospitality_technology.reservations r1 join hospitality_technology.reservations r2 on r1.guest_id = r2.guest_id and r2.check_in_date > r1.check_out_date where not exists (select 1 from hospitality_technology.reservations r3 where r3.guest_id = r1.guest_id and r3.check_in_date > r1.check_out_date and r3.check_in_date < r2.check_in_date) order by r1.guest_id, gap_days;

[User] Only include pairs where the next reservation status is 'Confirmed'.

[Assistant] select r1.reservation_id as current_reservation_id, r2.reservation_id as next_reservation_id, r2.check_in_date - r1.check_out_date as gap_days from hospitality_technology.reservations r1 join hospitality_technology.reservations r2 on r1.guest_id = r2.guest_id and r2.check_in_date > r1.check_out_date and r2.status = 'Confirmed' where not exists (select 1 from hospitality_technology.reservations r3 where r3.guest_id = r1.guest_id and r3.check_in_date > r1.check_out_date and r3.check_in_date < r2.check_in_date) order by r1.guest_id, gap_days;

[User] Also, only show those with gap_days less than or equal to 7, sorted by gap_days ascending, and limit to 5 results.

[Assistant] select r1.reservation_id as current_reservation_id, r2.reservation_id as next_reservation_id, r2.check_in_date - r1.check_out_date as gap_days from hospitality_technology.reservations r1 join hospitality_technology.reservations r2 on r1.guest_id = r2.guest_id and r2.check_in_date > r1.check_out_date and r2.status = 'Confirmed' where not exists (select 1 from hospitality_technology.reservations r3 where r3.guest_id = r1.guest_id and r3.check_in_date > r1.check_out_date and r3.check_in_date < r2.check_in_date) and r2.check_in_date - r1.check_out_date <= 7 order by gap_days asc limit 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )

[User] Show me all doctors who are affiliated with 'hospital_123', including their full names and specialties.

[Assistant] SELECT first_name, last_name, specialty FROM healthcare.doctors WHERE hospital_affiliation_id = 'hospital_123';

[User] Can you also include their phone numbers and email addresses in the result?

[Assistant] SELECT first_name, last_name, specialty, phone_number, email FROM healthcare.doctors WHERE hospital_affiliation_id = 'hospital_123';

[User] Only show doctors whose specialty is 'Pediatrics'.

[Assistant] SELECT first_name, last_name, specialty, phone_number, email FROM healthcare.doctors WHERE hospital_affiliation_id = 'hospital_123' AND specialty = 'Pediatrics';

[User] I got an error that says column 'speciality' does not exist. Can you check and fix the query?

[Assistant] SELECT first_name, last_name, specialty, phone_number, email FROM healthcare.doctors WHERE hospital_affiliation_id = 'hospital_123' AND specialty = 'Pediatrics';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
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.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 the route number and description for routes that have bookings associated with them.

[Assistant] SELECT DISTINCT T1.route_number, T1.description FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id;

[User] For these routes, what is the average fare of the associated bookings?

[Assistant] SELECT T1.route_number, AVG(T2.fare) FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id GROUP BY T1.route_number;

[User] Also, only include routes where the average fare is greater than 75.

[Assistant] SELECT T1.route_number, AVG(T2.fare) FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id GROUP BY T1.route_number HAVING AVG(T2.fare) > 75;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )

[User] Show me the case number and case name for all cases, along with the full name of the lawyer who uploaded any document related to those cases.

[Assistant]
SELECT c.case_number, c.case_name, l.first_name || ' ' || l.last_name AS lawyer_full_name
FROM legal_services.cases c
JOIN legal_services.documents d ON c.case_id = d.case_id
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id;

[User] Please also include the document name and the time it was uploaded.

[Assistant]
SELECT c.case_number, c.case_name, l.first_name || ' ' || l.last_name AS lawyer_full_name, d.document_name, d.upload_timestamp
FROM legal_services.cases c
JOIN legal_services.documents d ON c.case_id = d.case_id
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id;

[User] Can you limit this to only documents that were uploaded on or after January 1, 2024?

[Assistant]
SELECT c.case_number, c.case_name, l.first_name || ' ' || l.last_name AS lawyer_full_name, d.document_name, d.upload_timestamp
FROM legal_services.cases c
JOIN legal_services.documents d ON c.case_id = d.case_id
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
WHERE d.upload_timestamp >= '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )

[User] List pairs of group conversations that were created on the same calendar day, showing their IDs and creation times.

[Assistant] SELECT T1.conversation_id AS convo1_id, T1.created_at AS convo1_created_at, T2.conversation_id AS convo2_id, T2.created_at AS convo2_created_at FROM social_media.conversations AS T1 JOIN social_media.conversations AS T2 ON DATE(T1.created_at) = DATE(T2.created_at) AND T1.conversation_id < T2.conversation_id WHERE T1.is_group_chat = true AND T2.is_group_chat = true

[User] Only include pairs where the conversation IDs both start with 'G' and order by the creation time descending.

[Assistant] SELECT T1.conversation_id AS convo1_id, T1.created_at AS convo1_created_at, T2.conversation_id AS convo2_id, T2.created_at AS convo2_created_at FROM social_media.conversations AS T1 JOIN social_media.conversations AS T2 ON DATE(T1.created_at) = DATE(T2.created_at) AND T1.conversation_id < T2.conversation_id WHERE T1.is_group_chat = true AND T2.is_group_chat = true AND T1.conversation_id LIKE 'G%' AND T2.conversation_id LIKE 'G%' ORDER BY T1.created_at DESC


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

[User] List all appointments that have a location specified and their status is not 'Cancelled'. Show the appointment ID, subject, and location.

[Assistant] SELECT appointment_id, subject, location FROM legal_services.appointments WHERE location IS NOT NULL AND status <> 'Cancelled';

[User] Also, include appointments that have a case ID assigned. Order the final list by start time ascending.

[Assistant] SELECT appointment_id, subject, location FROM legal_services.appointments WHERE (location IS NOT NULL AND status <> 'Cancelled') OR case_id IS NOT NULL ORDER BY start_time ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )

[User] How many passengers were born in each year? Please show the birth year and the count.

[Assistant] SELECT EXTRACT(YEAR FROM date_of_birth) AS birth_year ,  COUNT(*) AS passenger_count FROM transportation.passengers WHERE date_of_birth IS NOT NULL GROUP BY birth_year ORDER BY birth_year

[User] Filter this list to include only years where more than 50 passengers were born, and order by the number of passengers descending.

[Assistant] SELECT EXTRACT(YEAR FROM date_of_birth) AS birth_year ,  COUNT(*) AS passenger_count FROM transportation.passengers WHERE date_of_birth IS NOT NULL GROUP BY birth_year HAVING COUNT(*)  >  50 ORDER BY passenger_count DESC


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.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] Show me the post_id, content, author's username, and the number of comments for each post where media_type is 'video'.

[Assistant]
SELECT p.post_id, p.content, u.username, COUNT(c.comment_id) AS comment_count
FROM social_media.posts p
JOIN social_media.users u ON p.user_id = u.user_id
LEFT JOIN social_media.comments c ON p.post_id = c.post_id
WHERE p.media_type = 'video'
GROUP BY p.post_id, p.content, u.username;

[User] Actually, only include posts created in the last 30 days and order the results by comment_count descending.

[Assistant]
SELECT p.post_id, p.content, u.username, COUNT(c.comment_id) AS comment_count
FROM social_media.posts p
JOIN social_media.users u ON p.user_id = u.user_id
LEFT JOIN social_media.comments c ON p.post_id = c.post_id
WHERE p.media_type = 'video'
  AND p.created_at >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY p.post_id, p.content, u.username
ORDER BY comment_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.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 NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )

[User] Which players have played sessions on more than one distinct game? Show their player_id, username, and the number of unique games they've played.

[Assistant]
SELECT p.player_id, p.username, COUNT(DISTINCT gs.game_id) AS unique_games_played
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.players p ON gs.player_id = p.player_id
GROUP BY p.player_id, p.username
HAVING COUNT(DISTINCT gs.game_id) > 1;

[User] For these players, also show the total number of sessions they've played.

[Assistant]
SELECT p.player_id, p.username, COUNT(DISTINCT gs.game_id) AS unique_games_played, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.players p ON gs.player_id = p.player_id
GROUP BY p.player_id, p.username
HAVING COUNT(DISTINCT gs.game_id) > 1;

[User] Now restrict it to players who registered after 2022-06-01.

[Assistant]
SELECT p.player_id, p.username, COUNT(DISTINCT gs.game_id) AS unique_games_played, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.players p ON gs.player_id = p.player_id
WHERE p.registration_date > '2022-06-01'
GROUP BY p.player_id, p.username
HAVING COUNT(DISTINCT gs.game_id) > 1;

[User] Order by unique_games_played descending, then by total_sessions descending. Limit the list to 10 players.

[Assistant]
SELECT p.player_id, p.username, COUNT(DISTINCT gs.game_id) AS unique_games_played, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.players p ON gs.player_id = p.player_id
WHERE p.registration_date > '2022-06-01'
GROUP BY p.player_id, p.username
HAVING COUNT(DISTINCT gs.game_id) > 1
ORDER BY unique_games_played DESC, total_sessions DESC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )

[User] I need to see claims where the incident date is in 2023. Show the claim ID, incident date, and customer ID.

[Assistant] SELECT claim_id, incident_date, customer_id FROM insurance.claims WHERE incident_date >= '2023-01-01' AND incident_date < '2024-01-01'

[User] Can you also include the status and filter the results to only show claims with an estimated loss greater than 5000?

[Assistant] SELECT claim_id, incident_date, customer_id, status FROM insurance.claims WHERE incident_date >= '2023-01-01' AND incident_date < '2024-01-01' AND estimated_loss > 5000

[User] Actually, I only want claims where the status is 'Approved' or 'Settled'.

[Assistant] SELECT claim_id, incident_date, customer_id, status FROM insurance.claims WHERE incident_date >= '2023-01-01' AND incident_date < '2024-01-01' AND estimated_loss > 5000 AND status IN ('Approved', 'Settled')

[User] For those claims, also include the settlement amount and order the results by settlement amount descending.

[Assistant] SELECT claim_id, incident_date, customer_id, status, settlement_amount FROM insurance.claims WHERE incident_date >= '2023-01-01' AND incident_date < '2024-01-01' AND estimated_loss > 5000 AND status IN ('Approved', 'Settled') ORDER BY settlement_amount DESC


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
CREATE TABLE financial_services.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
CREATE TABLE financial_services.securities ( security_id text PRIMARY KEY, 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 )
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )
CREATE TABLE financial_services.loans (
    loan_id character varying(64) NOT NULL, -- unique identifier for the loan, could be same as account_id
    account_id character varying(64) NOT NULL UNIQUE, -- link to the general account record
    loan_type character varying(50) NOT NULL, -- e.g., Mortgage, Personal, Auto, Student
    principal_amount numeric(19, 4) NOT NULL, -- original loan amount
    current_principal_balance numeric(19, 4) NOT NULL, -- remaining principal
    interest_rate numeric(6, 4) NOT NULL, -- annual interest rate
    term_months integer NOT NULL, -- loan term in months
    origination_date date NOT NULL, -- date the loan was disbursed
    maturity_date date NOT NULL, -- date the loan is due to be fully repaid
    monthly_payment numeric(12, 4), -- scheduled monthly payment amount
    collateral_description text, -- description of collateral, if secured loan
    status character varying(32) NOT NULL, -- e.g., Active, Paid Off, Defaulted
    PRIMARY KEY (loan_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id)
)

[User] Provide the average high price for securities on each exchange, using market data from the last 6 months.

[Assistant] SELECT s.exchange, AVG(md.high_price) AS average_high_price FROM financial_services.market_data AS md JOIN financial_services.securities AS s ON md.security_id = s.security_id WHERE md.data_timestamp >= CURRENT_DATE - INTERVAL '6 month' GROUP BY s.exchange;

[User] Exclude any exchanges where the total trading volume in this period is less than 1,000,000.

[Assistant] SELECT s.exchange, AVG(md.high_price) AS average_high_price FROM financial_services.market_data AS md JOIN financial_services.securities AS s ON md.security_id = s.security_id WHERE md.data_timestamp >= CURRENT_DATE - INTERVAL '6 month' GROUP BY s.exchange HAVING SUM(md.volume) >= 1000000;

[User] Order the results by the average high price in descending order.

[Assistant] SELECT s.exchange, AVG(md.high_price) AS average_high_price FROM financial_services.market_data AS md JOIN financial_services.securities AS s ON md.security_id = s.security_id WHERE md.data_timestamp >= CURRENT_DATE - INTERVAL '6 month' GROUP BY s.exchange HAVING SUM(md.volume) >= 1000000 ORDER BY average_high_price DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
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.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid, player_id uuid, item_id uuid, quantity integer, acquired_at timestamp with time zone, instance_data jsonb )

[User] List the names and types of all in-game items that have a rarity of 'Epic'.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic';

[User] Further restrict the list to only include items of item_type 'Weapon'.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon';

[User] Order these results by their cost_amount in descending order.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon' ORDER BY cost_amount DESC;

[User] Please also include the cost_currency and cost_amount in the output.

[Assistant] SELECT item_name, item_type, cost_currency, cost_amount FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon' ORDER BY cost_amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)

[User] Can you give me all medical records where the assessment field is not null and not empty?

[Assistant] SELECT record_id, patient_id, doctor_id, record_date, assessment FROM healthcare.medical_records WHERE assessment IS NOT NULL AND assessment <> '';

[User] Now, only show those made in the last 90 days.

[Assistant] SELECT record_id, patient_id, doctor_id, record_date, assessment FROM healthcare.medical_records WHERE assessment IS NOT NULL AND assessment <> '' AND record_date >= (CURRENT_DATE - INTERVAL '90 days');


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)

[User] I want a summary for each user showing their total buy value and total sell value across all trades.

[Assistant]
SELECT
  COALESCE(b.user_id, s.user_id) AS user_id,
  COALESCE(b.total_buy, 0) AS total_buy_value,
  COALESCE(s.total_sell, 0) AS total_sell_value
FROM
  (
    SELECT buyer_id AS user_id, SUM(quantity * price) AS total_buy
    FROM trading_platform.trades
    GROUP BY buyer_id
  ) b
FULL OUTER JOIN
  (
    SELECT seller_id AS user_id, SUM(quantity * price) AS total_sell
    FROM trading_platform.trades
    GROUP BY seller_id
  ) s
ON b.user_id = s.user_id;

[User] Actually, I only care about users who have both bought and sold assets.

[Assistant]
SELECT
  b.user_id,
  b.total_buy AS total_buy_value,
  s.total_sell AS total_sell_value
FROM
  (
    SELECT buyer_id AS user_id, SUM(quantity * price) AS total_buy
    FROM trading_platform.trades
    GROUP BY buyer_id
  ) b
INNER JOIN
  (
    SELECT seller_id AS user_id, SUM(quantity * price) AS total_sell
    FROM trading_platform.trades
    GROUP BY seller_id
  ) s
ON b.user_id = s.user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id text, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )

[User] For each network, list the deployer address and the number of contracts they have deployed, ordered from most to least.

[Assistant] SELECT network_id, deployer_address, COUNT(*) AS deployed_contracts FROM web3.contracts GROUP BY network_id, deployer_address ORDER BY network_id, deployed_contracts DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )

[User] Show me the total count and sum of amounts for spent and unspent UTXOs for each asset, including the asset name and symbol.

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol, u.spent, COUNT(*) AS utxo_count, SUM(u.amount) AS total_amount
FROM trading_platform.assets a
LEFT JOIN trading_platform.utxos u
  ON a.asset_id = u.transaction_id
GROUP BY a.asset_id, a.name, a.symbol, u.spent
ORDER BY a.asset_id, u.spent;

[User] I'd like to see only assets where the sum of amounts for spent UTXOs is at least 100. Also, show only the spent UTXOs.

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol, SUM(u.amount) AS spent_total_amount
FROM trading_platform.assets a
JOIN trading_platform.utxos u ON a.asset_id = u.transaction_id
WHERE u.spent = true
GROUP BY a.asset_id, a.name, a.symbol
HAVING SUM(u.amount) >= 100
ORDER BY spent_total_amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] List all insurance products that have a base premium greater than 1000 and are currently active, showing product name, type, and base premium.

[Assistant] SELECT product_name, product_type, base_premium FROM insurance.insurance_products WHERE base_premium > 1000 AND is_active = TRUE

[User] Now, find policies associated with these products that were issued in 2024, showing the policy number and its premium amount.

[Assistant] SELECT p.policy_number, p.premium_amount FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE ip.base_premium > 1000 AND ip.is_active = TRUE AND date_part('year', p.issued_at) = 2024


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text PRIMARY KEY, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )

[User] List all accounts with a balance below 1000, showing the account_id, account_number, and currency.

[Assistant]
SELECT account_id, account_number, currency
FROM financial_services.accounts
WHERE balance < 1000;

[User] Now, also include accounts with a negative balance and order the result by balance ascending.

[Assistant]
SELECT account_id, account_number, currency, balance
FROM financial_services.accounts
WHERE balance < 1000 OR balance < 0
ORDER BY balance ASC;

[User] I only want to see the accounts where status is not 'Closed'.

[Assistant]
SELECT account_id, account_number, currency, balance
FROM financial_services.accounts
WHERE (balance < 1000 OR balance < 0) AND status <> 'Closed'
ORDER BY balance ASC;