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.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )

[User] Count how many insurance plans exist for each plan type.

[Assistant]
SELECT plan_type, COUNT(*) AS plan_count
FROM healthcare.insurance_plans
GROUP BY plan_type;

[User] Now filter to only show plan types with more than 2 plans.

[Assistant]
SELECT plan_type, COUNT(*) AS plan_count
FROM healthcare.insurance_plans
GROUP BY plan_type
HAVING COUNT(*) > 2;

[User] Count the total number of unique insurance providers in the system.

[Assistant] SELECT COUNT(DISTINCT insurance_provider) FROM healthcare.insurance_plans;

[User] List the plan ID, name, provider, and type for all insurance plans from 'Healthcare Partners' with a plan type of 'PPO'.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO';

[User] Now, only show those plans that also have a website listed.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL;

[User] Further refine the results to only include plans where the plan name contains the word 'Plus'.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL AND plan_name ILIKE '%Plus%';

[User] Finally, count how many such plans exist.

[Assistant] SELECT COUNT(*) FROM healthcare.insurance_plans WHERE insurance_provider = 'Healthcare Partners' AND plan_type = 'PPO' AND website IS NOT NULL AND plan_name ILIKE '%Plus%';

[User] I want to list pairs of insurance plans from the same provider, showing both plan IDs and names alongside the provider.

[Assistant]
SELECT p1.plan_id, p1.plan_name, p2.plan_id AS plan_id_2, p2.plan_name AS plan_name_2, p1.insurance_provider
FROM healthcare.insurance_plans p1
JOIN healthcare.insurance_plans p2
  ON p1.insurance_provider = p2.insurance_provider
  AND p1.plan_id < p2.plan_id;

[User] Actually, only include pairs where the plan types are different.

[Assistant]
SELECT p1.plan_id, p1.plan_name, p2.plan_id AS plan_id_2, p2.plan_name AS plan_name_2, p1.insurance_provider
FROM healthcare.insurance_plans p1
JOIN healthcare.insurance_plans p2
  ON p1.insurance_provider = p2.insurance_provider
  AND p1.plan_id < p2.plan_id
WHERE p1.plan_type <> p2.plan_type;

[User] Also, sort the results by provider ascending and then by the first plan_id.

[Assistant]
SELECT p1.plan_id, p1.plan_name, p2.plan_id AS plan_id_2, p2.plan_name AS plan_name_2, p1.insurance_provider
FROM healthcare.insurance_plans p1
JOIN healthcare.insurance_plans p2
  ON p1.insurance_provider = p2.insurance_provider
  AND p1.plan_id < p2.plan_id
WHERE p1.plan_type <> p2.plan_type
ORDER BY p1.insurance_provider ASC, p1.plan_id ASC;

[User] I want to find all pairs of insurance plans that share the same contact phone number, showing plan IDs, names, and the shared phone.

[Assistant]
SELECT p1.plan_id, p1.plan_name, p2.plan_id AS plan_id_2, p2.plan_name AS plan_name_2, p1.contact_phone
FROM healthcare.insurance_plans p1
JOIN healthcare.insurance_plans p2
  ON p1.contact_phone = p2.contact_phone
  AND p1.plan_id < p2.plan_id;

[User] Actually, exclude any plans where the contact phone is null or empty.

[Assistant]
SELECT p1.plan_id, p1.plan_name, p2.plan_id AS plan_id_2, p2.plan_name AS plan_name_2, p1.contact_phone
FROM healthcare.insurance_plans p1
JOIN healthcare.insurance_plans p2
  ON p1.contact_phone = p2.contact_phone
  AND p1.plan_id < p2.plan_id
WHERE p1.contact_phone IS NOT NULL
  AND p1.contact_phone <> '';

[User] List all insurance providers along with the total number of plans they offer.

[Assistant]
SELECT insurance_provider, COUNT(*) AS plan_count
FROM healthcare.insurance_plans
GROUP BY insurance_provider;

[User] Only show providers with more than 2 plans.

[Assistant]
SELECT insurance_provider, COUNT(*) AS plan_count
FROM healthcare.insurance_plans
GROUP BY insurance_provider
HAVING COUNT(*) > 2;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )

[User] Can you show me the number of lawyers grouped by specialization?

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count FROM lawyers GROUP BY specialization;

[User] Include only specializations that have more than two lawyers.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2;

[User] Also show the average tenure in years for each of those specializations.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count, AVG(EXTRACT(EPOCH FROM (NOW() - hire_date)) / 31536000) AS avg_tenure_years FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2;

[User] Order the result by average tenure in descending order.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count, AVG(EXTRACT(EPOCH FROM (NOW() - hire_date)) / 31536000) AS avg_tenure_years FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2 ORDER BY avg_tenure_years DESC;

[User] Show me the first_name, last_name, and firm_id of all lawyers whose email domain is 'legalfirm.com'.

[Assistant]
SELECT first_name,
       last_name,
       firm_id
FROM legal_services.lawyers
WHERE SPLIT_PART(email, '@', 2) = 'legalfirm.com';

[User] Find all pairs of lawyers who work for the same firm, showing each lawyer's first_name, last_name, email, and firm_id.

[Assistant]
SELECT l1.first_name AS lawyer1_first_name,
       l1.last_name AS lawyer1_last_name,
       l1.email AS lawyer1_email,
       l2.first_name AS lawyer2_first_name,
       l2.last_name AS lawyer2_last_name,
       l2.email AS lawyer2_email,
       l1.firm_id
FROM legal_services.lawyers l1
JOIN legal_services.lawyers l2
  ON l1.firm_id = l2.firm_id
  AND l1.lawyer_id < l2.lawyer_id;

[User] Show me the number of lawyers for each law firm, along with the firm's ID.

[Assistant] SELECT firm_id, COUNT(*) AS lawyer_count FROM legal_services.lawyers GROUP BY firm_id;

[User] Can you also include the number of partners per firm in the result?

[Assistant] SELECT firm_id, COUNT(*) AS lawyer_count, SUM(CASE WHEN is_partner THEN 1 ELSE 0 END) AS partner_count FROM legal_services.lawyers GROUP BY firm_id;

[User] Please restrict the results to only those firms that have more than 3 partners.

[Assistant] SELECT firm_id, COUNT(*) AS lawyer_count, SUM(CASE WHEN is_partner THEN 1 ELSE 0 END) AS partner_count FROM legal_services.lawyers GROUP BY firm_id HAVING SUM(CASE WHEN is_partner THEN 1 ELSE 0 END) > 3;

[User] How many lawyers are there in each specialization, and what is the count per specialization?

[Assistant]
SELECT specialization,
       COUNT(*) AS lawyer_count
FROM legal_services.lawyers
GROUP BY specialization;

[User] Find all pairs of lawyers who were hired on the exact same date but have different specializations. Return each lawyer's name, hire_date, and both specializations.

[Assistant]
SELECT a.lawyer_id   AS lawyer1_id,
       a.first_name  AS lawyer1_first_name,
       a.last_name   AS lawyer1_last_name,
       b.lawyer_id   AS lawyer2_id,
       b.first_name  AS lawyer2_first_name,
       b.last_name   AS lawyer2_last_name,
       a.hire_date,
       a.specialization AS specialization1,
       b.specialization AS specialization2
FROM legal_services.lawyers a
JOIN legal_services.lawyers b
  ON DATE(a.hire_date) = DATE(b.hire_date)
 AND a.lawyer_id < b.lawyer_id
 AND a.specialization <> b.specialization;

[User] Actually, only include pairs where at least one of the lawyers is a partner.

[Assistant]
SELECT a.lawyer_id   AS lawyer1_id,
       a.first_name  AS lawyer1_first_name,
       a.last_name   AS lawyer1_last_name,
       b.lawyer_id   AS lawyer2_id,
       b.first_name  AS lawyer2_first_name,
       b.last_name   AS lawyer2_last_name,
       a.hire_date,
       a.specialization AS specialization1,
       b.specialization AS specialization2
