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.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)

[User] Can you show me all pairs of trips that use the same vehicle but have different drivers? Please include both trip IDs, vehicle_id, and the driver_id for each trip.

[Assistant]
SELECT t1.trip_id AS trip_id_1, t2.trip_id AS trip_id_2, t1.vehicle_id, t1.driver_id AS driver_id_1, t2.driver_id AS driver_id_2
FROM transportation.trips t1
JOIN transportation.trips t2
  ON t1.vehicle_id = t2.vehicle_id
 AND t1.trip_id < t2.trip_id
 AND t1.driver_id <> t2.driver_id;

[User] Actually, I also want to see only those pairs where both trips have a status of 'Completed'.

[Assistant]
SELECT t1.trip_id AS trip_id_1, t2.trip_id AS trip_id_2, t1.vehicle_id, t1.driver_id AS driver_id_1, t2.driver_id AS driver_id_2
FROM transportation.trips t1
JOIN transportation.trips t2
  ON t1.vehicle_id = t2.vehicle_id
 AND t1.trip_id < t2.trip_id
 AND t1.driver_id <> t2.driver_id
WHERE t1.status = 'Completed' AND t2.status = 'Completed';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.nodes (
    node_id character varying(64) NOT NULL,  -- unique identifier for the node
    ip_address character varying(15) NOT NULL, -- IP address of the node
    port integer NOT NULL, -- port number of the node
    last_seen timestamp NOT NULL, -- last time the node was active
    PRIMARY KEY (node_id)
)
CREATE TABLE blockchain.wallets ( wallet_id.text, user_id.text, address_id.text, private_key.text )
CREATE TABLE blockchain.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE blockchain.smart_contracts ( contract_id character varying(64) NOT NULL, creator_address character varying(128) NOT NULL, code text NOT NULL, timestamp timestamp NOT NULL, PRIMARY KEY (contract_id) )

[User] Retrieve all users and their associated wallet identifiers.

[Assistant] SELECT T1.username ,  T2.wallet_id FROM blockchain.users AS T1 JOIN blockchain.wallets AS T2 ON T1.user_id  =  T2.user_id

[User] Only show users whose username starts with 'J'.

[Assistant] SELECT T1.username ,  T2.wallet_id FROM blockchain.users AS T1 JOIN blockchain.wallets AS T2 ON T1.user_id  =  T2.user_id WHERE T1.username LIKE 'J%'

[User] Further filter to only include wallets where the address_id contains 'abc'.

[Assistant] SELECT T1.username ,  T2.wallet_id FROM blockchain.users AS T1 JOIN blockchain.wallets AS T2 ON T1.user_id  =  T2.user_id WHERE T1.username LIKE 'J%' AND T2.address_id LIKE '%abc%'

[User] For the filtered users and wallets, count how many wallets each user has.

[Assistant] SELECT T1.username ,  COUNT(T2.wallet_id) FROM blockchain.users AS T1 JOIN blockchain.wallets AS T2 ON T1.user_id  =  T2.user_id WHERE T1.username LIKE 'J%' AND T2.address_id LIKE '%abc%' GROUP BY T1.username


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 text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )

[User] List all pairs of token transfers occurring within the same transaction where one transferred value is greater than the other, showing both transfer IDs, the transaction ID, and both values.

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


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

[User] List group conversation names and the count of messages sent in each conversation after '2024-06-01'.

[Assistant] SELECT T1.group_name, COUNT(T2.message_id) FROM social_media.conversations AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T1.is_group_chat = TRUE AND T2.sent_at > '2024-06-01' GROUP BY T1.conversation_id, T1.group_name;

[User] Only show conversations that have more than 5 messages sent after that date.

[Assistant] SELECT T1.group_name, COUNT(T2.message_id) FROM social_media.conversations AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T1.is_group_chat = TRUE AND T2.sent_at > '2024-06-01' GROUP BY T1.conversation_id, T1.group_name HAVING COUNT(T2.message_id) > 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 legal_services.law_firms (
    firm_id character varying(64) NOT NULL,  -- unique identifier for the law firm
    firm_name character varying(200) NOT NULL, -- official name of the law firm
    address text NOT NULL, -- primary address of the firm
    phone character varying(32), -- firm's main phone number
    website character varying(255), -- firm's website URL
    founded_date date, -- date the firm was established
    managing_partner_id character varying(64), -- FK to lawyers table (optional)
    PRIMARY KEY (firm_id)
)

[User] List the first name, last name, and the name of the law firm for all lawyers.

[Assistant] SELECT T1.first_name, T1.last_name, T2.firm_name FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id

[User] Now, filter this list to only include lawyers who work for firms founded after the year 2010.

