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.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)

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

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

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

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

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

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

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

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

[User] For every game, can you provide the count of unique item types and the average item cost?

[Assistant] SELECT game_id, COUNT(DISTINCT item_type) AS num_unique_types, AVG(cost_amount) AS avg_item_cost FROM gaming_technology.in_game_items GROUP BY game_id;

[User] Could you also add the lowest item cost for each game?

[Assistant] SELECT game_id, COUNT(DISTINCT item_type) AS num_unique_types, AVG(cost_amount) AS avg_item_cost, MIN(cost_amount) AS min_item_cost FROM gaming_technology.in_game_items GROUP BY game_id;

[User] Now, please only show games with at least 2 different item types.

[Assistant] SELECT game_id, COUNT(DISTINCT item_type) AS num_unique_types, AVG(cost_amount) AS avg_item_cost, MIN(cost_amount) AS min_item_cost FROM gaming_technology.in_game_items GROUP BY game_id HAVING COUNT(DISTINCT item_type) >= 2;

[User] List the names and rarity of all items with a cost above 50.

[Assistant]
SELECT item_name, rarity
FROM gaming_technology.in_game_items
WHERE cost_amount > 50;

[User] Now, only include items where the rarity is 'Epic' or 'Legendary'.

[Assistant]
SELECT item_name, rarity
FROM gaming_technology.in_game_items
WHERE cost_amount > 50
AND rarity IN ('Epic', 'Legendary');

[User] Also show the item_type and order by cost_amount descending.

[Assistant]
SELECT item_name, item_type, rarity, cost_amount
FROM gaming_technology.in_game_items
WHERE cost_amount > 50
AND rarity IN ('Epic', 'Legendary')
ORDER BY cost_amount DESC;

[User] Can you show me the number of items per rarity and item type combination, along with the minimum and maximum cost for each group?

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost FROM gaming_technology.in_game_items GROUP BY item_type, rarity;

[User] Could you only show the combinations where there are more than 2 items in that group?

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost FROM gaming_technology.in_game_items GROUP BY item_type, rarity HAVING COUNT(*) > 2;

[User] Additionally, can you add the average cost for each group to the results?

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost, AVG(cost_amount) AS avg_cost FROM gaming_technology.in_game_items GROUP BY item_type, rarity HAVING COUNT(*) > 2;

[User] Now, please only include groups where rarity is not null and order the output by avg_cost descending.

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost, AVG(cost_amount) AS avg_cost FROM gaming_technology.in_game_items WHERE rarity IS NOT NULL GROUP BY item_type, rarity HAVING COUNT(*) > 2 ORDER BY avg_cost 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.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )

[User] Show me each staff member's first and last name along with their manager's first and last name.

[Assistant]
SELECT s.staff_id,
       s.first_name,
       s.last_name,
       m.staff_id AS manager_id,
       m.first_name AS manager_first_name,
       m.last_name AS manager_last_name
FROM hospitality_technology.staff AS s
LEFT JOIN hospitality_technology.staff AS m
  ON s.manager_id = m.staff_id;

[User] Actually, only include active staff and their active managers and sort by the staff last name.

[Assistant]
SELECT s.staff_id,
       s.first_name,
       s.last_name,
       m.staff_id AS manager_id,
       m.first_name AS manager_first_name,
       m.last_name AS manager_last_name
FROM hospitality_technology.staff AS s
LEFT JOIN hospitality_technology.staff AS m
  ON s.manager_id = m.staff_id
WHERE s.is_active = true
  AND m.is_active = true
ORDER BY s.last_name;

[User] List all staff members along with their direct manager's first and last names.

[Assistant]
SELECT s.staff_id,
       s.first_name AS staff_first_name,
       s.last_name AS staff_last_name,
       m.first_name AS manager_first_name,
       m.last_name AS manager_last_name
FROM hospitality_technology.staff s
LEFT JOIN hospitality_technology.staff m
  ON s.manager_id = m.staff_id;

[User] Show me all active staff including their staff_id, first_name, last_name, position, and work_email.

[Assistant]
SELECT staff_id,
       first_name,
       last_name,
       position,
       work_email
FROM hospitality_technology.staff
WHERE is_active = true;

[User] Actually, I need the results sorted by hire_date descending.

[Assistant]
SELECT staff_id,
       first_name,
       last_name,
       position,
       work_email
FROM hospitality_technology.staff
WHERE is_active = true
ORDER BY hire_date DESC;

[User] Show me the email addresses and hire dates for all staff who have a manager.

[Assistant]
SELECT work_email, hire_date
FROM hospitality_technology.staff
WHERE manager_id IS NOT NULL;

[User] Only include staff who were hired after January 1, 2023.

[Assistant]
SELECT work_email, hire_date
FROM hospitality_technology.staff
WHERE manager_id IS NOT NULL AND hire_date > '2023-01-01';

[User] What is the number of active staff members in each position?

[Assistant]
SELECT position,
       COUNT(*) AS staff_count
FROM hospitality_technology.staff
WHERE is_active = true
GROUP BY position;

[User] Now, only include positions with more than 3 active staff and order the result by staff_count descending.

[Assistant]
SELECT position,
       COUNT(*) AS staff_count
FROM hospitality_technology.staff
WHERE is_active = true
GROUP BY position
HAVING COUNT(*) > 3
ORDER BY staff_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 cex_token_balance ( snapshot_time.text, chain.text, address.text, exchange.text, token_address.text, token_symbol.text, balance.numeric, usd_value.numeric, price.numeric )

[User] Which exchanges hold the largest total USD value of tokens on the BSC chain in the most recent snapshot, and what is the top token (by usd_value) held by each exchange?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT
    c.exchange,
    SUM(c.usd_value) AS total_usd_value
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
  GROUP BY c.exchange
),
top_token_per_exchange AS (
  SELECT c.exchange, c.token_symbol, c.usd_value, ROW_NUMBER() OVER (PARTITION BY c.exchange ORDER BY c.usd_value DESC) AS rn
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
)
SELECT
  t.exchange,
  e.total_usd_value,
  t.token_symbol AS top_token_symbol,
  t.usd_value AS top_token_usd_value
FROM exchange_totals e
JOIN top_token_per_exchange t ON e.exchange = t.exchange AND t.rn = 1
ORDER BY e.total_usd_value DESC;

[User] Can you add the number of distinct tokens each exchange holds on BSC in the latest snapshot to the result?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT
    c.exchange,
    SUM(c.usd_value) AS total_usd_value,
    COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
  GROUP BY c.exchange
),
top_token_per_exchange AS (
  SELECT c.exchange, c.token_symbol, c.usd_value, ROW_NUMBER() OVER (PARTITION BY c.exchange ORDER BY c.usd_value DESC) AS rn
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
)
SELECT
  t.exchange,
  e.total_usd_value,
  e.token_count,
  t.token_symbol AS top_token_symbol,
  t.usd_value AS top_token_usd_value
FROM exchange_totals e
JOIN top_token_per_exchange t ON e.exchange = t.exchange AND t.rn = 1
ORDER BY e.total_usd_value DESC;

[User] I'd like the results filtered so only exchanges holding more than $2,000,000 in total on BSC are included.

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT
    c.exchange,
    SUM(c.usd_value) AS total_usd_value,
    COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
  GROUP BY c.exchange
  HAVING SUM(c.usd_value) > 2000000
),
top_token_per_exchange AS (
  SELECT c.exchange, c.token_symbol, c.usd_value, ROW_NUMBER() OVER (PARTITION BY c.exchange ORDER BY c.usd_value DESC) AS rn
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
)
SELECT
  t.exchange,
  e.total_usd_value,
  e.token_count,
  t.token_symbol AS top_token_symbol,
  t.usd_value AS top_token_usd_value
FROM exchange_totals e
JOIN top_token_per_exchange t ON e.exchange = t.exchange AND t.rn = 1
ORDER BY e.total_usd_value DESC;

[User] How many unique tokens are recorded for each chain in the latest snapshot in cex_token_balance?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
)
SELECT
  chain,
  COUNT(DISTINCT token_symbol) AS unique_token_count
FROM cex_token_balance c
JOIN latest_snapshot l ON c.snapshot_time = l.max_time
GROUP BY chain
ORDER BY unique_token_count DESC;