FROM legal_services.lawyers a
JOIN legal_services.lawyers b
  ON DATE(a.hire_date) = DATE(b.hire_date)
 AND a.lawyer_id < b.lawyer_id
 AND a.specialization <> b.specialization
WHERE a.is_partner OR b.is_partner;

[User] Also, sort the results by hire_date descending and then by the first lawyer's last_name ascending.

[Assistant]
SELECT a.lawyer_id   AS lawyer1_id,
       a.first_name  AS lawyer1_first_name,
       a.last_name   AS lawyer1_last_name,
       b.lawyer_id   AS lawyer2_id,
       b.first_name  AS lawyer2_first_name,
       b.last_name   AS lawyer2_last_name,
       a.hire_date,
       a.specialization AS specialization1,
       b.specialization AS specialization2
FROM legal_services.lawyers a
JOIN legal_services.lawyers b
  ON DATE(a.hire_date) = DATE(b.hire_date)
 AND a.lawyer_id < b.lawyer_id
 AND a.specialization <> b.specialization
WHERE a.is_partner OR b.is_partner
ORDER BY a.hire_date DESC,
         a.last_name ASC;


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

[User] List all pairs of wallets that use the same private_key. Display w1.wallet_id, w1.user_id, w2.wallet_id, w2.user_id, and the shared private_key.

[Assistant]
SELECT w1.wallet_id AS wallet1_id,
       w1.user_id   AS user1_id,
       w2.wallet_id AS wallet2_id,
       w2.user_id   AS user2_id,
       w1.private_key
FROM web3.wallets w1
JOIN web3.wallets w2
  ON w1.private_key = w2.private_key
 AND w1.wallet_id < w2.wallet_id;

[User] List all pairs of wallets that were created within 10 minutes of each other, showing both wallet IDs, the user_id, and both creation timestamps.

[Assistant]
SELECT
  w1.wallet_id AS wallet1_id,
  w2.wallet_id AS wallet2_id,
  w1.user_id,
  w1.created_at AS created_at1,
  w2.created_at AS created_at2
FROM web3.wallets w1
JOIN web3.wallets w2
  ON w1.user_id = w2.user_id
  AND w1.wallet_id < w2.wallet_id
  AND ABS(EXTRACT(EPOCH FROM (w1.created_at - w2.created_at))) <= 600;

[User] Find pairs of wallet IDs that belong to the same user, showing the user ID and the two wallet IDs.

[Assistant] SELECT w1.user_id, w1.wallet_id AS wallet1_id, w2.wallet_id AS wallet2_id FROM web3.wallets w1 JOIN web3.wallets w2 ON w1.user_id = w2.user_id AND w1.wallet_id < w2.wallet_id;

[User] List all wallet addresses that have the same private key as another wallet, showing the wallet_id, address, and the shared private_key.

[Assistant]
SELECT w1.wallet_id, w1.address, w1.private_key
FROM web3.wallets w1
JOIN web3.wallets w2 ON w1.private_key = w2.private_key AND w1.wallet_id <> w2.wallet_id;

[User] List the user IDs who own more than one wallet and show how many wallets each of them has.

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

[User] Which user has the earliest created wallet? Show the user_id, wallet_id, address, and the creation timestamp.

[Assistant]
SELECT user_id, wallet_id, address, created_at
FROM web3.wallets
ORDER BY created_at ASC
LIMIT 1;

[User] Can you show all users whose earliest wallet was created on '2023-01-01'? Please include their user_id, wallet_id, and wallet address.

[Assistant]
SELECT w.user_id, w.wallet_id, w.address
FROM web3.wallets w
INNER JOIN (
  SELECT user_id, MIN(created_at) AS min_created_at
  FROM web3.wallets
  GROUP BY user_id
) first_wallet ON w.user_id = first_wallet.user_id AND w.created_at = first_wallet.min_created_at
WHERE w.created_at::date = '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )

[User] List the case number and name for all cases that do not have any linked invoices.

[Assistant] SELECT T1.case_number, T1.case_name FROM cases AS T1 LEFT JOIN invoices AS T2 ON T1.case_id = T2.case_id WHERE T2.invoice_id IS NULL;

[User] Also include the date the case was opened, and restrict the list to cases opened after 2023-01-01.

[Assistant] SELECT T1.case_number, T1.case_name, T1.date_opened FROM cases AS T1 LEFT JOIN invoices AS T2 ON T1.case_id = T2.case_id WHERE T2.invoice_id IS NULL AND T1.date_opened > '2023-01-01';

[User] What is the total sum of amounts paid for all invoices?

[Assistant] SELECT SUM(amount_paid) FROM invoices;

[User] Group this total by the status of the invoice.

[Assistant] SELECT status, SUM(amount_paid) FROM invoices GROUP BY status;

[User] Only show statuses where the total amount paid is greater than 50000.

[Assistant] SELECT status, SUM(amount_paid) FROM invoices GROUP BY status HAVING SUM(amount_paid) > 50000;

[User] Order the results by the total paid amount in descending order.

[Assistant] SELECT status, SUM(amount_paid) FROM invoices GROUP BY status HAVING SUM(amount_paid) > 50000 ORDER BY SUM(amount_paid) DESC;

[User] Show all cases that are currently open and have a client whose status is prospect. Include the case_number, the case_name, and the client's full name.

[Assistant]
SELECT cs.case_number, cs.case_name, cl.first_name || ' ' || cl.last_name AS client_full_name
FROM legal_services.cases cs
JOIN legal_services.clients cl ON cs.client_id = cl.client_id
WHERE cs.status = 'Open' AND cl.status = 'prospect';

[User] List the invoice_number, total_amount, the full name of the client, and the case_number for all invoices.

[Assistant]
SELECT i.invoice_number, i.total_amount, c.first_name || ' ' || c.last_name AS client_full_name, cs.case_number
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id
LEFT JOIN legal_services.cases cs ON i.case_id = cs.case_id;

[User] Show only invoices with a total_amount greater than 3000 and issued after January 1st, 2024.

[Assistant]
SELECT i.invoice_number, i.total_amount, c.first_name || ' ' || c.last_name AS client_full_name, cs.case_number
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id
LEFT JOIN legal_services.cases cs ON i.case_id = cs.case_id
WHERE i.total_amount > 3000 AND i.issue_date > '2024-01-01';

[User] Please include only invoices where amount_paid is less than total_amount, and also add the due_date.

[Assistant]
SELECT i.invoice_number, i.total_amount, i.due_date, c.first_name || ' ' || c.last_name AS client_full_name, cs.case_number
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id
LEFT JOIN legal_services.cases cs ON i.case_id = cs.case_id
WHERE i.total_amount > 3000 AND i.issue_date > '2024-01-01' AND i.amount_paid < i.total_amount;

[User] Now, sort the result by due_date in ascending order and show the invoice status as well.

[Assistant]
SELECT i.invoice_number, i.total_amount, i.due_date, i.status, c.first_name || ' ' || c.last_name AS client_full_name, cs.case_number
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id
LEFT JOIN legal_services.cases cs ON i.case_id = cs.case_id
WHERE i.total_amount > 3000 AND i.issue_date > '2024-01-01' AND i.amount_paid < i.total_amount
ORDER BY i.due_date ASC;

[User] List each client_id, first_name, last_name, and the sum of total_amount for all of their invoices.

[Assistant]
SELECT c.client_id,
       c.first_name,
       c.last_name,
       SUM(i.total_amount) AS total_invoiced
FROM legal_services.clients c
JOIN legal_services.invoices i ON i.client_id = c.client_id
GROUP BY c.client_id, c.first_name, c.last_name;

[User] Now show only clients whose total_invoiced exceeds 20000 and include the count of invoices as invoice_count.

[Assistant]
SELECT c.client_id,
       c.first_name,
       c.last_name,
       SUM(i.total_amount) AS total_invoiced,
       COUNT(i.invoice_id) AS invoice_count