[Assistant] SELECT T1.first_name, T1.last_name, T2.firm_name FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T2.founded_date > '2010-12-31'

[User] For these lawyers, also include the firm's phone number and sort the results alphabetically by firm name.

[Assistant] SELECT T1.first_name, T1.last_name, T2.firm_name, T2.phone FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T2.founded_date > '2010-12-31' ORDER BY T2.firm_name


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )

[User] List user IDs and the creation timestamp of likes made by users who have email notifications enabled.

[Assistant] SELECT T1.user_id, T1.created_at FROM social_media.likes AS T1 JOIN social_media.user_settings AS T2 ON T1.user_id = T2.user_id WHERE T2.email_notifications_enabled = true;

[User] Only show likes created in the year 2024.

[Assistant] SELECT T1.user_id, T1.created_at FROM social_media.likes AS T1 JOIN social_media.user_settings AS T2 ON T1.user_id = T2.user_id WHERE T2.email_notifications_enabled = true AND T1.created_at >= '2024-01-01' AND T1.created_at < '2025-01-01';

[User] Filter to only include users whose profile is not private.

[Assistant] SELECT T1.user_id, T1.created_at FROM social_media.likes AS T1 JOIN social_media.user_settings AS T2 ON T1.user_id = T2.user_id WHERE T2.email_notifications_enabled = true AND T1.created_at >= '2024-01-01' AND T1.created_at < '2025-01-01' AND T2.private_profile = false;


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.clients ( client_id.text, first_name.text, last_name.text, company_name.text, email.text, phone.text, address.text, date_registered.timestamp, status.text )
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.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.time_entries ( entry_id.text, case_id.text, lawyer_id.text, date_worked.date, hours_spent.numeric, billing_rate.numeric, description.text, is_billable.boolean, is_billed.boolean, invoice_id.text, created_at.timestamp )
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )

[User] List all documents along with the case number they are associated with, as well as the name and email of the lawyer who uploaded them.

[Assistant] SELECT d.document_name, d.document_type, d.case_id, l.first_name || ' ' || l.last_name AS lawyer_full_name, l.email FROM legal_services.documents d JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id;

[User] Only include documents uploaded after April 1st, 2024.

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

[User] Add the case name and make sure only documents with version greater than 1 are listed.

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

[User] Order the results by upload_timestamp ascending.

[Assistant] SELECT d.document_name, d.document_type, d.case_id, c.case_name, l.first_name || ' ' || l.last_name AS lawyer_full_name, l.email, d.upload_timestamp FROM legal_services.documents d JOIN legal_services.cases c ON d.case_id = c.case_id JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id WHERE d.upload_timestamp > '2024-04-01' AND d.version > 1 ORDER BY d.upload_timestamp 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 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] Show me each invoice and the invoice_number of the next invoice for the same client, along with how many days apart their issue_dates are.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date;

[User] Please restrict to pairs where the days_between is greater than 30.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date
 WHERE (b.issue_date - a.issue_date) > 30;

[User] And only include pairs where both invoices have status 'Overdue'.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date
 WHERE (b.issue_date - a.issue_date) > 30
   AND a.status = 'Overdue'
   AND b.status = 'Overdue';


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.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )

[User] Which lawyers have handled cases in the 'Federal Court' jurisdiction? Return each lawyer's first and last name, the case number, and the court jurisdiction.

[Assistant]
SELECT l.first_name, l.last_name, c.case_number, c.court_jurisdiction
FROM legal_services.lawyers l
JOIN legal_services.cases c ON l.lawyer_id = c.lead_lawyer_id
WHERE c.court_jurisdiction = 'Federal Court';


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.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )

[User] How many appointments were created in the month of July 2024?

[Assistant]
SELECT COUNT(*) AS appointment_count
FROM legal_services.appointments
WHERE DATE_TRUNC('month', created_at) = DATE '2024-07-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.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )

[User] Count the total number of invoices issued in each calendar year and month. Show the year, month, and the count, ordered chronologically.

[Assistant] SELECT EXTRACT(YEAR FROM issue_date) AS issue_year, EXTRACT(MONTH FROM issue_date) AS issue_month, COUNT(*) AS invoice_count FROM legal_services.invoices GROUP BY issue_year, issue_month ORDER BY issue_year, issue_month;


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.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )

[User] I need a list of each case_number and case_name with the total hours spent on each case based on time_entries, but only include cases where the total hours is greater than 10.

[Assistant]
SELECT c.case_number, c.case_name, SUM(te.hours_spent) AS total_hours
FROM legal_services.cases c
JOIN legal_services.time_entries te ON c.case_id = te.case_id
GROUP BY c.case_number, c.case_name
HAVING SUM(te.hours_spent) > 10;