[User] What is the total USD value of tokens held by each exchange on Ethereum and Polygon chains in the latest snapshot? Please show exchange, chain, and total usd_value.

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
)
SELECT
  exchange,
  chain,
  SUM(usd_value) AS total_usd_value
FROM cex_token_balance c
JOIN latest_snapshot l ON c.snapshot_time = l.max_time
WHERE chain IN ('Ethereum', 'Polygon')
GROUP BY exchange, chain
ORDER BY chain, total_usd_value DESC;

[User] Can you add the number of distinct tokens each exchange holds on those chains to the result?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
)
SELECT
  exchange,
  chain,
  SUM(usd_value) AS total_usd_value,
  COUNT(DISTINCT token_symbol) AS token_count
FROM cex_token_balance c
JOIN latest_snapshot l ON c.snapshot_time = l.max_time
WHERE chain IN ('Ethereum', 'Polygon')
GROUP BY exchange, chain
ORDER BY chain, total_usd_value DESC;

[User] Only show exchanges where total USD value is greater than 5 million on either chain, and order the results by total_usd_value descending.

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_usd_values AS (
  SELECT
    exchange,
    chain,
    SUM(usd_value) AS total_usd_value,
    COUNT(DISTINCT token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE chain IN ('Ethereum', 'Polygon')
  GROUP BY exchange, chain
)
SELECT
  exchange,
  chain,
  total_usd_value,
  token_count
FROM exchange_usd_values
WHERE total_usd_value > 5000000
ORDER BY total_usd_value DESC;

[User] Show me the top 5 tokens by USD value held on the Binance Smart Chain, along with their average price and total balance.

[Assistant] SELECT token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Binance Smart Chain' GROUP BY token_symbol ORDER BY total_usd_value DESC LIMIT 5;

[User] Actually, I want to see this for the Polygon chain instead, and only include tokens with a total balance over 1000.

[Assistant] SELECT token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol HAVING SUM(balance) > 1000 ORDER BY total_usd_value DESC LIMIT 5;

[User] Can you add the exchange name to these results and filter to only show Binance holdings?

[Assistant] SELECT exchange, token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND exchange = 'Binance' GROUP BY exchange, token_symbol HAVING SUM(balance) > 1000 ORDER BY total_usd_value DESC LIMIT 5;

[User] Now order these results by total balance instead of USD value.

[Assistant] SELECT exchange, token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND exchange = 'Binance' GROUP BY exchange, token_symbol HAVING SUM(balance) > 1000 ORDER BY total_balance DESC 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 gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )

[User] Could you list each player's username and the total number of sessions they have played?

[Assistant]
SELECT p.username, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.players p
LEFT JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
GROUP BY p.username;

[User] Now I only want players registered after '2022-01-01'.

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

[User] Actually, also include their country_code and order the results by total_sessions descending.

[Assistant]
SELECT p.username,
       p.country_code,
       COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.players p
LEFT JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
WHERE p.registration_date > '2022-01-01'
GROUP BY p.username, p.country_code
ORDER BY total_sessions DESC;

[User] Finally, only include players who have played more than 10 sessions.

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

[User] Show me each achievement name and the number of players who have unlocked it.

[Assistant]
SELECT a.name,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name;

[User] Now only include achievements with at least 20 unlocks, and display their points as well.

[Assistant]
SELECT a.name,
       a.points,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name, a.points
HAVING COUNT(pa.player_id) >= 20;

[User] Finally, include the game_id for each achievement and sort by unlock_count descending.

[Assistant]
SELECT a.game_id,
       a.name,
       a.points,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.game_id, a.name, a.points
HAVING COUNT(pa.player_id) >= 20
ORDER BY unlock_count DESC;

[User] List each server's name and region along with the total number of sessions hosted on that server.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
GROUP BY s.server_name, s.region;

[User] Filter out servers with fewer than 50 sessions.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
GROUP BY s.server_name, s.region
HAVING COUNT(gs.session_id) >= 50;

[User] Also include the average duration_seconds of those sessions per server.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count,
       AVG(gs.duration_seconds) AS avg_duration
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
GROUP BY s.server_name, s.region
HAVING COUNT(gs.session_id) >= 50;

[User] And only for servers currently online, sorted by avg_duration descending.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count,
       AVG(gs.duration_seconds) AS avg_duration
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
WHERE s.status = 'online'
GROUP BY s.server_name, s.region
HAVING COUNT(gs.session_id) >= 50
ORDER BY avg_duration DESC;

[User] For each game session, list session_id, player_id, and the number of achievements that the player had unlocked before the session start_time.

[Assistant]
```sql
SELECT
  gs.session_id,
  gs.player_id,
  COUNT(pa.achievement_id) AS achievements_before_session
FROM gaming_technology.game_sessions gs
LEFT JOIN gaming_technology.player_achievements pa
  ON gs.player_id = pa.player_id
  AND pa.unlocked_at < gs.start_time
GROUP BY
  gs.session_id,
  gs.player_id;
```

[User] Exclude sessions where achievements_before_session is zero.

[Assistant]
```sql
SELECT
  gs.session_id,
  gs.player_id,
  COUNT(pa.achievement_id) AS achievements_before_session
FROM gaming_technology.game_sessions gs
LEFT JOIN gaming_technology.player_achievements pa
  ON gs.player_id = pa.player_id
  AND pa.unlocked_at < gs.start_time
GROUP BY
  gs.session_id,
  gs.player_id
HAVING
  COUNT(pa.achievement_id) > 0;
```

[User] Finally, order by achievements_before_session descending and limit to the top 10 sessions.

[Assistant]
```sql
SELECT
  gs.session_id,
  gs.player_id,
  COUNT(pa.achievement_id) AS achievements_before_session
FROM gaming_technology.game_sessions gs
LEFT JOIN gaming_technology.player_achievements pa
  ON gs.player_id = pa.player_id
  AND pa.unlocked_at < gs.start_time
GROUP BY
  gs.session_id,
  gs.player_id
HAVING
  COUNT(pa.achievement_id) > 0
ORDER BY
  achievements_before_session DESC
LIMIT 10;
```

[User] Show each player with their player_id, username, the number of distinct in-game items they own, and the total quantity of those items.

[Assistant]
```sql
SELECT
  p.player_id,
  p.username,
  COUNT(DISTINCT i.item_id) AS distinct_item_count,
  COALESCE(SUM(i.quantity), 0)    AS total_quantity
FROM gaming_technology.players p
LEFT JOIN gaming_technology.player_inventory i
  ON p.player_id = i.player_id
GROUP BY
  p.player_id,
  p.username;
```

[User] Only include inventory records acquired in the last 30 days.

[Assistant]
```sql
SELECT
  p.player_id,
  p.username,
  COUNT(DISTINCT i.item_id) AS distinct_item_count,
  COALESCE(SUM(i.quantity), 0)    AS total_quantity
FROM gaming_technology.players p
LEFT JOIN gaming_technology.player_inventory i
  ON p.player_id = i.player_id
  AND i.acquired_at >= NOW() - INTERVAL '30 days'
GROUP BY
  p.player_id,
  p.username;
```

[User] Also, show only players who have more than 5 distinct items in that period.

[Assistant]
```sql
SELECT
  p.player_id,
  p.username,
  COUNT(DISTINCT i.item_id) AS distinct_item_count,
  COALESCE(SUM(i.quantity), 0)    AS total_quantity
FROM gaming_technology.players p
LEFT JOIN gaming_technology.player_inventory i
  ON p.player_id = i.player_id
  AND i.acquired_at >= NOW() - INTERVAL '30 days'
GROUP BY
  p.player_id,
  p.username
HAVING
  COUNT(DISTINCT i.item_id) > 5;
```

[User] Order the results by total_quantity descending and then by username ascending.