FROM legal_services.clients c
JOIN legal_services.invoices i ON i.client_id = c.client_id
GROUP BY c.client_id, c.first_name, c.last_name
HAVING SUM(i.total_amount) > 20000;

[User] Calculate the total amount billed for each client, showing their first name, last name, and the total amount.

[Assistant] SELECT c.first_name, c.last_name, SUM(i.total_amount) FROM legal_services.clients c JOIN legal_services.invoices i ON c.client_id = i.client_id GROUP BY c.client_id, c.first_name, c.last_name;


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

[User] Find all pairs of different routes where the estimated duration in minutes is identical. For each pair, show both route IDs, their route numbers, and the shared duration.

[Assistant] SELECT r1.route_id AS route1_id, r1.route_number AS route1_number, r2.route_id AS route2_id, r2.route_number AS route2_number, r1.estimated_duration_minutes FROM transportation.routes r1 JOIN transportation.routes r2 ON r1.estimated_duration_minutes = r2.estimated_duration_minutes AND r1.route_id < r2.route_id;

[User] Retrieve route_number, description, and distance_km for routes that have a distance greater than the average distance of all routes.

[Assistant]
SELECT route_number, description, distance_km
FROM transportation.routes
WHERE distance_km > (
  SELECT AVG(distance_km)
  FROM transportation.routes
);

[User] Actually, I only want those routes where estimated_duration_minutes is less than 120, and sort by distance_km in descending order.

[Assistant]
SELECT route_number, description, distance_km
FROM transportation.routes
WHERE distance_km > (
  SELECT AVG(distance_km)
  FROM transportation.routes
)
  AND estimated_duration_minutes < 120
ORDER BY distance_km DESC;

[User] Which route numbers connect locations with a distance less than 80 km and more than 5 words in their description? Include the route type in the results.

[Assistant] SELECT route_number, type FROM transportation.routes WHERE distance_km < 80 AND array_length(regexp_split_to_array(description, '\s+'), 1) > 5;

[User] List pairs of distinct routes that originate from the same location but go to different destinations. Show the route ID and route number for both routes and the common origin location ID.

[Assistant]
SELECT
  r1.route_id AS route1_id,
  r1.route_number AS route1_number,
  r2.route_id AS route2_id,
  r2.route_number AS route2_number,
  r1.origin_location_id AS shared_origin_location_id
FROM transportation.routes AS r1
JOIN transportation.routes AS r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id < r2.route_id
WHERE
  r1.destination_location_id != r2.destination_location_id;

[User] Can you show me all routes where the origin_location_id is the same as the destination_location_id? List their route_id, route_number, and type.

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

[User] I'd also like to know the distance_km and estimated_duration_minutes for these routes.

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

[User] Finally, only include those routes where estimated_duration_minutes is less than 30 and sort by distance_km descending.

[Assistant]
SELECT route_id, route_number, type, distance_km, estimated_duration_minutes
FROM transportation.routes
WHERE origin_location_id = destination_location_id
  AND estimated_duration_minutes < 30
ORDER BY distance_km DESC;

[User] Show a list of all routes including their route number, type, distance in km, and estimated duration in minutes.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes;

[User] Filter this list to only show routes of type 'Express'.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes
WHERE
  type = 'Express';

[User] Sort the results by distance in descending order and limit to the top 5.

[Assistant]
SELECT
  route_number,
  type,
  distance_km,
  estimated_duration_minutes
FROM transportation.routes
WHERE
  type = 'Express'
ORDER BY
  distance_km DESC
LIMIT 5;

[User] Add the description and a column 'duration_per_km' showing the duration per kilometer.

[Assistant]
SELECT
  route_number,
  type,
  description,
  distance_km,
  estimated_duration_minutes,
  CAST(estimated_duration_minutes AS NUMERIC) / NULLIF(distance_km, 0) AS duration_per_km
FROM transportation.routes
WHERE
  type = 'Express'
ORDER BY
  distance_km 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.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )

[User] Show me, for each game, the achievement that has been unlocked by the most players. Include the game title, achievement name, and the number of players who unlocked it.

[Assistant] WITH RankedAchievements AS ( SELECT pa.achievement_id, COUNT(pa.player_id) AS unlock_count, ROW_NUMBER() OVER(PARTITION BY a.game_id ORDER BY COUNT(pa.player_id) DESC) as rn FROM player_achievements pa JOIN gaming_technology.achievements a ON pa.achievement_id = a.achievement_id GROUP BY pa.achievement_id, a.game_id ) SELECT g.title AS game_title, a.name AS achievement_name, ra.unlock_count FROM RankedAchievements ra JOIN gaming_technology.achievements a ON ra.achievement_id = a.achievement_id JOIN games g ON a.game_id = g.game_id WHERE ra.rn = 1;

[User] Can you refine this to only show games where the top achievement has been unlocked by at least 50 players?

[Assistant]
SELECT a1.game_id, a1.name AS achv1, a2.name AS achv2
FROM achievements a1
JOIN achievements a2
  ON a1.game_id = a2.game_id
  AND a1.achievement_id < a2.achievement_id;

[User] Only include pairs where the sum of their points exceeds 150.

[Assistant]
SELECT a1.game_id,
       a1.name AS achv1,
       a2.name AS achv2
FROM achievements a1
JOIN achievements a2
  ON a1.game_id = a2.game_id
  AND a1.achievement_id < a2.achievement_id
WHERE a1.points + a2.points > 150;

[User] Exclude any pairs where either achievement is hidden.

[Assistant]
SELECT a1.game_id,
       a1.name AS achv1,
       a2.name AS achv2
FROM achievements a1
JOIN achievements a2
  ON a1.game_id = a2.game_id
  AND a1.achievement_id < a2.achievement_id
WHERE a1.points + a2.points > 150
  AND a1.hidden = false
  AND a2.hidden = false;

[User] Finally, order the results by the combined points descending.

[Assistant]
SELECT a1.game_id,
       a1.name AS achv1,
       a2.name AS achv2
FROM achievements a1
JOIN achievements a2
  ON a1.game_id = a2.game_id
  AND a1.achievement_id < a2.achievement_id
WHERE a1.points + a2.points > 150
  AND a1.hidden = false
  AND a2.hidden = false
ORDER BY (a1.points + a2.points) DESC;

[User] List all achievements with their name, points, and the title of the game they belong to.

[Assistant] SELECT a.name AS achievement_name, a.points, g.title AS game_title FROM gaming_technology.achievements a JOIN games g ON a.game_id = g.game_id;

[User] Filter this list to only show achievements with more than 50 points.

[Assistant] SELECT a.name AS achievement_name, a.points, g.title AS game_title FROM gaming_technology.achievements a JOIN games g ON a.game_id = g.game_id WHERE a.points > 50;

[User] Retrieve each game_id alongside the achievement with the highest points, showing its name and points.

[Assistant]
SELECT a.game_id,
       a.name,
       a.points
FROM achievements a
JOIN (
  SELECT game_id,
         MAX(points) AS max_points
  FROM achievements
  GROUP BY game_id
) m ON a.game_id = m.game_id
   AND a.points = m.max_points;

[User] Exclude hidden achievements and only include games where that top achievement has at least 80 points.

[Assistant]
SELECT a.game_id,
       a.name,
       a.points
FROM achievements a
JOIN (
  SELECT game_id,
         MAX(points) AS max_points
  FROM achievements
  WHERE hidden = false
  GROUP BY game_id
) m ON a.game_id = m.game_id
   AND a.points = m.max_points
WHERE a.hidden = false
  AND a.points >= 80
ORDER BY a.points DESC;

[User] Retrieve pairs of visible achievements from the same game along with their point difference.

[Assistant]
SELECT a.achievement_id AS ach1_id,
       b.achievement_id AS ach2_id,
       a.name           AS ach1_name,
       b.name           AS ach2_name,
       ABS(a.points - b.points) AS point_difference