[User] Actually, tally only hours where is_billable is true.

[Assistant]
SELECT c.case_number, c.case_name, SUM(te.hours_spent) AS total_hours
FROM legal_services.cases c
JOIN legal_services.time_entries te ON c.case_id = te.case_id
WHERE te.is_billable = TRUE
GROUP BY c.case_number, c.case_name
HAVING SUM(te.hours_spent) > 10;

[User] Also include the client's first_name and last_name for each case.

[Assistant]
SELECT c.case_number, c.case_name, cl.first_name, cl.last_name, SUM(te.hours_spent) AS total_hours
FROM legal_services.cases c
JOIN legal_services.clients cl ON c.client_id = cl.client_id
JOIN legal_services.time_entries te ON c.case_id = te.case_id
WHERE te.is_billable = TRUE
GROUP BY c.case_number, c.case_name, cl.first_name, cl.last_name
HAVING SUM(te.hours_spent) > 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 legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )

[User] List all law firms that do not have a website registered, including their firm name and phone.

[Assistant]
SELECT firm_name, phone
FROM legal_services.law_firms
WHERE website IS NULL OR website = '';


[User] Show me all clients along with the total number of invoices they have and the sum of total_amount for those invoices.

[Assistant]
SELECT cl.client_id, cl.first_name, cl.last_name, COUNT(inv.invoice_id) AS invoice_count, SUM(inv.total_amount) AS sum_total_amount
FROM legal_services.clients cl
LEFT JOIN legal_services.invoices inv ON cl.client_id = inv.client_id
GROUP BY cl.client_id, cl.first_name, cl.last_name;

[User] Could you limit this to invoices issued after '2023-01-01'?

[Assistant]
SELECT cl.client_id, cl.first_name, cl.last_name, COUNT(inv.invoice_id) AS invoice_count, SUM(inv.total_amount) AS sum_total_amount
FROM legal_services.clients cl
LEFT JOIN legal_services.invoices inv
  ON cl.client_id = inv.client_id AND inv.issue_date > '2023-01-01'
GROUP BY cl.client_id, cl.first_name, cl.last_name;

[User] Also exclude clients who haven't paid any invoice.

[Assistant]
SELECT cl.client_id, cl.first_name, cl.last_name, COUNT(inv.invoice_id) AS invoice_count, SUM(inv.total_amount) AS sum_total_amount
FROM legal_services.clients cl
LEFT JOIN legal_services.invoices inv
  ON cl.client_id = inv.client_id AND inv.issue_date > '2023-01-01'
GROUP BY cl.client_id, cl.first_name, cl.last_name
HAVING SUM(inv.amount_paid) > 0;

[User] Sort the results by sum_total_amount descending.

[Assistant]
SELECT cl.client_id, cl.first_name, cl.last_name, COUNT(inv.invoice_id) AS invoice_count, SUM(inv.total_amount) AS sum_total_amount
FROM legal_services.clients cl
LEFT JOIN legal_services.invoices inv
  ON cl.client_id = inv.client_id AND inv.issue_date > '2023-01-01'
GROUP BY cl.client_id, cl.first_name, cl.last_name
HAVING SUM(inv.amount_paid) > 0
ORDER BY sum_total_amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] List the latest version of each document (identified by case_id and document_name), showing the version number and its upload_timestamp.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version   AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m ON d.case_id = m.case_id
    AND d.document_name = m.document_name
    AND d.version = m.max_version;

[User] Actually, I also want to see the upload_timestamp of the previous version for each document.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version         AS latest_version,
       d_latest.upload_timestamp  AS latest_timestamp,
       d_prev.upload_timestamp    AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] Also, only include documents whose first version (version = 1) was uploaded in 2024.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version          AS latest_version,
       d_latest.upload_timestamp   AS latest_timestamp,
       d_prev.upload_timestamp     AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_first
  ON d_first.case_id = m.case_id
 AND d_first.document_name = m.document_name
 AND d_first.version = 1
 AND d_first.upload_timestamp >= '2024-01-01'
 AND d_first.upload_timestamp < '2025-01-01'
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;


[User] For each client, list their first and last invoice numbers along with the corresponding issue_dates.

[Assistant]
SELECT first_inv.client_id,
       first_inv.invoice_number   AS first_invoice,
       first_inv.issue_date       AS first_date,
       last_inv.invoice_number    AS last_invoice,
       last_inv.issue_date        AS last_date
FROM legal_services.invoices first_inv
JOIN legal_services.invoices last_inv
  ON first_inv.client_id = last_inv.client_id
 AND first_inv.issue_date = (
       SELECT MIN(issue_date)
       FROM legal_services.invoices
       WHERE client_id = first_inv.client_id
     )
 AND last_inv.issue_date = (
       SELECT MAX(issue_date)
       FROM legal_services.invoices
       WHERE client_id = last_inv.client_id
     );