[Assistant]
```sql
SELECT
  p.player_id,
  p.username,
  COUNT(DISTINCT i.item_id) AS distinct_item_count,
  COALESCE(SUM(i.quantity), 0)    AS total_quantity
FROM gaming_technology.players p
LEFT JOIN gaming_technology.player_inventory i
  ON p.player_id = i.player_id
  AND i.acquired_at >= NOW() - INTERVAL '30 days'
GROUP BY
  p.player_id,
  p.username
HAVING
  COUNT(DISTINCT i.item_id) > 5
ORDER BY
  total_quantity DESC,
  p.username 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 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] List all unique claim handler IDs present in the claims table.

[Assistant] SELECT DISTINCT claim_handler_id FROM insurance.claims WHERE claim_handler_id IS NOT NULL

[User] Find claims where the estimated loss is greater than the average estimated loss for claims with a status of 'Closed'. Show the claim ID, incident date, estimated loss, and status.

[Assistant] SELECT claim_id, incident_date, estimated_loss, status FROM insurance.claims WHERE estimated_loss > (SELECT AVG(estimated_loss) FROM insurance.claims WHERE status = 'Closed')

[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

[User] What is the total estimated_loss and average settlement_amount for all claims with status 'Approved'?

[Assistant]
SELECT SUM(estimated_loss) AS total_estimated_loss,
       AVG(settlement_amount) AS average_settlement
FROM insurance.claims
WHERE status = 'Approved';

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

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


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.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )

[User] For each server, what is the earliest and latest start time of its sessions?

[Assistant] SELECT server_id, MIN(start_time), MAX(start_time) FROM gaming_technology.game_sessions GROUP BY server_id;

[User] Only show servers where the difference between the earliest and latest session is more than 30 days.

[Assistant] SELECT server_id, MIN(start_time), MAX(start_time) FROM gaming_technology.game_sessions GROUP BY server_id HAVING MAX(start_time) - MIN(start_time) > INTERVAL '30 days';

[User] Show each player's highest score for each game they have played.

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id;

[User] Only include games where the player's highest score is at least 500.

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500;

[User] For each result, could you also include the number of sessions that player has for that game?

[Assistant] SELECT player_id, game_id, COUNT(*) AS session_count, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500;

[User] Order the results by highest_score in descending order.

[Assistant] SELECT player_id, game_id, COUNT(*) AS session_count, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500 ORDER BY highest_score DESC;

[User] Show the total session duration in seconds and the average score for each game.

[Assistant] SELECT game_id, SUM(duration_seconds), AVG(score) FROM gaming_technology.game_sessions GROUP BY game_id;

[User] Now, only include games where the total session duration is greater than 100000 seconds.

[Assistant] SELECT game_id, SUM(duration_seconds), AVG(score) FROM gaming_technology.game_sessions GROUP BY game_id HAVING SUM(duration_seconds) > 100000;

[User] How many game sessions started on each calendar day?

[Assistant] SELECT DATE(start_time), COUNT(*) FROM gaming_technology.game_sessions GROUP BY DATE(start_time) ORDER BY DATE(start_time);

[User] Only display days that had more than 100 sessions.

[Assistant] SELECT DATE(start_time), COUNT(*) FROM gaming_technology.game_sessions GROUP BY DATE(start_time) HAVING COUNT(*) > 100 ORDER BY DATE(start_time);

[User] Show the game ID and the average session duration in minutes for each game, ordered by average session duration descending.

[Assistant]
SELECT game_id, AVG(duration_seconds) / 60.0 AS avg_duration_minutes
FROM gaming_technology.game_sessions
GROUP BY game_id
ORDER BY avg_duration_minutes DESC;

[User] Also, include the total number of sessions for each game.

[Assistant]
SELECT game_id, COUNT(*) AS total_sessions, AVG(duration_seconds) / 60.0 AS avg_duration_minutes
FROM gaming_technology.game_sessions
GROUP BY game_id
ORDER BY avg_duration_minutes DESC;

[User] Filter to only show games with at least 100 sessions.

[Assistant]
SELECT game_id, COUNT(*) AS total_sessions, AVG(duration_seconds) / 60.0 AS avg_duration_minutes
FROM gaming_technology.game_sessions
GROUP BY game_id
HAVING COUNT(*) >= 100
ORDER BY avg_duration_minutes DESC;

[User] Order by total_sessions descending, then avg_duration_minutes descending.

[Assistant]
SELECT game_id, COUNT(*) AS total_sessions, AVG(duration_seconds) / 60.0 AS avg_duration_minutes
FROM gaming_technology.game_sessions
GROUP BY game_id
HAVING COUNT(*) >= 100
ORDER BY total_sessions DESC, avg_duration_minutes DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )

[User] List the diagnosis_id, patient_id, and doctor_id for all diagnoses with status 'Pending' and is_chronic set to TRUE.

[Assistant] SELECT diagnosis_id, patient_id, doctor_id FROM healthcare.diagnoses WHERE status = 'Pending' AND is_chronic = TRUE;

[User] List each patient and the total number of chronic diagnoses they have received, as well as the number of distinct doctors who have made those diagnoses.

[Assistant] SELECT patient_id, COUNT(*) AS chronic_diagnoses_count, COUNT(DISTINCT doctor_id) AS distinct_doctors FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY patient_id;

[User] Only include patients who have received diagnoses recorded as 'Active' status.

[Assistant] SELECT patient_id, COUNT(*) AS chronic_diagnoses_count, COUNT(DISTINCT doctor_id) AS distinct_doctors FROM healthcare.diagnoses WHERE is_chronic = TRUE AND status = 'Active' GROUP BY patient_id;

[User] Show all diagnosis codes and descriptions for patients diagnosed by doctor 'doctor_789'.

[Assistant] SELECT patient_id, diagnosis_code, description FROM healthcare.diagnoses WHERE doctor_id = 'doctor_789';

[User] Filter the results to include only diagnoses made after '2023-01-01'.

[Assistant] SELECT patient_id, diagnosis_code, description FROM healthcare.diagnoses WHERE doctor_id = 'doctor_789' AND diagnosis_date > '2023-01-01';

[User] Can you also show whether each diagnosis is chronic?

[Assistant] SELECT patient_id, diagnosis_code, description, is_chronic FROM healthcare.diagnoses WHERE doctor_id = 'doctor_789' AND diagnosis_date > '2023-01-01';

[User] Now, only include records where the diagnosis status is 'Active'.

[Assistant] SELECT patient_id, diagnosis_code, description, is_chronic FROM healthcare.diagnoses WHERE doctor_id = 'doctor_789' AND diagnosis_date > '2023-01-01' AND status = 'Active';

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

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

[User] Find all unique diagnosis codes that are associated with more than one doctor, and show how many doctors are linked to each code.

[Assistant] SELECT diagnosis_code, COUNT(DISTINCT doctor_id) AS doctor_count FROM healthcare.diagnoses GROUP BY diagnosis_code HAVING COUNT(DISTINCT doctor_id) > 1;

[User] Also, show only codes that are used after January 1st, 2023.

[Assistant] SELECT diagnosis_code, COUNT(DISTINCT doctor_id) AS doctor_count FROM healthcare.diagnoses WHERE diagnosis_date > '2023-01-01' GROUP BY diagnosis_code HAVING COUNT(DISTINCT doctor_id) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )

[User] Show me all wallet addresses along with their private keys for users who have more than 3 wallets.

[Assistant] SELECT w1.address_id, w1.private_key FROM blockchain.wallets w1 INNER JOIN (SELECT user_id FROM blockchain.wallets GROUP BY user_id HAVING COUNT(*) > 3) w2 ON w1.user_id = w2.user_id;

[User] Now, filter these results to only show wallets where the private_key starts with '0x1'.

[Assistant] SELECT w1.address_id, w1.private_key FROM blockchain.wallets w1 INNER JOIN (SELECT user_id FROM blockchain.wallets GROUP BY user_id HAVING COUNT(*) > 3) w2 ON w1.user_id = w2.user_id WHERE w1.private_key LIKE '0x1%';

[User] Show me the top 5 users with the most wallet addresses, along with the count of their wallets.

[Assistant] SELECT user_id, COUNT(wallet_id) AS wallet_count FROM blockchain.wallets WHERE user_id IS NOT NULL GROUP BY user_id ORDER BY wallet_count DESC LIMIT 5;

[User] Now include the earliest created wallet address for each of these top 5 users.

[Assistant] Note: The wallets table doesn't have a creation timestamp column. Without this information, we cannot determine the earliest created wallet. Please provide a table with creation timestamps if you need this analysis.

[User] Then just show me these top 5 users with their wallet counts and the first wallet_id alphabetically for each user.

[Assistant] SELECT user_id, COUNT(wallet_id) AS wallet_count, MIN(wallet_id) AS first_wallet_id FROM blockchain.wallets WHERE user_id IS NOT NULL GROUP BY user_id ORDER BY wallet_count DESC LIMIT 5;

[User] Show each user_id along with the total number of wallets they own.

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM blockchain.wallets
GROUP BY user_id;

[User] Only include users who have more than 1 wallet.

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM blockchain.wallets
GROUP BY user_id
HAVING COUNT(*) > 1;

[User] And order the output by wallet_count descending.

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM blockchain.wallets
GROUP BY user_id
HAVING COUNT(*) > 1
ORDER BY wallet_count DESC;

[User] I want to find all pairs of wallets that belong to the same user.

[Assistant]
SELECT w1.wallet_id AS wallet1, w2.wallet_id AS wallet2, w1.user_id
FROM blockchain.wallets w1
JOIN blockchain.wallets w2
  ON w1.user_id = w2.user_id
  AND w1.wallet_id < w2.wallet_id;

[User] Can you include the address_id for both wallets in each pair as well?

[Assistant]
SELECT
  w1.wallet_id AS wallet1,
  w1.address_id AS address1,
  w2.wallet_id AS wallet2,
  w2.address_id AS address2,
  w1.user_id
FROM blockchain.wallets w1
JOIN blockchain.wallets w2
  ON w1.user_id = w2.user_id
  AND w1.wallet_id < w2.wallet_id;

[User] Actually, only show pairs where both address_id values start with '0xA'.

[Assistant]
SELECT
  w1.wallet_id AS wallet1,
  w1.address_id AS address1,
  w2.wallet_id AS wallet2,
  w2.address_id AS address2,
  w1.user_id
FROM blockchain.wallets w1
JOIN blockchain.wallets w2
  ON w1.user_id = w2.user_id
  AND w1.wallet_id < w2.wallet_id
WHERE w1.address_id LIKE '0xA%'
  AND w2.address_id LIKE '0xA%';

[User] Great. Now sort the results by user_id ascending and then wallet1 ascending.

[Assistant]
SELECT
  w1.wallet_id AS wallet1,
  w1.address_id AS address1,
  w2.wallet_id AS wallet2,
  w2.address_id AS address2,
  w1.user_id
FROM blockchain.wallets w1
JOIN blockchain.wallets w2
  ON w1.user_id = w2.user_id
  AND w1.wallet_id < w2.wallet_id
WHERE w1.address_id LIKE '0xA%'
  AND w2.address_id LIKE '0xA%'
ORDER BY w1.user_id ASC, w1.wallet_id ASC;

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

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

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

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


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.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)

[User] For each security sector, what is the average volume recorded in the market data?

[Assistant] SELECT T2.sector, AVG(T1.volume) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id GROUP BY T2.sector;

[User] Can you restrict this to data points from the last 6 months?

[Assistant] SELECT T2.sector, AVG(T1.volume) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= NOW() - INTERVAL '6 months' GROUP BY T2.sector;

[User] Also include the count of data points per sector in the result.

[Assistant] SELECT T2.sector, AVG(T1.volume), COUNT(T1.data_point_id) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= NOW() - INTERVAL '6 months' GROUP BY T2.sector;

[User] Filter out sectors with fewer than 1000 data points in this period.

[Assistant] SELECT T2.sector, AVG(T1.volume), COUNT(T1.data_point_id) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= NOW() - INTERVAL '6 months' GROUP BY T2.sector HAVING COUNT(T1.data_point_id) >= 1000;

[User] For each security exchange, what is the average daily high price and the total volume recorded in market data for securities listed on that exchange over the past 6 months? Include the exchange name.

[Assistant] SELECT T2.exchange, AVG(T1.high_price) AS avg_daily_high_price, SUM(T1.volume) AS total_volume FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= CURRENT_DATE - INTERVAL '6 months' GROUP BY T2.exchange;

[User] Only include exchanges where the total volume is greater than 10,000,000.

[Assistant] SELECT T2.exchange, AVG(T1.high_price) AS avg_daily_high_price, SUM(T1.volume) AS total_volume FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= CURRENT_DATE - INTERVAL '6 months' GROUP BY T2.exchange HAVING SUM(T1.volume) > 10000000;

[User] Also, only show results for securities with a security type of 'Equity'.

[Assistant] SELECT T2.exchange, AVG(T1.high_price) AS avg_daily_high_price, SUM(T1.volume) AS total_volume FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= CURRENT_DATE - INTERVAL '6 months' AND T2.security_type = 'Equity' GROUP BY T2.exchange HAVING SUM(T1.volume) > 10000000;

[User] Finally, order the results by average high price descending and show only the top 5 exchanges.

[Assistant] SELECT T2.exchange, AVG(T1.high_price) AS avg_daily_high_price, SUM(T1.volume) AS total_volume FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= CURRENT_DATE - INTERVAL '6 months' AND T2.security_type = 'Equity' GROUP BY T2.exchange HAVING SUM(T1.volume) > 10000000 ORDER BY avg_daily_high_price DESC LIMIT 5;

[User] For each security issuer, show the count of market data points and the average close price for their securities.

[Assistant] SELECT T2.issuer_name, COUNT(T1.*) AS data_point_count, AVG(T1.close_price) AS avg_close_price FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id GROUP BY T2.issuer_name;

[User] Only include issuers who have more than 1000 market data points in total.

[Assistant] SELECT T2.issuer_name, COUNT(T1.*) AS data_point_count, AVG(T1.close_price) AS avg_close_price FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id GROUP BY T2.issuer_name HAVING COUNT(T1.*) > 1000;

[User] Also, include the average volume for each issuer and sort the results by average close price descending.

[Assistant] SELECT T2.issuer_name, COUNT(T1.*) AS data_point_count, AVG(T1.close_price) AS avg_close_price, AVG(T1.volume) AS avg_volume FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id GROUP BY T2.issuer_name HAVING COUNT(T1.*) > 1000 ORDER BY avg_close_price DESC;

[User] For each date in the last 30 days with market data, show the total volume and the maximum high price recorded.

[Assistant] SELECT data_timestamp::date, SUM(volume) AS total_volume, MAX(high_price) AS max_high_price FROM financial_services.market_data WHERE data_timestamp >= CURRENT_DATE - INTERVAL '30 days' GROUP BY data_timestamp::date ORDER BY data_timestamp::date ASC;

[User] Exclude any days where the total volume is less than 1,000,000.

[Assistant] SELECT data_timestamp::date, SUM(volume) AS total_volume, MAX(high_price) AS max_high_price FROM financial_services.market_data WHERE data_timestamp >= CURRENT_DATE - INTERVAL '30 days' GROUP BY data_timestamp::date HAVING SUM(volume) >= 1000000 ORDER BY data_timestamp::date ASC;

[User] Sort the results by date ascending and also show the average close price for each day.

[Assistant] SELECT data_timestamp::date, SUM(volume) AS total_volume, MAX(high_price) AS max_high_price, AVG(close_price) AS avg_close_price FROM financial_services.market_data WHERE data_timestamp >= CURRENT_DATE - INTERVAL '30 days' GROUP BY data_timestamp::date HAVING SUM(volume) >= 1000000 ORDER BY data_timestamp::date ASC;

[User] List the ticker symbol and security name for all securities that had a volume greater than 100000 on '2023-10-27'.

[Assistant] SELECT T2.ticker_symbol, T2.security_name FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp::date = '2023-10-27' AND T1.volume > 100000;

[User] Also include the close price from that day in the result.

[Assistant] SELECT T2.ticker_symbol, T2.security_name, T1.close_price FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp::date = '2023-10-27' AND T1.volume > 100000;

[User] Filter this list to only show securities belonging to the 'Technology' sector.

[Assistant] SELECT T2.ticker_symbol, T2.security_name, T1.close_price FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp::date = '2023-10-27' AND T1.volume > 100000 AND T2.sector = 'Technology';


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

[User] How many reservations have been booked each month in 2023?

[Assistant]
SELECT DATE_TRUNC('month', created_at) AS month,
       COUNT(*) AS reservation_count
FROM hospitality_technology.reservations
WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01'
GROUP BY month;

[User] Actually, exclude reservations with status 'Canceled' and order by month.

[Assistant]
SELECT DATE_TRUNC('month', created_at) AS month,
       COUNT(*) AS reservation_count
FROM hospitality_technology.reservations
WHERE created_at >= '2023-01-01'
  AND created_at < '2024-01-01'
  AND status <> 'Canceled'
GROUP BY month
ORDER BY month;

[User] Find reservations where the same guest has overlapping stays in the same property.

[Assistant]
SELECT r1.reservation_id AS res1,
       r2.reservation_id AS res2,
       r1.guest_id,
       r1.property_id
FROM hospitality_technology.reservations r1
JOIN hospitality_technology.reservations r2
  ON r1.guest_id = r2.guest_id
 AND r1.property_id = r2.property_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date;

[User] Only include overlaps where the overlapping period is more than 2 days.

[Assistant]
SELECT r1.reservation_id AS res1,
       r2.reservation_id AS res2,
       r1.guest_id,
       r1.property_id
FROM hospitality_technology.reservations r1
JOIN hospitality_technology.reservations r2
  ON r1.guest_id = r2.guest_id
 AND r1.property_id = r2.property_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date
WHERE (LEAST(r1.check_out_date, r2.check_out_date) - GREATEST(r1.check_in_date, r2.check_in_date)) > 2;

[User] Also return the exact overlap duration in days as overlap_days.

[Assistant]
SELECT r1.reservation_id AS res1,
       r2.reservation_id AS res2,
       r1.guest_id,
       r1.property_id,
       (LEAST(r1.check_out_date, r2.check_out_date) - GREATEST(r1.check_in_date, r2.check_in_date)) AS overlap_days
FROM hospitality_technology.reservations r1
JOIN hospitality_technology.reservations r2
  ON r1.guest_id = r2.guest_id
 AND r1.property_id = r2.property_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date
WHERE (LEAST(r1.check_out_date, r2.check_out_date) - GREATEST(r1.check_in_date, r2.check_in_date)) > 2;

[User] List reservations, including the reservation ID, check-in date, check-out date, property name, room type name, and room type base rate, for reservations with 3 or more adults.

[Assistant] SELECT T1.reservation_id, T1.check_in_date, T1.check_out_date, T2.property_name, T3.type_name, T3.base_rate FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.num_adults >= 3;

[User] Now, only include reservations made at properties with a star rating of 4 or higher and sort the results by check-in date.

[Assistant] SELECT T1.reservation_id, T1.check_in_date, T1.check_out_date, T2.property_name, T3.type_name, T3.base_rate FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.num_adults >= 3 AND T2.star_rating >= 4 ORDER BY T1.check_in_date;

[User] Further refine this list to include only reservations where the total amount is over 700, and limit the results to the top 15.

[Assistant] SELECT T1.reservation_id, T1.check_in_date, T1.check_out_date, T2.property_name, T3.type_name, T3.base_rate FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.num_adults >= 3 AND T2.star_rating >= 4 AND T1.total_amount > 700 ORDER BY T1.check_in_date LIMIT 15;

[User] What is the total revenue (sum of total_amount) and total amount_paid for each booking_source?

[Assistant]
SELECT booking_source,
       SUM(total_amount) AS total_revenue,
       SUM(amount_paid) AS total_paid
FROM reservations
GROUP BY booking_source;

[User] Only include sources where total revenue > 10000 and order by total_revenue descending.

[Assistant]
SELECT booking_source,
       SUM(total_amount) AS total_revenue,
       SUM(amount_paid) AS total_paid
FROM reservations
GROUP BY booking_source
HAVING SUM(total_amount) > 10000
ORDER BY total_revenue DESC;

[User] List pairs of overlapping reservations for the same room, including both reservation IDs, room_id, and each reservation's check-in and check-out dates.

[Assistant]
SELECT r1.reservation_id AS reservation_id_1,
       r2.reservation_id AS reservation_id_2,
       r1.room_id,
       r1.check_in_date AS check_in_1,
       r1.check_out_date AS check_out_1,
       r2.check_in_date AS check_in_2,
       r2.check_out_date AS check_out_2
FROM reservations r1
JOIN reservations r2
  ON r1.room_id = r2.room_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date;


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

[User] I need to list all chronic diagnoses that have at least one prescription, including diagnosis_code, diagnosis_date, and medication_name.

[Assistant]
SELECT d.diagnosis_code, d.diagnosis_date, m.medication_name
FROM healthcare.diagnoses d
JOIN healthcare.prescriptions p ON d.patient_id = p.patient_id
JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE d.is_chronic = TRUE;

[User] Actually, only include those prescriptions where quantity_dispensed > 50 and the diagnosis status is 'Active'.

[Assistant]
SELECT d.diagnosis_code, d.diagnosis_date, m.medication_name
FROM healthcare.diagnoses d
JOIN healthcare.prescriptions p ON d.patient_id = p.patient_id
JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE d.is_chronic = TRUE
  AND d.status = 'Active'
  AND p.quantity_dispensed > 50;

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

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

[User] Show prescription_id, medication_name, and dosage for all prescriptions where the medication manufacturer is 'Pfizer'.

[Assistant]
SELECT p.prescription_id, m.medication_name, p.dosage
FROM healthcare.prescriptions p
JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE m.manufacturer = 'Pfizer';

[User] Show me a list of patients along with their latest prescription's medication name, prescription date, and the prescribing doctor's ID.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, pr.medication_id, m.medication_name, pr.prescription_date, pr.doctor_id
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE pr.prescription_date = (
    SELECT MAX(prescription_date)
    FROM healthcare.prescriptions pr2
    WHERE pr2.patient_id = p.patient_id
);

[User] Instead, only show results for patients whose latest prescription's end_date is in the future.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, pr.medication_id, m.medication_name, pr.prescription_date, pr.doctor_id
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE pr.prescription_date = (
    SELECT MAX(prescription_date)
    FROM healthcare.prescriptions pr2
    WHERE pr2.patient_id = p.patient_id
)
AND (pr.end_date IS NULL OR pr.end_date > CURRENT_DATE);

[User] Also include the generic name of the medication in the results.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, pr.medication_id, m.medication_name, m.generic_name, pr.prescription_date, pr.doctor_id
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE pr.prescription_date = (
    SELECT MAX(prescription_date)
    FROM healthcare.prescriptions pr2
    WHERE pr2.patient_id = p.patient_id
)
AND (pr.end_date IS NULL OR pr.end_date > CURRENT_DATE);

[User] List the full names of patients who have ever been prescribed a medication manufactured by 'Novartis'.

[Assistant]
SELECT DISTINCT p.first_name, p.last_name
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE m.manufacturer = 'Novartis';

[User] Please also show the medication name for each result.

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, m.medication_name
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE m.manufacturer = 'Novartis';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)

[User] List all pairs of customers who live in the same zip_code. Show customer1_id, customer2_id, and zip_code.

[Assistant]
SELECT
  c1.customer_id AS customer1_id,
  c2.customer_id AS customer2_id,
  c1.zip_code
FROM insurance.customers c1
JOIN insurance.customers c2
  ON c1.zip_code = c2.zip_code
  AND c1.customer_id <> c2.customer_id;

[User] Please also include both customers' email addresses in the results.

[Assistant]
SELECT
  c1.customer_id AS customer1_id,
  c2.customer_id AS customer2_id,
  c1.zip_code,
  c1.email AS email1,
  c2.email AS email2
FROM insurance.customers c1
JOIN insurance.customers c2
  ON c1.zip_code = c2.zip_code
  AND c1.customer_id <> c2.customer_id;

[User] List all agents along with the first and last name of their manager.

[Assistant] SELECT a1.first_name AS agent_first_name, a1.last_name AS agent_last_name, a2.first_name AS manager_first_name, a2.last_name AS manager_last_name FROM insurance.agents AS a1 LEFT JOIN insurance.agents AS a2 ON a1.manager_id = a2.agent_id;

[User] Only include agents who were hired after the start of 2022.

[Assistant] SELECT a1.first_name AS agent_first_name, a1.last_name AS agent_last_name, a2.first_name AS manager_first_name, a2.last_name AS manager_last_name FROM insurance.agents AS a1 LEFT JOIN insurance.agents AS a2 ON a1.manager_id = a2.agent_id WHERE a1.hire_date > '2022-01-01';

[User] Order the results first by manager's last name, then by agent's last name.

[Assistant] SELECT a1.first_name AS agent_first_name, a1.last_name AS agent_last_name, a2.first_name AS manager_first_name, a2.last_name AS manager_last_name FROM insurance.agents AS a1 LEFT JOIN insurance.agents AS a2 ON a1.manager_id = a2.agent_id WHERE a1.hire_date > '2022-01-01' ORDER BY a2.last_name ASC, a1.last_name ASC;

[User] List all inactive customers from Texas who were created in the last 2 years, showing their full names and creation dates.

[Assistant] SELECT first_name, last_name, created_at FROM insurance.customers WHERE state = 'Texas' AND status = 'Inactive' AND created_at >= CURRENT_DATE - INTERVAL '2 years';

[User] Now sort these results by creation date in descending order.

[Assistant] SELECT first_name, last_name, created_at FROM insurance.customers WHERE state = 'Texas' AND status = 'Inactive' AND created_at >= CURRENT_DATE - INTERVAL '2 years' ORDER BY created_at DESC;

[User] Show me all active policies for customers who live in California, along with their total premium payments made so far.

[Assistant] SELECT p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount, SUM(pp.amount_paid) AS total_payments_made FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id LEFT JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id WHERE p.status = 'Active' AND c.state = 'California' GROUP BY p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount;

[User] I also want to see how many claims each of these policies has had.

[Assistant] SELECT p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount, SUM(pp.amount_paid) AS total_payments_made, COUNT(cl.claim_id) AS claim_count FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id LEFT JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id LEFT JOIN insurance.claims cl ON p.policy_id = cl.policy_id WHERE p.status = 'Active' AND c.state = 'California' GROUP BY p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount;

[User] Actually, I only want to see policies that have at least one claim.

[Assistant] SELECT p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount, SUM(pp.amount_paid) AS total_payments_made, COUNT(cl.claim_id) AS claim_count FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id LEFT JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id JOIN insurance.claims cl ON p.policy_id = cl.policy_id WHERE p.status = 'Active' AND c.state = 'California' GROUP BY p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount HAVING COUNT(cl.claim_id) > 0;

[User] Now show me the average settlement amount for these policies' claims.

[Assistant] SELECT p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount, SUM(pp.amount_paid) AS total_payments_made, COUNT(cl.claim_id) AS claim_count, AVG(cl.settlement_amount) AS avg_settlement FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id LEFT JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id JOIN insurance.claims cl ON p.policy_id = cl.policy_id WHERE p.status = 'Active' AND c.state = 'California' GROUP BY p.policy_id, p.policy_number, c.first_name, c.last_name, p.premium_amount HAVING COUNT(cl.claim_id) > 0;

[User] Show all claims and the full name of the customer who filed each claim.

[Assistant] SELECT T1.claim_id, T1.incident_date, T1.description, T2.first_name, T2.last_name FROM insurance.claims AS T1 JOIN insurance.customers AS T2 ON T1.customer_id = T2.customer_id

[User] Can you also include the ID of the claim handler for each claim?

[Assistant] SELECT T1.claim_id, T1.incident_date, T1.description, T2.first_name, T2.last_name, T1.claim_handler_id FROM insurance.claims AS T1 JOIN insurance.customers AS T2 ON T1.customer_id = T2.customer_id

[User] Actually, only show claims with status 'Open' and an estimated loss greater than $10,000.

[Assistant] SELECT T1.claim_id, T1.incident_date, T1.description, T2.first_name, T2.last_name, T1.claim_handler_id FROM insurance.claims AS T1 JOIN insurance.customers AS T2 ON T1.customer_id = T2.customer_id WHERE T1.status = 'Open' AND T1.estimated_loss > 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 social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )

[User] List all posts where the content mentions 'meeting'.

[Assistant] SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%'

[User] Also, only include those posts that are public.

[Assistant] SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%' AND visibility = 'public'

[User] How many posts are currently marked as 'private' visibility?

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

[User] List all posts created by user 'U789'.

[Assistant] SELECT post_id, content, created_at, media_type FROM social_media.posts WHERE user_id = 'U789'

[User] Only show me the posts that have a media type of 'image'.

[Assistant] SELECT post_id, content, created_at, media_type FROM social_media.posts WHERE user_id = 'U789' AND media_type = 'image'

[User] Also, filter these images to only include those created in May 2024.

[Assistant] SELECT post_id, content, created_at, media_type FROM social_media.posts WHERE user_id = 'U789' AND media_type = 'image' AND created_at BETWEEN '2024-05-01 00:00:00' AND '2024-05-31 23:59:59'

[User] Order these results by creation time, with the most recent first.

[Assistant] SELECT post_id, content, created_at, media_type FROM social_media.posts WHERE user_id = 'U789' AND media_type = 'image' AND created_at BETWEEN '2024-05-01 00:00:00' AND '2024-05-31 23:59:59' ORDER BY created_at DESC

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

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

[User] Show me the count of posts per media_type for public posts.

[Assistant]
SELECT media_type, COUNT(*) AS post_count
FROM social_media.posts
WHERE visibility = 'public'
GROUP BY media_type;


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

[User] I need to find users who have liked both a post and a comment on the same day. For each such user and date, list user_id, date, post_id, and comment_id.

[Assistant]
SELECT p.user_id, DATE(p.created_at) AS like_date, p.post_id, c.comment_id
FROM social_media.likes p
JOIN social_media.likes c
  ON p.user_id = c.user_id
  AND DATE(p.created_at) = DATE(c.created_at)
WHERE p.post_id IS NOT NULL
  AND c.comment_id IS NOT NULL;

[User] Actually, I only want cases where the post and comment were liked within two hours of each other.

[Assistant]
SELECT p.user_id, DATE(p.created_at) AS like_date, p.post_id, c.comment_id
FROM social_media.likes p
JOIN social_media.likes c
  ON p.user_id = c.user_id
  AND DATE(p.created_at) = DATE(c.created_at)
WHERE p.post_id IS NOT NULL
  AND c.comment_id IS NOT NULL
  AND ABS(EXTRACT(EPOCH FROM (p.created_at - c.created_at))) <= 7200;

[User] Please order the results by like_date descending.

[Assistant]
SELECT p.user_id, DATE(p.created_at) AS like_date, p.post_id, c.comment_id
FROM social_media.likes p
JOIN social_media.likes c
  ON p.user_id = c.user_id
  AND DATE(p.created_at) = DATE(c.created_at)
WHERE p.post_id IS NOT NULL
  AND c.comment_id IS NOT NULL
  AND ABS(EXTRACT(EPOCH FROM (p.created_at - c.created_at))) <= 7200
ORDER BY like_date DESC;

[User] Also, limit the output to the top 10 records.

[Assistant]
SELECT p.user_id, DATE(p.created_at) AS like_date, p.post_id, c.comment_id
FROM social_media.likes p
JOIN social_media.likes c
  ON p.user_id = c.user_id
  AND DATE(p.created_at) = DATE(c.created_at)
WHERE p.post_id IS NOT NULL
  AND c.comment_id IS NOT NULL
  AND ABS(EXTRACT(EPOCH FROM (p.created_at - c.created_at))) <= 7200
ORDER BY like_date DESC
LIMIT 10;

[User] Show the total number of likes made by each user, including the user_id and their like count.

[Assistant] SELECT user_id, COUNT(*) AS like_count FROM social_media.likes GROUP BY user_id;

[User] Only show users who have made more than 50 likes.

[Assistant] SELECT user_id, COUNT(*) AS like_count FROM social_media.likes GROUP BY user_id HAVING COUNT(*) > 50;

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

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

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

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

[User] What is the total number of likes recorded in the system?

[Assistant] SELECT COUNT(*) FROM social_media.likes;

[User] Count the total number of likes each post has received.

[Assistant]
SELECT post_id, COUNT(*) AS like_count
FROM social_media.likes
WHERE post_id IS NOT NULL
GROUP BY post_id;


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

  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

  "CREATE TABLE smart_money_profit (",
    "address character varying(100) NOT NULL, -- the user's address",
    "rank INT, -- the rank of the address in trade performance, value 1 expresses the best address.",
    "profit numeric(38,6), -- the profit user made in a month",
    "roi numeric(38,2), -- the roi of the user in a month",
    "realized_ratio numeric(38,2), -- the percentage of the user's realized profit",
    "most_profit_token character varying(100), -- the token symbol of the user's most profitable trade",
    "last_trade_time character varying(100), -- the last trade time of the user",
    "chain character varying(100), -- the chain that the address resides",
    "PRIMARY KEY (address, chain));",

  "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] Which smart money address on the 'Ethereum' chain has the highest profit from tokens in the 'DeFi' narrative, and what is their ROI?

[Assistant]
SELECT sm.address, sm.profit, sm.roi
FROM smart_money_profit sm
JOIN smart_money_token_inflow si ON sm.address = si.address AND sm.chain = si.chain
WHERE sm.chain = 'Ethereum' AND si.narrative = 'DeFi'
ORDER BY sm.profit DESC
LIMIT 1;

[User] Could you include the most profitable token for each address in the result?

[Assistant]
SELECT sm.address, sm.profit, sm.roi, sm.most_profit_token
FROM smart_money_profit sm
JOIN smart_money_token_inflow si ON sm.address = si.address AND sm.chain = si.chain
WHERE sm.chain = 'Ethereum' AND si.narrative = 'DeFi'
ORDER BY sm.profit DESC
LIMIT 1;

[User] Now, only show addresses with ROI above 10.

[Assistant]
SELECT sm.address, sm.profit, sm.roi, sm.most_profit_token
FROM smart_money_profit sm
JOIN smart_money_token_inflow si ON sm.address = si.address AND sm.chain = si.chain
WHERE sm.chain = 'Ethereum' AND si.narrative = 'DeFi' AND sm.roi > 10
ORDER BY sm.profit DESC;

[User] Order the results by ROI descending and show the top 2.

[Assistant]
SELECT sm.address, sm.profit, sm.roi, sm.most_profit_token
FROM smart_money_profit sm
JOIN smart_money_token_inflow si ON sm.address = si.address AND sm.chain = si.chain
WHERE sm.chain = 'Ethereum' AND si.narrative = 'DeFi' AND sm.roi > 10
ORDER BY sm.roi DESC
LIMIT 2;

[User] List all tokens from the token_dexpool_info table with a liquidity over $10 million and a positive 6-hour price change percentage on the Ethereum chain.

[Assistant] SELECT token_name, token_symbol, liquidity, price_change_percentage_6h FROM token_dexpool_info WHERE liquidity > 10000000 AND price_change_percentage_6h > 0 AND chain = 'Ethereum';

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

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

[User] Actually, I only want narratives with a negative 1-hour price change percentage.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[Assistant] SELECT AVG(roi) FROM smart_money_token_performance WHERE chain = 'Ethereum';


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.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)

[User] For each transaction ID, provide a count of unspent UTXOs.

[Assistant] SELECT transaction_id, COUNT(*) FROM utxos WHERE spent = FALSE GROUP BY transaction_id;

[User] For each address, show the total amount contained in UTXOs that have been spent.

[Assistant] SELECT address, SUM(amount) FROM utxos WHERE spent = TRUE GROUP BY address;

[User] Only include addresses where this total spent amount is greater than 500 and order the results by the total amount descending.

[Assistant] SELECT address, SUM(amount) FROM utxos WHERE spent = TRUE GROUP BY address HAVING SUM(amount) > 500 ORDER BY SUM(amount) DESC;

[User] How many UTXOs are associated with each transaction_id?

[Assistant] SELECT transaction_id, COUNT(*) AS utxo_count FROM trading_platform.utxos GROUP BY transaction_id;

[User] Can you also show the sum of all amounts per transaction_id?

[Assistant] SELECT transaction_id, COUNT(*) AS utxo_count, SUM(amount) AS total_amount FROM trading_platform.utxos GROUP BY transaction_id;

[User] I only want transactions where the total amount is at least 2.

[Assistant] SELECT transaction_id, COUNT(*) AS utxo_count, SUM(amount) AS total_amount FROM trading_platform.utxos GROUP BY transaction_id HAVING SUM(amount) >= 2;

[User] Order the results by total_amount descending.

[Assistant] SELECT transaction_id, COUNT(*) AS utxo_count, SUM(amount) AS total_amount FROM trading_platform.utxos GROUP BY transaction_id HAVING SUM(amount) >= 2 ORDER BY total_amount DESC;

[User] I want a list of DApp names and the asset symbols mentioned in their descriptions.

[Assistant]
SELECT d.name AS dapp_name,
       a.symbol AS asset_symbol
FROM trading_platform.dapps d
JOIN trading_platform.assets a
  ON d.description ILIKE '%' || a.symbol || '%';

[User] Now, only include DApps where the description mentions more than one distinct asset symbol.

[Assistant]
SELECT d.name AS dapp_name,
       COUNT(DISTINCT a.symbol) AS symbol_count
FROM trading_platform.dapps d
JOIN trading_platform.assets a
  ON d.description ILIKE '%' || a.symbol || '%'
GROUP BY d.name
HAVING COUNT(DISTINCT a.symbol) > 1;

[User] Also show the comma-separated list of these symbols.

[Assistant]
SELECT d.name AS dapp_name,
       COUNT(DISTINCT a.symbol) AS symbol_count,
       STRING_AGG(DISTINCT a.symbol, ',') AS symbols_list
FROM trading_platform.dapps d
JOIN trading_platform.assets a
  ON d.description ILIKE '%' || a.symbol || '%'
GROUP BY d.name
HAVING COUNT(DISTINCT a.symbol) > 1;

[User] Finally, order the result by number of mentioned assets descending and limit to top 3.

[Assistant]
SELECT d.name AS dapp_name,
       COUNT(DISTINCT a.symbol) AS symbol_count,
       STRING_AGG(DISTINCT a.symbol, ',') AS symbols_list
FROM trading_platform.dapps d
JOIN trading_platform.assets a
  ON d.description ILIKE '%' || a.symbol || '%'
GROUP BY d.name
HAVING COUNT(DISTINCT a.symbol) > 1
ORDER BY symbol_count DESC
LIMIT 3;

[User] List all assets mentioned in DApp descriptions along with the DApp name and URL.

[Assistant]
SELECT a.name AS asset_name,
       a.symbol AS asset_symbol,
       d.name AS dapp_name,
       d.url
FROM trading_platform.assets a
JOIN trading_platform.dapps d
  ON d.description ILIKE '%' || a.symbol || '%';

[User] Actually, only include assets of type 'cryptocurrency'.

[Assistant]
SELECT a.name AS asset_name,
       a.symbol AS asset_symbol,
       d.name AS dapp_name,
       d.url
FROM trading_platform.assets a
JOIN trading_platform.dapps d
  ON d.description ILIKE '%' || a.symbol || '%'
WHERE a.type = 'cryptocurrency';


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 cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

[User] Which token symbol has the highest price among all tokens held by CEXes on the Polygon chain?

[Assistant] SELECT token_symbol, MAX(price) AS max_price FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY max_price DESC LIMIT 1;

[User] Can you also show which exchange holds the largest balance of that token?

[Assistant] SELECT exchange, address, balance, usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND token_symbol = (SELECT token_symbol FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY MAX(price) DESC LIMIT 1) ORDER BY usd_value DESC LIMIT 1;

[User] Please include the snapshot_time of the record as well.

[Assistant] SELECT snapshot_time, exchange, address, balance, usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND token_symbol = (SELECT token_symbol FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY MAX(price) DESC LIMIT 1) ORDER BY usd_value DESC LIMIT 1;

[User] Instead of only the largest balance, can you list the top 3 addresses by usd_value for that token?

[Assistant] SELECT snapshot_time, exchange, address, balance, usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND token_symbol = (SELECT token_symbol FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY MAX(price) DESC LIMIT 1) ORDER BY usd_value DESC LIMIT 3;

[User] List smart money addresses with a realized ratio greater than 0.9 and a profit greater than 50000. Show the address, chain, realized ratio, and profit.

[Assistant] SELECT address, chain, realized_ratio, profit FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 50000;

[User] For the chains represented by these high-performing smart money addresses, list the top 2 centralized exchanges by total USD value on each of those chains (using the latest snapshot time). Show the chain, exchange, and total USD value.

[Assistant] WITH HighPerfChains AS (SELECT DISTINCT chain FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 50000), LatestSnapshot AS (SELECT MAX(snapshot_time) AS latest_time FROM cex_token_balance), ExchangeChainValue AS (SELECT c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value FROM cex_token_balance c JOIN LatestSnapshot ls ON c.snapshot_time = ls.latest_time JOIN HighPerfChains hpc ON c.chain = hpc.chain WHERE c.usd_value IS NOT NULL GROUP BY c.chain, c.exchange), RankedExchangeChainValue AS (SELECT chain, exchange, total_usd_value, RANK() OVER (PARTITION BY chain ORDER BY total_usd_value DESC) as rank_within_chain FROM ExchangeChainValue) SELECT chain, exchange, total_usd_value FROM RankedExchangeChainValue WHERE rank_within_chain <= 2 ORDER BY chain, total_usd_value DESC;

[User] Limit the results to only include chains where the total USD value for the top exchange is greater than 10,000,000.

[Assistant] WITH HighPerfChains AS (SELECT DISTINCT chain FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 50000), LatestSnapshot AS (SELECT MAX(snapshot_time) AS latest_time FROM cex_token_balance), ExchangeChainValue AS (SELECT c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value FROM cex_token_balance c JOIN LatestSnapshot ls ON c.snapshot_time = ls.latest_time JOIN HighPerfChains hpc ON c.chain = hpc.chain WHERE c.usd_value IS NOT NULL GROUP BY c.chain, c.exchange), RankedExchangeChainValue AS (SELECT chain, exchange, total_usd_value, RANK() OVER (PARTITION BY chain ORDER BY total_usd_value DESC) as rank_within_chain FROM ExchangeChainValue) SELECT chain, exchange, total_usd_value FROM RankedExchangeChainValue WHERE rank_within_chain <= 2 AND total_usd_value > 10000000 ORDER BY chain, total_usd_value DESC;

[User] Also, show the average smart money ROI for each of the chains included in the result.

[Assistant] WITH HighPerfChains AS (SELECT DISTINCT chain FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 50000), LatestSnapshot AS (SELECT MAX(snapshot_time) AS latest_time FROM cex_token_balance), ExchangeChainValue AS (SELECT c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value FROM cex_token_balance c JOIN LatestSnapshot ls ON c.snapshot_time = ls.latest_time JOIN HighPerfChains hpc ON c.chain = hpc.chain WHERE c.usd_value IS NOT NULL GROUP BY c.chain, c.exchange), RankedExchangeChainValue AS (SELECT chain, exchange, total_usd_value, RANK() OVER (PARTITION BY chain ORDER BY total_usd_value DESC) as rank_within_chain FROM ExchangeChainValue), FilteredRankedValue AS (SELECT chain, exchange, total_usd_value FROM RankedExchangeChainValue WHERE rank_within_chain <= 2 AND total_usd_value > 10000000), ChainAvgROI AS (SELECT chain, AVG(roi) AS average_smart_money_roi FROM smart_money_profit WHERE chain IN (SELECT DISTINCT chain FROM FilteredRankedValue) AND roi IS NOT NULL GROUP BY chain) SELECT frv.chain, frv.exchange, frv.total_usd_value, car.average_smart_money_roi FROM FilteredRankedValue frv JOIN ChainAvgROI car ON frv.chain = car.chain ORDER BY frv.chain, frv.total_usd_value DESC;

[User] For each exchange, compute the percentage change in total USD value of its holdings between snapshots '2023-01-01 00:00:00' and '2023-02-01 00:00:00'. Show exchange, chain, value_jan, value_feb, and pct_change.

[Assistant]
SELECT t1.exchange,
       t1.chain,
       t1.total_usd AS value_jan,
       t2.total_usd AS value_feb,
       ((t2.total_usd - t1.total_usd) / NULLIF(t1.total_usd,0)) * 100 AS pct_change
FROM (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = '2023-01-01 00:00:00'
  GROUP BY exchange, chain
) t1
JOIN (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = '2023-02-01 00:00:00'
  GROUP BY exchange, chain
) t2
  ON t1.exchange = t2.exchange AND t1.chain = t2.chain;

[User] Please modify the query to compare between '2023-01-01 00:00:00' and the latest available snapshot instead.

[Assistant]
WITH latest AS (
  SELECT MAX(snapshot_time) AS snap FROM cex_token_balance
),
jan AS (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = '2023-01-01 00:00:00'
  GROUP BY exchange, chain
),
feb AS (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = (SELECT snap FROM latest)
  GROUP BY exchange, chain
)
SELECT j.exchange,
       j.chain,
       j.total_usd AS value_jan,
       f.total_usd AS value_latest,
       ((f.total_usd - j.total_usd) / NULLIF(j.total_usd,0)) * 100 AS pct_change
FROM jan j
JOIN feb f
  ON j.exchange = f.exchange AND j.chain = f.chain;

[User] List all CEX addresses on the BSC chain that hold more than $1 million USD value in total.

[Assistant] SELECT address, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'BSC' GROUP BY address HAVING SUM(usd_value) > 1000000;

[User] List each blockchain (chain) and the centralized exchange that holds the highest total USD value of tokens, as well as the exchange with the lowest total USD value of tokens. Show chain, max_exchange, max_value, min_exchange, and min_value.

[Assistant]
WITH totals AS (
  SELECT chain, exchange, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  GROUP BY chain, exchange
),
max_totals AS (
  SELECT chain, exchange AS max_exchange, total_usd AS max_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd DESC) AS rn
    FROM totals
  ) t
  WHERE rn = 1
),
min_totals AS (
  SELECT chain, exchange AS min_exchange, total_usd AS min_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd ASC) AS rn
    FROM totals
  ) t
  WHERE rn = 1
)
SELECT m.chain, m.max_exchange, m.max_value, n.min_exchange, n.min_value
FROM max_totals m
JOIN min_totals n USING (chain);

[User] Actually, restrict the analysis to the latest snapshot_time only.

[Assistant]
WITH latest AS (
  SELECT MAX(snapshot_time) AS snap
  FROM cex_token_balance
),
totals AS (
  SELECT chain, exchange, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = (SELECT snap FROM latest)
  GROUP BY chain, exchange
),
max_totals AS (
  SELECT chain, exchange AS max_exchange, total_usd AS max_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd DESC) AS rn
    FROM totals
  ) t WHERE rn = 1
),
min_totals AS (
  SELECT chain, exchange AS min_exchange, total_usd AS min_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd ASC) AS rn
    FROM totals
  ) t WHERE rn = 1
)
SELECT m.chain, m.max_exchange, m.max_value, n.min_exchange, n.min_value
FROM max_totals m
JOIN min_totals n USING (chain);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )

[User] List all events and any token transfers that occurred in the same transaction, showing event_id, event_name, transfer_id, and token_symbol.

[Assistant]
SELECT
  e.event_id,
  e.event_name,
  tt.transfer_id,
  tk.token_symbol
FROM web3.events e
LEFT JOIN web3.token_transfers tt
  ON e.transaction_id = tt.transaction_id
LEFT JOIN web3.tokens tk
  ON tt.token_id = tk.token_id
ORDER BY e.transaction_id, e.log_index;

[User] For each contract deployed on network 'mainnet', show its address, status, the number of tokens created by that contract's address, and the total number of events emitted by that contract.

[Assistant]
SELECT
  c.address AS contract_address,
  c.status,
  COUNT(DISTINCT t.token_id) AS token_count,
  COUNT(e.event_id) AS event_count
FROM web3.contracts c
LEFT JOIN web3.tokens t
  ON c.address = t.contract_address
LEFT JOIN web3.events e
  ON c.contract_id = e.contract_id
WHERE c.network_id = 'mainnet'
GROUP BY c.address, c.status;

[User] List all contracts along with the number of tokens deployed at each contract address.

[Assistant]
SELECT c.contract_id, c.address AS contract_address, COUNT(t.token_id) AS token_count
FROM web3.contracts c
LEFT JOIN web3.tokens t ON c.address = t.contract_address
GROUP BY c.contract_id, c.address;

[User] Actually, just show contracts that have deployed at least 2 tokens.

[Assistant]
SELECT c.contract_id, c.address AS contract_address, COUNT(t.token_id) AS token_count
FROM web3.contracts c
LEFT JOIN web3.tokens t ON c.address = t.contract_address
GROUP BY c.contract_id, c.address
HAVING COUNT(t.token_id) >= 2;

[User] For each token transfer, show the transfer id, token symbol, and the username of the user who owns the sender address. Please order the result by transfer id.

[Assistant]
SELECT tt.transfer_id, tk.token_symbol, u.username
FROM web3.token_transfers tt
JOIN web3.tokens tk ON tt.token_id = tk.token_id
JOIN web3.wallets w ON tt.from_address = w.address
JOIN web3.users u ON w.user_id = u.user_id
ORDER BY tt.transfer_id;

[User] List all users who created a wallet on the same day they registered. Show user ID, username, and the wallet address.

[Assistant] SELECT u.user_id, u.username, w.address FROM web3.users AS u JOIN web3.wallets AS w ON u.user_id = w.user_id WHERE DATE(u.created_at) = DATE(w.created_at);