FROM gaming_technology.achievements a
JOIN gaming_technology.achievements b
  ON a.game_id = b.game_id
  AND a.hidden = false
  AND b.hidden = false
  AND a.achievement_id < b.achievement_id;

[User] Only include pairs where the point_difference exceeds 20.

[Assistant]
SELECT a.achievement_id AS ach1_id,
       b.achievement_id AS ach2_id,
       a.name           AS ach1_name,
       b.name           AS ach2_name,
       ABS(a.points - b.points) AS point_difference
FROM gaming_technology.achievements a
JOIN gaming_technology.achievements b
  ON a.game_id = b.game_id
  AND a.hidden = false
  AND b.hidden = false
  AND a.achievement_id < b.achievement_id
WHERE ABS(a.points - b.points) > 20;

[User] Also display the game_id in the result.

[Assistant]
SELECT a.game_id,
       a.achievement_id AS ach1_id,
       b.achievement_id AS ach2_id,
       a.name           AS ach1_name,
       b.name           AS ach2_name,
       ABS(a.points - b.points) AS point_difference
FROM gaming_technology.achievements a
JOIN gaming_technology.achievements b
  ON a.game_id = b.game_id
  AND a.hidden = false
  AND b.hidden = false
  AND a.achievement_id < b.achievement_id
WHERE ABS(a.points - b.points) > 20;

[User] Order by point_difference descending, then by ach1_name ascending.

[Assistant]
SELECT a.game_id,
       a.achievement_id AS ach1_id,
       b.achievement_id AS ach2_id,
       a.name           AS ach1_name,
       b.name           AS ach2_name,
       ABS(a.points - b.points) AS point_difference
FROM gaming_technology.achievements a
JOIN gaming_technology.achievements b
  ON a.game_id = b.game_id
  AND a.hidden = false
  AND b.hidden = false
  AND a.achievement_id < b.achievement_id
WHERE ABS(a.points - b.points) > 20
ORDER BY point_difference DESC, ach1_name ASC;

[User] List all achievements with more than 100 points.

[Assistant]
SELECT *
FROM gaming_technology.achievements
WHERE points > 100;

[User] Now exclude any hidden achievements.

[Assistant]
SELECT *
FROM gaming_technology.achievements
WHERE points > 100
  AND hidden = false;

[User] Only show the columns achievement_id, name, and points.

[Assistant]
SELECT achievement_id, name, points
FROM gaming_technology.achievements
WHERE points > 100
  AND hidden = false;

[User] Order the output by points in descending order and limit to top 5.

[Assistant]
SELECT achievement_id, name, points
FROM gaming_technology.achievements
WHERE points > 100
  AND hidden = false
ORDER BY points 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 government_services.agencies (
    agency_id character varying(64) NOT NULL, -- unique identifier for the agency
    agency_name character varying(255) NOT NULL, -- full name of the government agency
    jurisdiction_level character varying(50) NOT NULL, -- e.g., Federal, State, County, City
    primary_contact_email character varying(128),
    main_phone_number character varying(32),
    website_url character varying(255),
    established_date date,
    parent_agency_id character varying(64), -- FK to self for hierarchical structure
    PRIMARY KEY (agency_id)
)
CREATE TABLE government_services.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)

[User] List the agency names and addresses for all service locations in the state of 'Florida'.

[Assistant]
SELECT a.agency_name, l.address
FROM government_services.service_locations l
JOIN government_services.agencies a ON l.agency_id = a.agency_id
WHERE l.state = 'Florida';

[User] Which agencies have at least one service location in a city named 'Austin', and what are their agency names and main phone numbers?

[Assistant]
SELECT DISTINCT a.agency_id, a.agency_name, a.main_phone_number
FROM government_services.agencies a
JOIN government_services.service_locations l ON a.agency_id = l.agency_id
WHERE l.city = 'Austin';

[User] How many documents are set to expire in the year 2025?

[Assistant]
SELECT COUNT(*) AS document_count
FROM government_services.documents
WHERE expiry_date >= '2025-01-01' AND expiry_date < '2026-01-01';

[User] For each application that has pending documents, list the application's reference_number and the corresponding service_name. Only include documents with verification_status = 'Pending'.

[Assistant]
SELECT DISTINCT a.reference_number, s.service_name
FROM government_services.applications a
JOIN government_services.documents d ON a.application_id = d.application_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE d.verification_status = 'Pending';

[User] Get the name of each agency and the count of accessible service locations it operates in. Only include agencies that have more than two accessible locations.

[Assistant]
SELECT a.agency_name, COUNT(sl.location_id) AS accessible_locations
FROM government_services.agencies a
JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.is_accessible = TRUE
GROUP BY a.agency_name
HAVING COUNT(sl.location_id) > 2;

[User] Modify the query so that it counts distinct cities instead of locations.

[Assistant]
SELECT a.agency_name, COUNT(DISTINCT sl.city) AS accessible_cities
FROM government_services.agencies a
JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.is_accessible = TRUE
GROUP BY a.agency_name
HAVING COUNT(DISTINCT sl.city) > 2;

[User] List the reference number and status for all applications that have at least one document associated with them.

[Assistant] SELECT DISTINCT a.reference_number, a.status FROM government_services.applications AS a JOIN government_services.documents AS d ON a.application_id = d.application_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 insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )

[User] Retrieve the policy_number, start_date, end_date, premium_amount, and corresponding product_name for policies with a coverage_limit greater than 500000.

[Assistant]
SELECT p.policy_number, p.start_date, p.end_date, p.premium_amount, ip.product_name
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.coverage_limit > 500000;

[User] List policy_number, customer_id, and product_name for policies that are currently active.

[Assistant]
SELECT p.policy_number, p.customer_id, ip.product_name
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'Active' AND ip.is_active = true;

[User] Actually, only show those policies that will expire within the next 30 days.

[Assistant]
SELECT p.policy_number, p.customer_id, ip.product_name
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'Active'
  AND ip.is_active = true
  AND p.end_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days';

[User] Also, include the product_type and only for products of type 'Life'.

[Assistant]
SELECT p.policy_number, p.customer_id, ip.product_name, ip.product_type
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'Active'
  AND ip.is_active = true
  AND p.end_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND ip.product_type = 'Life';

[User] Sort the final results by end_date ascending, please.

[Assistant]
SELECT p.policy_number, p.customer_id, ip.product_name, ip.product_type, p.end_date
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'Active'
  AND ip.is_active = true
  AND p.end_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND ip.product_type = 'Life'
ORDER BY p.end_date ASC;

[User] List the product_id, product_name, and base_premium for all products that are currently inactive.

[Assistant]
SELECT product_id, product_name, base_premium
FROM insurance.insurance_products
WHERE is_active = false;

[User] Show me all insurance products of type 'Travel', including their product_id, product_name, and base_premium.

[Assistant]
SELECT product_id, product_name, base_premium
FROM insurance.insurance_products
WHERE product_type = 'Travel';

[User] Which policies have a premium amount greater than the base premium of their respective insurance product? Please show the policy_number, premium_amount, product_name, and base_premium.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
INNER JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.premium_amount > ip.base_premium;

[User] Now, only include policies where the coverage_limit is above 500,000.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
INNER JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.premium_amount > ip.base_premium
  AND p.coverage_limit > 500000;

[User] Actually, I also want to see only active policies.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
INNER JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.premium_amount > ip.base_premium
  AND p.coverage_limit > 500000
  AND p.status = 'Active';

[User] Could you sort the results by premium_amount in descending order?

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
INNER JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.premium_amount > ip.base_premium
  AND p.coverage_limit > 500000
  AND p.status = 'Active'
ORDER BY p.premium_amount DESC;

[User] List active policies where the premium amount is greater than the base premium of the linked insurance product. Show policy number, policy premium, product name, and product base premium.

[Assistant] SELECT T1.policy_number, T1.premium_amount, T2.product_name, T2.base_premium FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T1.status = 'active' AND T1.premium_amount > T2.base_premium;