[User] Sort the output by client_id.

[Assistant]
SELECT first_inv.client_id,
       first_inv.invoice_number   AS first_invoice,
       first_inv.issue_date       AS first_date,
       last_inv.invoice_number    AS last_invoice,
       last_inv.issue_date        AS last_date
FROM legal_services.invoices first_inv
JOIN legal_services.invoices last_inv
  ON first_inv.client_id = last_inv.client_id
 AND first_inv.issue_date = (
       SELECT MIN(issue_date)
       FROM legal_services.invoices
       WHERE client_id = first_inv.client_id
     )
 AND last_inv.issue_date = (
       SELECT MAX(issue_date)
       FROM legal_services.invoices
       WHERE client_id = last_inv.client_id
     )
ORDER BY first_inv.client_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 legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )

[User] Show me the invoice number and total amount for invoices, along with the case number and case name for the related case.

[Assistant]
SELECT i.invoice_number, i.total_amount, c.case_number, c.case_name
FROM legal_services.invoices i
JOIN legal_services.cases c ON i.case_id = c.case_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 erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE nft_holders (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter)
    token_id varchar NOT NULL, -- NFT token id
    contract_type varchar NOT NULL, -- NFT contract type
    amount varchar NOT NULL, -- Number of held NFTs
    pk varchar NOT NULL  -- The last string partition of the contract.
)
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 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 varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    name varchar NOT NULL, -- name fields for the functionType  in contract
    symbol varchar NOT NULL, -- symbol fields for the functionType  in contract
    deploy_block_number bigint NOT NULL, -- deploy_block_number fields for the functionType  in contract
    deploy_block_time bigint NOT NULL, -- deploy_block_time fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    description varchar NOT NULL, -- description fields for the functionType  in contract
    slug varchar NOT NULL, -- slug fields for the functionType  in contract
    media_info varchar NOT NULL, -- media_info fields for the functionType  in contract
    image_url varchar NOT NULL, -- image_url fields for the functionType  in contract
    banner_image_url varchar NOT NULL, -- banner_image_url fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    banner varchar NOT NULL, -- banner fields for the functionType  in contract
    token_count bigint NOT NULL, -- token_count fields for the functionType  in contract
    floor_price varchar NOT NULL, -- floor_price fields for the functionType  in contract
    floor_price_symbol varchar NOT NULL, -- floor_price_symbol fields for the functionType  in contract
    floor_price_contract varchar NOT NULL, -- floor_price_contract fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(deploy_block_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
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 varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )

[User] Show me the total amount and number of unique holder wallets for each ERC20 token held on Ethereum. Please display contract address, sum of amounts, and holder count.

[Assistant]
SELECT contract_address, SUM(amount::numeric) AS total_amount, COUNT(DISTINCT wallet_address) AS holder_count
FROM erc20_balances
GROUP BY contract_address;

[User] Add the token symbol and decimals for each contract by joining with token_prices_latest.

[Assistant]
SELECT eb.contract_address, SUM(eb.amount::numeric) AS total_amount, COUNT(DISTINCT eb.wallet_address) AS holder_count, t.symbol, t.decimals
FROM erc20_balances eb
LEFT JOIN token_prices_latest t ON eb.contract_address = t.address AND t.blockchain = 'Ethereum'
GROUP BY eb.contract_address, t.symbol, t.decimals;

[User] Filter to only include tokens with more than 300 holders and order by total amount descending.

[Assistant]
SELECT eb.contract_address, SUM(eb.amount::numeric) AS total_amount, COUNT(DISTINCT eb.wallet_address) AS holder_count, t.symbol, t.decimals
FROM erc20_balances eb
LEFT JOIN token_prices_latest t ON eb.contract_address = t.address AND t.blockchain = 'Ethereum'
GROUP BY eb.contract_address, t.symbol, t.decimals
HAVING COUNT(DISTINCT eb.wallet_address) > 300
ORDER BY total_amount DESC;

[User] Limit the result to the top 10 tokens only.

[Assistant]
SELECT eb.contract_address, SUM(eb.amount::numeric) AS total_amount, COUNT(DISTINCT eb.wallet_address) AS holder_count, t.symbol, t.decimals
FROM erc20_balances eb
LEFT JOIN token_prices_latest t ON eb.contract_address = t.address AND t.blockchain = 'Ethereum'
GROUP BY eb.contract_address, t.symbol, t.decimals
HAVING COUNT(DISTINCT eb.wallet_address) > 300
ORDER BY total_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 erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
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 sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
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_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar NOT NULL, -- Token tick
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
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 varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )

[User] For each Bitcoin token tick, show me the creator address from the token_info_bitcoin table and the number of unique wallets currently holding that token.

[Assistant] SELECT ti.tick, ti.creator, COUNT(DISTINCT tb.wallet_address) AS unique_wallets FROM token_info_bitcoin ti JOIN token_balances_bitcoin tb ON ti.tick = tb.tick GROUP BY ti.tick, ti.creator;

[User] Now, only include ticks where there are more than 5 unique wallets, and order the result by the number of unique wallets descending.

[Assistant] SELECT ti.tick, ti.creator, COUNT(DISTINCT tb.wallet_address) AS unique_wallets FROM token_info_bitcoin ti JOIN token_balances_bitcoin tb ON ti.tick = tb.tick GROUP BY ti.tick, ti.creator HAVING COUNT(DISTINCT tb.wallet_address) > 5 ORDER BY unique_wallets DESC;


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

[User] For each ERC1155 NFT on Ethereum, can you show the contract address, token ID, and the total number of unique wallet holders?

[Assistant]
SELECT nh.contract_address, nh.token_id, COUNT(DISTINCT nh.wallet_address) AS unique_holders
FROM nft_holders nh
WHERE nh.contract_type = 'ERC1155'
GROUP BY nh.contract_address, nh.token_id;

[User] Can you also include the total amount held for each NFT across all wallets?

[Assistant]
SELECT nh.contract_address, nh.token_id, COUNT(DISTINCT nh.wallet_address) AS unique_holders, SUM(CAST(nh.amount AS BIGINT)) AS total_amount
FROM nft_holders nh
WHERE nh.contract_type = 'ERC1155'
GROUP BY nh.contract_address, nh.token_id;

[User] I want the result restricted to NFTs where the total amount held is more than 1000.

[Assistant]
SELECT nh.contract_address, nh.token_id, COUNT(DISTINCT nh.wallet_address) AS unique_holders, SUM(CAST(nh.amount AS BIGINT)) AS total_amount
FROM nft_holders nh
WHERE nh.contract_type = 'ERC1155'
GROUP BY nh.contract_address, nh.token_id
HAVING SUM(CAST(nh.amount AS BIGINT)) > 1000;

[User] Please also add the name of each NFT from the nft_metadata table, if available.

[Assistant]
SELECT nh.contract_address, nh.token_id, nm.name AS nft_name, COUNT(DISTINCT nh.wallet_address) AS unique_holders, SUM(CAST(nh.amount AS BIGINT)) AS total_amount
FROM nft_holders nh
LEFT JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id AND nm.blockchain = 'Ethereum'
WHERE nh.contract_type = 'ERC1155'
GROUP BY nh.contract_address, nh.token_id, nm.name
HAVING SUM(CAST(nh.amount AS BIGINT)) > 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 erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
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 varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
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 token_prices (
    uuid varchar(36) NOT NULL, -- uuid fields for the functionType  in contract
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )

[User] Show me the wallet addresses that hold more than 1000 of any ERC20 token, along with the token symbol and amount, from the erc20_balances table.

[Assistant] SELECT e.wallet_address, t.symbol, e.amount FROM erc20_balances e JOIN token_prices_latest t ON e.contract_address = t.address WHERE CAST(e.amount AS decimal) > 1000;

[User] Can you also include the current price of each token from the token_prices_latest table and sort the results by amount in descending order?

[Assistant] SELECT e.wallet_address, t.symbol, e.amount, t.price FROM erc20_balances e JOIN token_prices_latest t ON e.contract_address = t.address WHERE CAST(e.amount AS decimal) > 1000 ORDER BY CAST(e.amount AS decimal) 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 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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
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 NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter)
    token_id varchar NOT NULL, -- NFT token id
    contract_type varchar NOT NULL, -- NFT contract type
    amount varchar NOT NULL, -- The quantity held in the wallet
    pk integer NOT NULL  -- Partition key for the table(floor(block_number / 7200))
)
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
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 varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar NOT NULL, -- Token tick
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
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 varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )

[User] List the ERC20 tokens (from token_metas) with exactly 6 decimals. Show their symbol, contract_address, and name.

[Assistant] SELECT symbol, contract_address, name FROM token_metas WHERE is_erc20 = 1 AND decimals = 6;

[User] Can you also include the total current supply for each token?

[Assistant] SELECT symbol, contract_address, name, total_supply FROM token_metas WHERE is_erc20 = 1 AND decimals = 6;

[User] Now, join with token_prices_latest to also include the latest price for each token.