[User] Also, only include policies that were issued in the year 2023.

[Assistant] SELECT T1.policy_number, T1.premium_amount, T2.product_name, T2.base_premium FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T1.status = 'active' AND T1.premium_amount > T2.base_premium AND EXTRACT(YEAR FROM T1.issued_at) = 2023;

[User] Could you sort the results by policy premium in descending order and limit to the top 10?

[Assistant] SELECT T1.policy_number, T1.premium_amount, T2.product_name, T2.base_premium FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T1.status = 'active' AND T1.premium_amount > T2.base_premium AND EXTRACT(YEAR FROM T1.issued_at) = 2023 ORDER BY T1.premium_amount DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] Find application IDs that have received notifications with both a 'Sent' status and a 'Failed' status.

[Assistant] SELECT application_id FROM government_services.notifications WHERE status IN ('Sent', 'Failed') GROUP BY application_id HAVING COUNT(DISTINCT status) = 2;

[User] For each notification, list its notification_id, message_subject, and the message_subject of the notification it relates to (assuming related_entity_type = 'notification').

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id;

[User] Only include notifications with status = 'Sent'.

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id
WHERE n.status = 'Sent';

[User] List the IDs of citizens who have received notifications related to more than one distinct type of entity.

[Assistant] SELECT citizen_id FROM government_services.notifications WHERE related_entity_type IS NOT NULL AND related_entity_type != '' GROUP BY citizen_id HAVING COUNT(DISTINCT related_entity_type) > 1;

[User] For each application that has at least one failed notification, provide the application ID, the total number of notifications received for that application, and the count of failed notifications.

[Assistant] SELECT application_id, COUNT(*) AS total_notifications, COUNT(CASE WHEN status = 'Failed' THEN 1 END) AS failed_notifications FROM government_services.notifications GROUP BY application_id HAVING COUNT(CASE WHEN status = 'Failed' THEN 1 END) > 0;

[User] For each citizen, find the timestamp of their first 'SMS' notification and their first 'Email' notification. Show citizen_id, first_sms_at, and first_email_at.

[Assistant]
SELECT citizen_id,
       MIN(sent_at) FILTER (WHERE channel = 'SMS')   AS first_sms_at,
       MIN(sent_at) FILTER (WHERE channel = 'Email') AS first_email_at
FROM government_services.notifications
GROUP BY citizen_id;

[User] Find pairs of notifications for the same citizen where one was sent via 'Email' and another via 'SMS'. Display citizen_id, email_notification_id, sms_notification_id, email_sent_at, and sms_sent_at.

[Assistant]
SELECT e.citizen_id,
       e.notification_id AS email_notification_id,
       s.notification_id AS sms_notification_id,
       e.sent_at           AS email_sent_at,
       s.sent_at           AS sms_sent_at
FROM government_services.notifications e
JOIN government_services.notifications s
  ON e.citizen_id = s.citizen_id
 AND e.channel = 'Email'
 AND s.channel = 'SMS';


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] Which achievements have the highest unlock counts? List the top 5 achievement names along with the number of distinct players who unlocked each.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name
ORDER BY player_count DESC
LIMIT 5;

[User] Only exclude hidden achievements from the ranking.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
WHERE a.hidden = FALSE
GROUP BY a.name
ORDER BY player_count DESC
LIMIT 5;

[User] Now include only achievements unlocked by at least 50 players and order by player_count descending.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
WHERE a.hidden = FALSE
GROUP BY a.name
HAVING COUNT(DISTINCT pa.player_id) >= 50
ORDER BY player_count DESC;

[User] For each in-game item type, display the item type, total quantity held by players, and the average cost amount of those items.

[Assistant]
SELECT i.item_type,
       COALESCE(SUM(pi.quantity), 0) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
GROUP BY i.item_type;

[User] Now restrict to items with rarity 'Epic'.

[Assistant]
SELECT i.item_type,
       COALESCE(SUM(pi.quantity), 0) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.rarity = 'Epic'
GROUP BY i.item_type;

[User] Also exclude any groups where the average cost_amount is less than 100.

[Assistant]
SELECT i.item_type,
       SUM(pi.quantity) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.rarity = 'Epic'
GROUP BY i.item_type
HAVING AVG(i.cost_amount) >= 100;

[User] Please order the results by total_quantity descending.

[Assistant]
SELECT i.item_type,
       SUM(pi.quantity) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.rarity = 'Epic'
GROUP BY i.item_type
HAVING AVG(i.cost_amount) >= 100
ORDER BY total_quantity DESC;

[User] For each game, show the game title, the total duration of all sessions in seconds, and the average score.

[Assistant] SELECT g.title, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Could you also show the total number of sessions for each game?

[Assistant] SELECT g.title, COUNT(gs.session_id) AS total_sessions, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Filter the results to only include games with more than 100 sessions.

[Assistant] SELECT g.title, COUNT(gs.session_id) AS total_sessions, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title HAVING COUNT(gs.session_id) > 100;


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

[User] Find all ERC20 tokens (from token_metas) currently held by wallet '0xfoo...' with a balance over 1000. Show the contract address and amount.

[Assistant]
SELECT contract_address, amount
FROM erc20_balances
WHERE wallet_address = '0xfoo...'
  AND CAST(amount AS NUMERIC) > 1000;

[User] Add the symbol and name for each token by joining to token_metas.

[Assistant]
SELECT b.contract_address, b.amount, m.symbol, m.name
FROM erc20_balances b
JOIN token_metas m ON b.contract_address = m.contract_address
WHERE b.wallet_address = '0xfoo...'
  AND CAST(b.amount AS NUMERIC) > 1000;

[User] Actually, I want the results sorted by amount descending and limit to the top 5 tokens.

[Assistant]
SELECT b.contract_address, b.amount, m.symbol, m.name
FROM erc20_balances b
JOIN token_metas m ON b.contract_address = m.contract_address
WHERE b.wallet_address = '0xfoo...'
  AND CAST(b.amount AS NUMERIC) > 1000
ORDER BY CAST(b.amount AS NUMERIC) DESC
LIMIT 5;

[User] Can you also include how many decimal places each token uses?

[Assistant]
SELECT b.contract_address, b.amount, m.symbol, m.name, m.decimals
FROM erc20_balances b
JOIN token_metas m ON b.contract_address = m.contract_address
WHERE b.wallet_address = '0xfoo...'
  AND CAST(b.amount AS NUMERIC) > 1000
ORDER BY CAST(b.amount AS NUMERIC) DESC
LIMIT 5;

[User] Show the symbol, name, and total supply for all SUI coins with status 'active'.

[Assistant]
SELECT scm.symbol, scm.name, scm.coin_type, scm.total_supply
FROM sui_coins_metadata scm
WHERE scm.status = 'active';

[User] I received an error that column 'total_supply' doesn't exist in sui_coins_metadata.

[Assistant]
SELECT scm.symbol, scm.name, scm.coin_type
FROM sui_coins_metadata scm
WHERE scm.status = 'active';

[User] Now, join with sui_coins to add up the total balance across all owners for each coin_type.

[Assistant]
SELECT scm.symbol, scm.name, scm.coin_type, SUM(CAST(sc.balance AS NUMERIC)) AS total_balance
FROM sui_coins_metadata scm
JOIN sui_coins sc ON scm.coin_type = sc.coin_type
WHERE scm.status = 'active'
GROUP BY scm.symbol, scm.name, scm.coin_type;

[User] List all Avalanche tokens where the circulating total supply is less than the maximum supply. Include tick, creator, max_supply, total_supply (sum of amount), and the difference between max_supply and total_supply.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick;

[User] Also include the number of holders and number of transactions (holders and txs) for each token.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff,
       bi.holders,
       bi.txs
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick;

[User] Now restrict to tokens where the supply difference is greater than 1000 and only include records where the info block_number is above 500000.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff,
       bi.holders,
       bi.txs
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick
WHERE (bi.max_supply - COALESCE(tb.total_supply, 0)) > 1000
  AND bi.block_number > 500000;

[User] Finally, sort the results by supply_diff descending and limit to the top 5 tokens.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff,
       bi.holders,
       bi.txs
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick
WHERE (bi.max_supply - COALESCE(tb.total_supply, 0)) > 1000
  AND bi.block_number > 500000
ORDER BY supply_diff DESC
LIMIT 5;

[User] Show the total balance for each SUI coin across all owners. Group by coin_type.

[Assistant]
SELECT coin_type,
       SUM(CAST(balance AS DECIMAL)) AS total_balance
FROM sui_coins
GROUP BY coin_type;

[User] Also include symbol, name, decimals and description from the metadata table by joining on coin_type.

[Assistant]
SELECT sc.coin_type,
       scm.symbol,
       scm.name,
       scm.decimals,
       scm.description,
       SUM(CAST(sc.balance AS DECIMAL)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata scm
  ON sc.coin_type = scm.coin_type
GROUP BY sc.coin_type, scm.symbol, scm.name, scm.decimals, scm.description;

[User] Only include metadata entries where status = 'exists' and description contains the word 'staking'.

[Assistant]
SELECT sc.coin_type,
       scm.symbol,
       scm.name,
       scm.decimals,
       scm.description,
       SUM(CAST(sc.balance AS DECIMAL)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata scm
  ON sc.coin_type = scm.coin_type
WHERE scm.status = 'exists'
  AND scm.description ILIKE '%staking%'
GROUP BY sc.coin_type, scm.symbol, scm.name, scm.decimals, scm.description;

[User] Sort the results by total_balance descending and limit to the top 3 coins.

[Assistant]
SELECT sc.coin_type,
       scm.symbol,
       scm.name,
       scm.decimals,
       scm.description,
       SUM(CAST(sc.balance AS DECIMAL)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata scm
  ON sc.coin_type = scm.coin_type
WHERE scm.status = 'exists'
  AND scm.description ILIKE '%staking%'
GROUP BY sc.coin_type, scm.symbol, scm.name, scm.decimals, scm.description
ORDER BY total_balance DESC
LIMIT 3;

[User] Which ERC20 tokens have more than 8 decimals? Show their symbol, name, and decimals.

[Assistant] SELECT symbol, name, decimals FROM token_metas WHERE decimals > 8;

[User] Can you also show the contract address and the total supply for each of these tokens?

[Assistant] SELECT contract_address, symbol, name, decimals, total_supply FROM token_metas WHERE decimals > 8;

[User] Now, include only tokens where total_supply is greater than '100000000000' and order the results by total_supply descending.

[Assistant] SELECT contract_address, symbol, name, decimals, total_supply FROM token_metas WHERE decimals > 8 AND CAST(total_supply AS NUMERIC) > 100000000000 ORDER BY CAST(total_supply AS NUMERIC) DESC;

[User] Show me the is_proxy field for each token as well.

[Assistant] SELECT contract_address, symbol, name, decimals, total_supply, is_proxy FROM token_metas WHERE decimals > 8 AND CAST(total_supply AS NUMERIC) > 100000000000 ORDER BY CAST(total_supply AS NUMERIC) DESC;

[User] For each ERC1155 NFT contract on Ethereum, show the contract address, token_id, and the total amount held across all wallets.

[Assistant] SELECT nh.contract_address, nh.token_id, SUM(CAST(nh.amount AS NUMERIC)) AS total_amount FROM nft_holder_historical nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_type = 'ERC1155' AND nm.blockchain = 'Ethereum' GROUP BY nh.contract_address, nh.token_id;

[User] Include the name of each NFT from the nft_metadata table as well.

[Assistant] SELECT nh.contract_address, nh.token_id, nm.name, SUM(CAST(nh.amount AS NUMERIC)) AS total_amount FROM nft_holder_historical nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_type = 'ERC1155' AND nm.blockchain = 'Ethereum' GROUP BY nh.contract_address, nh.token_id, nm.name;

[User] Only include NFTs where the total amount held exceeds 500, and order the results by total_amount descending.

[Assistant] SELECT nh.contract_address, nh.token_id, nm.name, SUM(CAST(nh.amount AS NUMERIC)) AS total_amount FROM nft_holder_historical nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_type = 'ERC1155' AND nm.blockchain = 'Ethereum' GROUP BY nh.contract_address, nh.token_id, nm.name HAVING SUM(CAST(nh.amount AS NUMERIC)) > 500 ORDER BY total_amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )

[User] Show all payments along with the guest's first and last name, and the staff member who processed each payment. Include payment_id, amount, currency_code, payment_timestamp, guest first_name, guest last_name, staff first_name, and staff last_name.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       p.payment_timestamp,
       g.first_name AS guest_first_name,
       g.last_name AS guest_last_name,
       s.first_name AS staff_first_name,
       s.last_name AS staff_last_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id;

[User] Filter to only include payments with status = 'Succeeded' and amount greater than 100.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       p.payment_timestamp,
       g.first_name AS guest_first_name,
       g.last_name AS guest_last_name,
       s.first_name AS staff_first_name,
       s.last_name AS staff_last_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id
WHERE p.status = 'Succeeded'
  AND p.amount > 100;

[User] Also order the results by amount descending and limit to the top 10 payments.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       p.payment_timestamp,
       g.first_name AS guest_first_name,
       g.last_name AS guest_last_name,
       s.first_name AS staff_first_name,
       s.last_name AS staff_last_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id
WHERE p.status = 'Succeeded'
  AND p.amount > 100
ORDER BY p.amount DESC
LIMIT 10;

[User] Get the total number of guests for each country_code.

[Assistant]
SELECT country_code, COUNT(*) AS guest_count
FROM hospitality_technology.guests
GROUP BY country_code;

[User] Actually, only include countries with at least 5 guests and order by guest_count descending.

[Assistant]
SELECT country_code, COUNT(*) AS guest_count
FROM hospitality_technology.guests
GROUP BY country_code
HAVING COUNT(*) >= 5
ORDER BY guest_count DESC;

[User] List all reviews for properties with a star rating of at least 4.5. Include the property_name, review_id, rating_overall, and review_date.

[Assistant]
SELECT p.property_name, r.review_id, r.rating_overall, r.review_date
FROM hospitality_technology.reviews r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE p.star_rating >= 4.5;

[User] Which staff members processed payments for guests who live in California? I need their names and the corresponding guest names.

[Assistant] SELECT DISTINCT st.first_name AS staff_first_name, st.last_name AS staff_last_name, g.first_name AS guest_first_name, g.last_name AS guest_last_name FROM hospitality_technology.payments p INNER JOIN hospitality_technology.staff st ON p.staff_id_processed = st.staff_id INNER JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id WHERE g.state_province = 'CA';

[User] Include only staff members who are currently active.

[Assistant] SELECT DISTINCT st.first_name AS staff_first_name, st.last_name AS staff_last_name, g.first_name AS guest_first_name, g.last_name AS guest_last_name FROM hospitality_technology.payments p INNER JOIN hospitality_technology.staff st ON p.staff_id_processed = st.staff_id INNER JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id WHERE g.state_province = 'CA' AND st.is_active = TRUE;

[User] Actually, could you also show the payment amount and sort the results by amount descending?

[Assistant] SELECT st.first_name AS staff_first_name, st.last_name AS staff_last_name, g.first_name AS guest_first_name, g.last_name AS guest_last_name, p.amount FROM hospitality_technology.payments p INNER JOIN hospitality_technology.staff st ON p.staff_id_processed = st.staff_id INNER JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id WHERE g.state_province = 'CA' AND st.is_active = TRUE ORDER BY p.amount DESC;

[User] Show the names and emails of all guests who have communication consent enabled.

[Assistant] SELECT first_name, last_name, email FROM hospitality_technology.guests WHERE communication_consent = TRUE;

[User] Only include guests who have a loyalty member ID.

[Assistant] SELECT first_name, last_name, email FROM hospitality_technology.guests WHERE communication_consent = TRUE AND loyalty_member_id IS NOT NULL;

[User] Which staff members are managing properties, and what are the names and email addresses of those properties?

[Assistant] SELECT s.staff_id, s.first_name, s.last_name, p.property_name, p.email_address FROM hospitality_technology.staff s INNER JOIN hospitality_technology.properties p ON s.staff_id = p.manager_staff_id;

[User] Only include properties located in the United States and list the staff position as well.

[Assistant] SELECT s.staff_id, s.first_name, s.last_name, s.position, p.property_name, p.email_address FROM hospitality_technology.staff s INNER JOIN hospitality_technology.properties p ON s.staff_id = p.manager_staff_id WHERE p.country_code = 'US';


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.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )

[User] List all pairs of hashtags created within the same hour, including both hashtag IDs and their creation timestamps.

[Assistant] SELECT h1.hashtag_id AS hashtag1_id, h1.created_at AS created1, h2.hashtag_id AS hashtag2_id, h2.created_at AS created2 FROM hashtags h1 JOIN hashtags h2 ON date_trunc('hour', h1.created_at) = date_trunc('hour', h2.created_at) AND h1.hashtag_id < h2.hashtag_id;

[User] Actually, I also want to include the time difference in minutes between the two hashtags.

[Assistant] SELECT h1.hashtag_id AS hashtag1_id, h1.created_at AS created1, h2.hashtag_id AS hashtag2_id, h2.created_at AS created2, EXTRACT(EPOCH FROM (h2.created_at - h1.created_at)) / 60 AS diff_minutes FROM hashtags h1 JOIN hashtags h2 ON date_trunc('hour', h1.created_at) = date_trunc('hour', h2.created_at) AND h1.hashtag_id < h2.hashtag_id;

[User] Also, filter to only include pairs where both tag names start with the letter 'T'.

[Assistant] SELECT h1.hashtag_id AS hashtag1_id, h1.tag_name AS tag1, h2.hashtag_id AS hashtag2_id, h2.tag_name AS tag2, EXTRACT(EPOCH FROM (h2.created_at - h1.created_at)) / 60 AS diff_minutes FROM hashtags h1 JOIN hashtags h2 ON date_trunc('hour', h1.created_at) = date_trunc('hour', h2.created_at) AND h1.hashtag_id < h2.hashtag_id WHERE h1.tag_name LIKE 'T%' AND h2.tag_name LIKE 'T%';

[User] Finally, order the results by the earlier creation timestamp in descending order.

[Assistant] SELECT h1.hashtag_id AS hashtag1_id, h1.tag_name AS tag1, h2.hashtag_id AS hashtag2_id, h2.tag_name AS tag2, EXTRACT(EPOCH FROM (h2.created_at - h1.created_at)) / 60 AS diff_minutes FROM hashtags h1 JOIN hashtags h2 ON date_trunc('hour', h1.created_at) = date_trunc('hour', h2.created_at) AND h1.hashtag_id < h2.hashtag_id WHERE h1.tag_name LIKE 'T%' AND h2.tag_name LIKE 'T%' ORDER BY LEAST(h1.created_at, h2.created_at) DESC;

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

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

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

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

[User] How many distinct posts does each hashtag appear in?

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

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

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

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

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

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

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

[User] List the tag names and creation dates for all hashtags created on June 12, 2024.

[Assistant] SELECT tag_name, created_at FROM social_media.hashtags WHERE created_at::date = '2024-06-12';

[User] Please also include the hashtag IDs and order by tag name alphabetically.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE created_at::date = '2024-06-12' ORDER BY tag_name ASC;

[User] Show me all hashtag IDs and their tag names that were created after June 10, 2024 and whose tag names contain the word 'dev'.

[Assistant] SELECT hashtag_id, tag_name FROM social_media.hashtags WHERE created_at > '2024-06-10' AND tag_name ILIKE '%dev%';

[User] Can you also include the creation timestamp and order the results by created_at ascending?

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE created_at > '2024-06-10' AND tag_name ILIKE '%dev%' ORDER BY created_at ASC;

[User] Actually, only show hashtags where the tag name starts with the letter 'D'.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE created_at > '2024-06-10' AND tag_name ILIKE 'D%' ORDER BY created_at ASC;

[User] Limit the results to the top 8 hashtags.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE created_at > '2024-06-10' AND tag_name ILIKE 'D%' ORDER BY created_at ASC LIMIT 8;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)