[Assistant]
SELECT tm.symbol, tm.contract_address, tm.name, tm.total_supply, tpl.price AS latest_price
FROM token_metas tm
JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tpl.blockchain = 'Ethereum'
WHERE tm.is_erc20 = 1 AND tm.decimals = 6;

[User] Only include tokens where the latest price is between 0.5 and 2.0 USD, and limit the result to the top 5 tokens by price descending.

[Assistant]
SELECT tm.symbol, tm.contract_address, tm.name, tm.total_supply, tpl.price AS latest_price
FROM token_metas tm
JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tpl.blockchain = 'Ethereum'
WHERE tm.is_erc20 = 1 AND tm.decimals = 6 AND tpl.price BETWEEN 0.5 AND 2.0
ORDER BY tpl.price 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.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)

[User] Find the date (calendar day) with the highest total number of game sessions. Show the date and the total session count.

[Assistant]
SELECT CAST(start_time AS DATE) AS session_date, COUNT(*) AS total_sessions
FROM gaming_technology.game_sessions
GROUP BY session_date
ORDER BY total_sessions DESC
LIMIT 1;

[User] Also include the day with the second highest session count.

[Assistant]
SELECT session_date, total_sessions FROM (
  SELECT CAST(start_time AS DATE) AS session_date, COUNT(*) AS total_sessions,
         ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) AS rn
  FROM gaming_technology.game_sessions
  GROUP BY session_date
) ranked
WHERE rn <= 2
ORDER BY total_sessions DESC;

[User] Can you also add the total score across all sessions for each of those days?

[Assistant]
SELECT session_date, total_sessions, total_score FROM (
  SELECT CAST(start_time AS DATE) AS session_date,
         COUNT(*) AS total_sessions,
         SUM(score) AS total_score,
         ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) AS rn
  FROM gaming_technology.game_sessions
  GROUP BY session_date
) ranked
WHERE rn <= 2
ORDER BY total_sessions DESC;

[User] I got an error that session_date is not found, can you fix this SQL?

[Assistant]
SELECT sub.session_date, sub.total_sessions, sub.total_score FROM (
  SELECT CAST(start_time AS DATE) AS session_date,
         COUNT(*) AS total_sessions,
         SUM(score) AS total_score,
         ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) AS rn
  FROM gaming_technology.game_sessions
  GROUP BY CAST(start_time AS DATE)
) AS sub
WHERE sub.rn <= 2
ORDER BY sub.total_sessions DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid 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.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.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 NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
CREATE TABLE gaming_technology.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 NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] Give me each server's name, the region, and the maximum number of players that have been connected at once.

[Assistant]
SELECT s.server_id, s.server_name, s.region, MAX(s.current_players) AS max_players_seen
FROM gaming_technology.servers s
GROUP BY s.server_id, s.server_name, s.region;

[User] Could you also include the associated game title for each server?

[Assistant]
SELECT s.server_id, s.server_name, s.region, g.title AS game_title, MAX(s.current_players) AS max_players_seen
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
GROUP BY s.server_id, s.server_name, s.region, g.title;

[User] Now, can you show only servers where the max number of players ever connected exceeded 20?

[Assistant]
SELECT s.server_id, s.server_name, s.region, g.title AS game_title, MAX(s.current_players) AS max_players_seen
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
GROUP BY s.server_id, s.server_name, s.region, g.title
HAVING MAX(s.current_players) > 20;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
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, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
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, game_id.uuid, item_name.text, item_type.text, description.text, rarity.text, cost_currency.text, cost_amount.numeric, attributes.jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )

[User] List the usernames and registration dates for all players from 'Canada'.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE country_code = 'Canada';

[User] Now, only show players from Canada who registered after January 1st, 2023.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE country_code = 'Canada' AND registration_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 gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )

[User] Retrieve the title and release_date of all games on the 'PC' platform.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC';

[User] Now exclude any games released before 2018.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC'
  AND release_date >= '2018-01-01';

[User] Also sort the results by release_date in ascending order.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC'
  AND release_date >= '2018-01-01'
ORDER BY release_date 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 gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )

[User] I need to list all pairs of in-game items in the same game where one item is Epic and the other is Legendary, showing game_id, epic_item, and legendary_item.

[Assistant]
SELECT a.game_id,
       a.item_name AS epic_item,
       b.item_name AS legendary_item
FROM gaming_technology.in_game_items a
JOIN gaming_technology.in_game_items b
  ON a.game_id = b.game_id
WHERE a.rarity = 'Epic'
  AND b.rarity = 'Legendary';

[User] Actually, only include pairs where both items have cost_amount greater than 100.

[Assistant]
SELECT a.game_id,
       a.item_name AS epic_item,
       b.item_name AS legendary_item