[User] Find cases where an address received tokens in one transfer and then sent tokens in another. List the receive transfer_id, the send transfer_id, the address, and both transfer values.

[Assistant]
SELECT recv.transfer_id AS receive_transfer_id,
       send.transfer_id AS send_transfer_id,
       recv.to_address AS address,
       recv.value       AS received_value,
       send.value       AS sent_value
FROM web3.token_transfers recv
JOIN web3.token_transfers send
  ON recv.to_address = send.from_address;

[User] Find pairs of distinct token transfers that occurred in the same transaction and were initiated by the same sender address. List the transaction ID, the common sender address, and both transfer IDs.

[Assistant]
SELECT
  t1.transaction_id,
  t1.from_address,
  t1.transfer_id AS transfer_id_1,
  t2.transfer_id AS transfer_id_2
FROM web3.token_transfers AS t1
JOIN web3.token_transfers AS t2
  ON t1.transaction_id = t2.transaction_id
  AND t1.from_address = t2.from_address
WHERE
  t1.transfer_id < t2.transfer_id;

[User] For each sender address, count how many distinct tokens they have transferred. Show from_address and token_count.

[Assistant]
SELECT from_address, COUNT(DISTINCT token_id) AS token_count
FROM web3.token_transfers
GROUP BY from_address;

[User] Now filter to only include senders who have transferred more than 5 distinct tokens.

[Assistant]
SELECT from_address, COUNT(DISTINCT token_id) AS token_count
FROM web3.token_transfers
GROUP BY from_address
HAVING COUNT(DISTINCT token_id) > 5;

[User] For each token, show the token_id and the total number of unique addresses that have ever received it.

[Assistant]
SELECT token_id, COUNT(DISTINCT to_address) AS unique_recipients
FROM web3.token_transfers
GROUP BY token_id;

[User] List all token transfers with a value greater than 1000000. Show transfer ID, token ID, from address, to address, and value.

[Assistant]
SELECT
  transfer_id,
  token_id,
  from_address,
  to_address,
  value
FROM web3.token_transfers
WHERE
  value > 1000000;

[User] Now, only show transfers for token ID '0xabc...xyz'.

[Assistant]
SELECT
  transfer_id,
  token_id,
  from_address,
  to_address,
  value
FROM web3.token_transfers
WHERE
  value > 1000000
  AND token_id = '0xabc...xyz';

[User] List all token transfers between two distinct addresses, showing transfer_id, from_address, to_address, value, and transaction_id.

[Assistant]
SELECT transfer_id, from_address, to_address, value, transaction_id
FROM web3.token_transfers
WHERE from_address <> to_address;

[User] Actually, I only want to see transfers where the value transferred is greater than 1000 tokens.

[Assistant]
SELECT transfer_id, from_address, to_address, value, transaction_id
FROM web3.token_transfers
WHERE from_address <> to_address AND value > 1000;


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

[User] Show me the appointment ID, start time, and subject for all appointments scheduled with lawyer 'lawyer123'.

[Assistant] SELECT appointment_id, start_time, subject FROM legal_services.appointments WHERE lawyer_id = 'lawyer123';

[User] Only include those appointments where the status is 'Scheduled'.

[Assistant] SELECT appointment_id, start_time, subject FROM legal_services.appointments WHERE lawyer_id = 'lawyer123' AND status = 'Scheduled';

[User] Further filter to only show appointments starting after '2024-07-01'.

[Assistant] SELECT appointment_id, start_time, subject FROM legal_services.appointments WHERE lawyer_id = 'lawyer123' AND status = 'Scheduled' AND start_time > '2024-07-01';

[User] Show me the subject and start times of all appointments along with the corresponding lawyer IDs for each client.

[Assistant] SELECT client_id, lawyer_id, subject, start_time FROM legal_services.appointments;

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

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

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

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

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

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

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

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

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

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

[User] What is the count of appointments for each lawyer? Display the lawyer ID and the total count.

[Assistant] SELECT lawyer_id, COUNT(*) AS appointment_count FROM legal_services.appointments GROUP BY lawyer_id;

[User] Only show lawyers who have more than 5 appointments.

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

[User] Consider only appointments that were created in the year 2023.

[Assistant] SELECT lawyer_id, COUNT(*) AS appointment_count FROM legal_services.appointments WHERE created_at BETWEEN '2023-01-01 00:00:00' AND '2023-12-31 23:59:59' GROUP BY lawyer_id HAVING COUNT(*) > 5;

[User] Order the results by the appointment count in descending order.

[Assistant] SELECT lawyer_id, COUNT(*) AS appointment_count FROM legal_services.appointments WHERE created_at BETWEEN '2023-01-01 00:00:00' AND '2023-12-31 23:59:59' GROUP BY lawyer_id HAVING COUNT(*) > 5 ORDER BY appointment_count DESC;

[User] How many appointments have a status of 'Cancelled'?

[Assistant] SELECT COUNT(*) FROM legal_services.appointments WHERE status = 'Cancelled';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
  "CREATE TABLE token_dexpool_info (",
    "pair_address character varying(512) NOT NULL, -- the id of dexpool",
    "token_name character varying(100) NOT NULL, -- the name of the token in the dexpool",
    "token_symbol character varying(100) NOT NULL, -- the token's symbol",
    "chain text, -- the chain that the dexpool resides",
    "price double precision, -- the current price of the token",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour",
    "price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours",
    "makers_24h double precision, -- the makers of the dex pool in 24 hours",
    "volume_24h double precision, -- the trade volume of the dex pool in 24 hours",
    "liquidity double precision, -- the liquidity of the dex pool",
    "market_cap double precision, -- the market cap of the token",
    "trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token.",
    ",PRIMARY KEY (pair_address, chain);"

[User] For each chain, find the token with the highest price and the token with the lowest price. List chain, high_price_token, max_price, low_price_token, and min_price.

[Assistant]
WITH max_prices AS (
  SELECT chain,
         token_symbol AS high_price_token,
         price AS max_price
  FROM token_dexpool_info t1
  WHERE price = (
    SELECT MAX(price)
    FROM token_dexpool_info t2
    WHERE t2.chain = t1.chain
  )
),
min_prices AS (
  SELECT chain,
         token_symbol AS low_price_token,
         price AS min_price
  FROM token_dexpool_info t1
  WHERE price = (
    SELECT MIN(price)
    FROM token_dexpool_info t2
    WHERE t2.chain = t1.chain
  )
)
SELECT m.chain,
       m.high_price_token,
       m.max_price,
       n.low_price_token,
       n.min_price
FROM max_prices m
JOIN min_prices n
  ON m.chain = n.chain;

[User] Exclude any chain where min_price is below 0.01 and only show the top 3 chains by max_price descending.

[Assistant]
WITH max_prices AS (
  SELECT chain,
         token_symbol AS high_price_token,
         price AS max_price
  FROM token_dexpool_info t1
  WHERE price = (
    SELECT MAX(price)
    FROM token_dexpool_info t2
    WHERE t2.chain = t1.chain
  )
),
min_prices AS (
  SELECT chain,
         token_symbol AS low_price_token,
         price AS min_price
  FROM token_dexpool_info t1
  WHERE price = (
    SELECT MIN(price)
    FROM token_dexpool_info t2
    WHERE t2.chain = t1.chain
  )
)
SELECT m.chain,
       m.high_price_token,
       m.max_price,
       n.low_price_token,
       n.min_price
FROM max_prices m
JOIN min_prices n
  ON m.chain = n.chain
WHERE n.min_price >= 0.01
ORDER BY m.max_price DESC
LIMIT 3;

[User] List the top 5 tokens by liquidity on the Ethereum chain. Show token_symbol, liquidity, and price.

[Assistant]
SELECT token_symbol, liquidity, price
FROM token_dexpool_info
WHERE chain = 'Ethereum'
ORDER BY liquidity DESC
LIMIT 5;

[User] List the top 3 tokens by liquidity on BSC and show their token symbols, prices, market cap, and liquidity.

[Assistant]
SELECT token_symbol, price, market_cap, liquidity
FROM token_dexpool_info
WHERE chain = 'BSC'
ORDER BY liquidity DESC
LIMIT 3;

[User] Could you also include the 24-hour price change percentage and 24-hour trading volume for these tokens?

[Assistant]
SELECT token_symbol, price, market_cap, liquidity, price_change_percentage_24h, volume_24h
FROM token_dexpool_info
WHERE chain = 'BSC'
ORDER BY liquidity DESC
LIMIT 3;

[User] Show only those tokens with positive 6-hour and 24-hour price change percentages.

[Assistant]
SELECT token_symbol, price, market_cap, liquidity, price_change_percentage_24h, volume_24h
FROM token_dexpool_info
WHERE chain = 'BSC'
  AND price_change_percentage_6h > 0
  AND price_change_percentage_24h > 0
ORDER BY liquidity DESC
LIMIT 3;

[User] Now include the makers_24h for each result.

[Assistant]
SELECT token_symbol, price, market_cap, liquidity, price_change_percentage_24h, volume_24h, makers_24h
FROM token_dexpool_info
WHERE chain = 'BSC'
  AND price_change_percentage_6h > 0
  AND price_change_percentage_24h > 0
ORDER BY liquidity DESC
LIMIT 3;

[User] List tokens on 'Arbitrum' with liquidity over 5000000.

[Assistant] SELECT * FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000;

[User] Filter those tokens to only include ones with a positive price change in the last 24 hours.

[Assistant] SELECT * FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000 AND price_change_percentage_24h > 0;

[User] Order the results by 24-hour trading volume descending and show the top 5 tokens.

[Assistant] SELECT * FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000 AND price_change_percentage_24h > 0 ORDER BY volume_24h DESC LIMIT 5;

[User] Also show their market cap and trend rank.

[Assistant] SELECT token_symbol, token_name, chain, price, liquidity, price_change_percentage_24h, volume_24h, market_cap, trend_rank FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000 AND price_change_percentage_24h > 0 ORDER BY volume_24h DESC LIMIT 5;

[User] Find tokens that have a positive price change percentage over the last 1 hour, 6 hours, and 24 hours. Display their symbol and chain.

[Assistant] SELECT token_symbol, chain FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0;

[User] Only show results for chains where the average trend rank is better than 5 (lower value indicates higher popularity).

[Assistant] SELECT token_symbol, chain FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5);

[User] Order the results by the 24-hour price change percentage in descending order.

[Assistant] SELECT token_symbol, chain, price_change_percentage_24h FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5) ORDER BY price_change_percentage_24h DESC;

[User] Limit the result to the top 20 tokens.

[Assistant] SELECT token_symbol, chain, price_change_percentage_24h FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5) ORDER BY price_change_percentage_24h DESC LIMIT 20;

[User] What is the total market cap for all tokens listed on the 'Polygon' chain?

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon';

[User] Only sum the market cap for tokens on 'Polygon' that have a 24-hour volume greater than 500000.

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Also show the number of unique tokens that meet these criteria.

[Assistant] SELECT COUNT(DISTINCT token_symbol), SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Can you show the total market cap and token count for *each* chain that meets these volume criteria, ordered by total market cap descending?

[Assistant] SELECT chain, COUNT(DISTINCT token_symbol) AS token_count, SUM(market_cap) AS total_market_cap FROM token_dexpool_info WHERE volume_24h > 500000 GROUP BY chain ORDER BY total_market_cap DESC;