FROM gaming_technology.in_game_items a
JOIN gaming_technology.in_game_items b
  ON a.game_id = b.game_id
WHERE a.rarity = 'Epic'
  AND b.rarity = 'Legendary'
  AND a.cost_amount > 100
  AND b.cost_amount > 100;

[User] Also, ensure each pair appears only once and avoid reversed duplicates.

[Assistant]
SELECT DISTINCT
       LEAST(a.item_id::text, b.item_id::text) AS item1_id,
       GREATEST(a.item_id::text, b.item_id::text) AS item2_id,
       a.game_id,
       a.item_name AS epic_item,
       b.item_name AS legendary_item
FROM gaming_technology.in_game_items a
JOIN gaming_technology.in_game_items b
  ON a.game_id = b.game_id
WHERE a.rarity = 'Epic'
  AND b.rarity = 'Legendary'
  AND a.cost_amount > 100
  AND b.cost_amount > 100;

[User] Finally, order the results by game_id ascending.

[Assistant]
SELECT DISTINCT
       LEAST(a.item_id::text, b.item_id::text) AS item1_id,
       GREATEST(a.item_id::text, b.item_id::text) AS item2_id,
       a.game_id,
       a.item_name AS epic_item,
       b.item_name AS legendary_item
FROM gaming_technology.in_game_items a
JOIN gaming_technology.in_game_items b
  ON a.game_id = b.game_id
WHERE a.rarity = 'Epic'
  AND b.rarity = 'Legendary'
  AND a.cost_amount > 100
  AND b.cost_amount > 100
ORDER BY a.game_id 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 gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )

[User] Could you list the title of each game and the total quantity of items acquired by players for that specific game?

[Assistant] SELECT g.title, SUM(pi.quantity) AS total_acquired_quantity FROM gaming_technology.games g JOIN gaming_technology.player_inventory pi ON g.game_id = pi.item_id GROUP BY g.title;

[User] Now, I only want to include games where the total acquired quantity is more than 100.

[Assistant] SELECT g.title, SUM(pi.quantity) AS total_acquired_quantity FROM gaming_technology.games g JOIN gaming_technology.player_inventory pi ON g.game_id = pi.item_id GROUP BY g.title HAVING SUM(pi.quantity) > 100;

[User] Please filter the results further to include only games from the 'Action' genre.

[Assistant] SELECT g.title, SUM(pi.quantity) AS total_acquired_quantity FROM gaming_technology.games g JOIN gaming_technology.player_inventory pi ON g.game_id = pi.item_id WHERE g.genre = 'Action' GROUP BY g.title HAVING SUM(pi.quantity) > 100;

[User] Finally, order the results by the total acquired quantity in descending order.

[Assistant] SELECT g.title, SUM(pi.quantity) AS total_acquired_quantity FROM gaming_technology.games g JOIN gaming_technology.player_inventory pi ON g.game_id = pi.item_id WHERE g.genre = 'Action' GROUP BY g.title HAVING SUM(pi.quantity) > 100 ORDER BY total_acquired_quantity DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, game_id uuid NOT NULL, server_id uuid, start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb, PRIMARY KEY (session_id) )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, name character varying(150) NOT NULL, description text NOT NULL, icon_url character varying(255), points integer DEFAULT 0, hidden boolean DEFAULT false, PRIMARY KEY (achievement_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] List the name and points of all hidden achievements.

[Assistant]
SELECT name, points
FROM gaming_technology.achievements
WHERE hidden = true;

[User] Only include those with points greater than 50.

[Assistant]
SELECT name, points
FROM gaming_technology.achievements
WHERE hidden = true
  AND points > 50;

[User] Now order the results by points in ascending order.

[Assistant]
SELECT name, points
FROM gaming_technology.achievements
WHERE hidden = true
  AND points > 50
ORDER BY points ASC;

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

[Assistant]
SELECT name, points
FROM gaming_technology.achievements
WHERE hidden = true
  AND points > 50
ORDER BY points ASC
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 gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)

[User] Can you show the total quantity of all in-game items held by each player?

[Assistant]
SELECT player_id, SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
GROUP BY player_id;

[User] I'd like to see only players whose total quantity is over 20.

[Assistant]
SELECT player_id, SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
GROUP BY player_id
HAVING SUM(quantity) > 20;

[User] Also, can you include the number of different unique items each player owns?

[Assistant]
SELECT player_id, COUNT(DISTINCT item_id) AS unique_items, SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
GROUP BY player_id
HAVING SUM(quantity) > 20;

[User] Order the final result by unique_items descending, then by total_quantity descending.

[Assistant]
SELECT player_id, COUNT(DISTINCT item_id) AS unique_items, SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
GROUP BY player_id
HAVING SUM(quantity) > 20
ORDER BY unique_items DESC, total_quantity DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )

[User] Show me all pairs of servers that are located in the same region, listing both server names and their region.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id;

[User] Filter this list to only include pairs where both servers are currently 'online'.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] For these pairs, also show the current_players for both servers.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.current_players AS server1_current_players, s2.current_players AS server2_current_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] Order the results by region ascending, then by the current players of the first server in the pair ascending.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.current_players AS server1_current_players, s2.current_players AS server2_current_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online' ORDER BY s1.region ASC, s1.current_players 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 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.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.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 PRIMARY KEY, game_id uuid, server_name text, region text, ip_address text, port int, current_players int, max_players int, status text, last_heartbeat timestamptz )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )
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 )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )

[User] For each game, find the hidden achievement with the highest points and show the game title, achievement name, and points.

[Assistant]
SELECT g.title AS game_title,
       a.name  AS achievement_name,
       a.points
FROM gaming_technology.achievements a
JOIN gaming_technology.games g
  ON a.game_id = g.game_id
WHERE a.hidden = true
  AND a.points = (
    SELECT MAX(points)
    FROM gaming_technology.achievements
    WHERE game_id = a.game_id
      AND hidden = true
  );

[User] Actually, exclude games that do not have any hidden achievements.

[Assistant]
SELECT g.title AS game_title,
       a.name  AS achievement_name,
       a.points
FROM gaming_technology.games g
JOIN gaming_technology.achievements a
  ON g.game_id = a.game_id
WHERE a.hidden = true
  AND a.points = (
    SELECT MAX(points)
    FROM gaming_technology.achievements
    WHERE game_id = a.game_id
      AND hidden = true
  );

[User] Also, order the results by a.points descending.

[Assistant]
SELECT g.title AS game_title,
       a.name  AS achievement_name,
       a.points
FROM gaming_technology.games g
JOIN gaming_technology.achievements a
  ON g.game_id = a.game_id
WHERE a.hidden = true
  AND a.points = (
    SELECT MAX(points)
    FROM gaming_technology.achievements
    WHERE game_id = a.game_id
      AND hidden = true
  )
ORDER BY a.points DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )

[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 gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )

[User] For each player, show the total number of achievements they have unlocked and their total game session count.

[Assistant]
SELECT p.player_id, COUNT(pa.achievement_id) AS total_achievements_unlocked, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.player_achievements pa
FULL JOIN gaming_technology.game_sessions gs ON pa.player_id = gs.player_id
RIGHT JOIN (
    SELECT DISTINCT player_id FROM gaming_technology.player_achievements
    UNION
    SELECT DISTINCT player_id FROM gaming_technology.game_sessions
) p ON pa.player_id = p.player_id OR gs.player_id = p.player_id
GROUP BY p.player_id;

[User] Can you modify it to only include players who have unlocked at least 3 achievements and played at least 2 sessions?

[Assistant]
SELECT p.player_id, COUNT(pa.achievement_id) AS total_achievements_unlocked, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.player_achievements pa
FULL JOIN gaming_technology.game_sessions gs ON pa.player_id = gs.player_id
RIGHT JOIN (
    SELECT DISTINCT player_id FROM gaming_technology.player_achievements
    UNION
    SELECT DISTINCT player_id FROM gaming_technology.game_sessions
) p ON pa.player_id = p.player_id OR gs.player_id = p.player_id
GROUP BY p.player_id
HAVING COUNT(pa.achievement_id) >= 3 AND COUNT(gs.session_id) >= 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 gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)

[User] List pairs of games that share the same publisher but belong to different genres, showing both titles and genres.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.genre AS genre1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.genre AS genre2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND g1.genre <> g2.genre;

[User] Exclude any pairs where the publisher_id is NULL.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.genre AS genre1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.genre AS genre2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND g1.genre <> g2.genre
WHERE g1.publisher_id IS NOT NULL;

[User] Further restrict to game pairs released within one year of each other.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.release_date AS release1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.release_date AS release2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND ABS(EXTRACT(YEAR FROM AGE(g1.release_date, g2.release_date))) <= 1
WHERE g1.publisher_id IS NOT NULL;

[User] Order the final result by publisher_id and then by the earliest release_date among each pair.

[Assistant]
SELECT g1.publisher_id,
       g1.game_id AS game1_id,
       g1.title AS title1,
       g1.release_date AS release1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.release_date AS release2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND ABS(EXTRACT(YEAR FROM AGE(g1.release_date, g2.release_date))) <= 1
WHERE g1.publisher_id IS NOT NULL
ORDER BY g1.publisher_id,
         LEAST(g1.release_date, g2.release_date) ASC;