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 text PRIMARY KEY, ip_address text, port int, last_seen timestamp )

[User] Show me all nodes that were last seen in the past 30 days, along with their IP addresses and ports.

[Assistant] SELECT node_id, ip_address, port, last_seen FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '30 days';

[User] Now, filter these results to only show nodes with port numbers between 8000 and 9000.

[Assistant] SELECT node_id, ip_address, port, last_seen FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '30 days' AND port BETWEEN 8000 AND 9000;

[User] Show me pairs of node_id and node_id for nodes that share the same ip_address but have different port numbers.

[Assistant] SELECT n1.node_id AS node_id1, n2.node_id AS node_id2, n1.ip_address, n1.port AS port1, n2.port AS port2 FROM blockchain.nodes n1 JOIN blockchain.nodes n2 ON n1.ip_address = n2.ip_address WHERE n1.node_id < n2.node_id AND n1.port <> n2.port;

[User] List all ports along with the count of unique IP addresses that have been seen on each port.

[Assistant] SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count FROM blockchain.nodes GROUP BY port;

[User] Filter to only include ports where the unique IP count is greater than 5.

[Assistant] SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count FROM blockchain.nodes GROUP BY port HAVING COUNT(DISTINCT ip_address) > 5;

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

[Assistant] SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count FROM blockchain.nodes GROUP BY port HAVING COUNT(DISTINCT ip_address) > 5 ORDER BY unique_ip_count DESC;

[User] Retrieve all pairs of nodes that share the same port and were last seen on the same day. Include node_id, ip_address, and last_seen of both nodes.

[Assistant] SELECT n1.node_id AS node_id1, n1.ip_address AS ip1, n1.last_seen AS last_seen1, n2.node_id AS node_id2, n2.ip_address AS ip2, n2.last_seen AS last_seen2, n1.port FROM blockchain.nodes n1 JOIN blockchain.nodes n2 ON n1.port = n2.port AND date_trunc('day', n1.last_seen) = date_trunc('day', n2.last_seen) WHERE n1.node_id < n2.node_id;

[User] Actually, exclude any pairs where the two nodes have the same IP address.

[Assistant] SELECT n1.node_id AS node_id1, n1.ip_address AS ip1, n1.last_seen AS last_seen1, n2.node_id AS node_id2, n2.ip_address AS ip2, n2.last_seen AS last_seen2, n1.port FROM blockchain.nodes n1 JOIN blockchain.nodes n2 ON n1.port = n2.port AND date_trunc('day', n1.last_seen) = date_trunc('day', n2.last_seen) WHERE n1.node_id < n2.node_id AND n1.ip_address <> n2.ip_address;

[User] Also, sort the results by port ascending and then by last_seen of the first node.

[Assistant] SELECT n1.node_id AS node_id1, n1.ip_address AS ip1, n1.last_seen AS last_seen1, n2.node_id AS node_id2, n2.ip_address AS ip2, n2.last_seen AS last_seen2, n1.port FROM blockchain.nodes n1 JOIN blockchain.nodes n2 ON n1.port = n2.port AND date_trunc('day', n1.last_seen) = date_trunc('day', n2.last_seen) WHERE n1.node_id < n2.node_id AND n1.ip_address <> n2.ip_address ORDER BY n1.port ASC, n1.last_seen;

[User] Lastly, limit the output to the first 20 pairs.

[Assistant] SELECT n1.node_id AS node_id1, n1.ip_address AS ip1, n1.last_seen AS last_seen1, n2.node_id AS node_id2, n2.ip_address AS ip2, n2.last_seen AS last_seen2, n1.port FROM blockchain.nodes n1 JOIN blockchain.nodes n2 ON n1.port = n2.port AND date_trunc('day', n1.last_seen) = date_trunc('day', n2.last_seen) WHERE n1.node_id < n2.node_id AND n1.ip_address <> n2.ip_address ORDER BY n1.port ASC, n1.last_seen LIMIT 20;

[User] Find all pairs of nodes that share the same ip_address but have different port numbers, include both node IDs, their ports, and the ip_address.

[Assistant]
SELECT n1.node_id AS node1_id, n2.node_id AS node2_id, n1.ip_address, n1.port AS port1, n2.port AS port2
FROM blockchain.nodes n1
JOIN blockchain.nodes n2 ON n1.ip_address = n2.ip_address AND n1.port <> n2.port;

[User] Actually, I only want pairs where the first node’s last_seen is earlier than the second node’s last_seen.

[Assistant]
SELECT n1.node_id AS node1_id, n2.node_id AS node2_id, n1.ip_address, n1.port AS port1, n2.port AS port2, n1.last_seen AS last_seen1, n2.last_seen AS last_seen2
FROM blockchain.nodes n1
JOIN blockchain.nodes n2
  ON n1.ip_address = n2.ip_address
  AND n1.port <> n2.port
WHERE n1.last_seen < n2.last_seen;

[User] Can you also include the time difference in hours between their last_seen timestamps?

[Assistant]
SELECT n1.node_id AS node1_id, n2.node_id AS node2_id, n1.ip_address, n1.port AS port1, n2.port AS port2,
       n1.last_seen AS last_seen1, n2.last_seen AS last_seen2,
       EXTRACT(EPOCH FROM (n2.last_seen - n1.last_seen)) / 3600 AS hours_diff
FROM blockchain.nodes n1
JOIN blockchain.nodes n2
  ON n1.ip_address = n2.ip_address
  AND n1.port <> n2.port
WHERE n1.last_seen < n2.last_seen;

[User] Now limit to pairs where the time difference is less than 2 hours, order by the smallest difference first, and return only the top 10.

[Assistant]
SELECT n1.node_id AS node1_id, n2.node_id AS node2_id, n1.ip_address, n1.port AS port1, n2.port AS port2,
       EXTRACT(EPOCH FROM (n2.last_seen - n1.last_seen)) / 3600 AS hours_diff
FROM blockchain.nodes n1
JOIN blockchain.nodes n2
  ON n1.ip_address = n2.ip_address
  AND n1.port <> n2.port
WHERE n1.last_seen < n2.last_seen
  AND (EXTRACT(EPOCH FROM (n2.last_seen - n1.last_seen)) / 3600) < 2
ORDER BY hours_diff ASC
LIMIT 10;

[User] Retrieve all pairs of nodes where one node was last seen before '2023-06-01' and the other after '2023-06-01', and they share the same IP address.

[Assistant]
SELECT a.node_id AS node_before,
       b.node_id AS node_after,
       a.ip_address
FROM blockchain.nodes a
JOIN blockchain.nodes b
  ON a.ip_address = b.ip_address
WHERE a.last_seen < '2023-06-01'
  AND b.last_seen > '2023-06-01';

[User] List each port along with the count of distinct IP addresses observed on that port.

[Assistant] SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count FROM blockchain.nodes GROUP BY port;

[User] Only include ports that have more than 3 unique IP addresses.

[Assistant] SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count FROM blockchain.nodes GROUP BY port HAVING COUNT(DISTINCT ip_address) > 3;

[User] Also include the latest last_seen timestamp for each of these ports.

[Assistant] SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count, MAX(last_seen) AS last_seen_latest FROM blockchain.nodes GROUP BY port HAVING COUNT(DISTINCT ip_address) > 3;

[User] Find all pairs of node IDs that share the same IP address but operate on different ports.

[Assistant] SELECT a.node_id AS node1, b.node_id AS node2, a.ip_address, a.port AS port1, b.port AS port2 FROM blockchain.nodes a JOIN blockchain.nodes b ON a.ip_address = b.ip_address AND a.node_id < b.node_id AND a.port <> b.port;

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

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

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

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

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

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

[User] Show me each transaction ID along with the sender's public key, the receiver's balance, and the transaction amount.

[Assistant]
SELECT t.transaction_id, a_sender.public_key AS sender_public_key, a_receiver.balance AS receiver_balance, t.amount
FROM blockchain.transactions t
JOIN blockchain.addresses a_sender ON t.sender_address = a_sender.address_id
JOIN blockchain.addresses a_receiver ON t.receiver_address = a_receiver.address_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 government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )

[User] For each access level, count the number of employees. Return access_level and the corresponding employee_count.

[Assistant] SELECT access_level, COUNT(*) AS employee_count FROM government_services.employees GROUP BY access_level;

[User] List the full names and hire dates of all employees who report directly to a manager with the job title 'Director'.

[Assistant]
SELECT e.first_name, e.last_name, e.hire_date
FROM government_services.employees e
JOIN government_services.employees m ON e.manager_employee_id = m.employee_id
WHERE m.job_title = 'Director';

[User] Find all currently employed staff whose managers are no longer employed. Show the employee's full name, hire date, the manager's full name, and the manager's termination_date.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, e.hire_date, m.first_name || ' ' || m.last_name AS manager_name, m.termination_date FROM government_services.employees e JOIN government_services.employees m ON e.manager_employee_id = m.employee_id WHERE e.termination_date IS NULL AND m.termination_date IS NOT NULL;

[User] List all employees whose job titles differ from their direct managers. Provide each employee's full name, their job title, the manager's full name, and the manager's job title.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, e.job_title AS employee_job_title, m.first_name || ' ' || m.last_name AS manager_name, m.job_title AS manager_job_title FROM government_services.employees e JOIN government_services.employees m ON e.manager_employee_id = m.employee_id WHERE e.job_title <> m.job_title;

[User] Show a list of departments with more than 5 employees. Include the department name and the count.

[Assistant]
SELECT department, COUNT(*) AS employee_count
FROM government_services.employees
GROUP BY department
HAVING COUNT(*) > 5;

[User] Also, only include departments where at least one employee's access level is 'Admin'.

[Assistant]
SELECT department, COUNT(*) AS employee_count
FROM government_services.employees
WHERE department IN (
    SELECT department
    FROM government_services.employees
    WHERE access_level = 'Admin'
)
GROUP BY department
HAVING COUNT(*) > 5;

[User] Could you provide the average hire date for each of those departments as well?

[Assistant]
SELECT department, COUNT(*) AS employee_count, AVG(hire_date) AS avg_hire_date
FROM government_services.employees
WHERE department IN (
    SELECT department
    FROM government_services.employees
    WHERE access_level = 'Admin'
)
GROUP BY department
HAVING COUNT(*) > 5;

[User] I got an error that AVG(hire_date) is not allowed. Please return the earliest (MIN) hire date instead.

[Assistant]
SELECT department, COUNT(*) AS employee_count, MIN(hire_date) AS earliest_hire_date
FROM government_services.employees
WHERE department IN (
    SELECT department
    FROM government_services.employees
    WHERE access_level = 'Admin'
)
GROUP BY department
HAVING COUNT(*) > 5;

[User] Which employees are managers themselves? Show their employee ID, full name, and job title.

[Assistant]
SELECT DISTINCT m.employee_id, m.first_name || ' ' || m.last_name AS full_name, m.job_title
FROM government_services.employees m
JOIN government_services.employees e ON e.manager_employee_id = m.employee_id;

[User] Show the full name, job title, and termination date for all employees whose job title includes the word 'Specialist' and who are no longer employed.

[Assistant] SELECT first_name, last_name, job_title, termination_date FROM government_services.employees WHERE job_title LIKE '%Specialist%' AND termination_date IS NOT NULL;

[User] List the full names of employees whose direct manager themselves report to another manager. Also show the direct manager's full name.

[Assistant] SELECT E.first_name, E.last_name, M.first_name AS manager_first_name, M.last_name AS manager_last_name FROM government_services.employees AS E JOIN government_services.employees AS M ON E.manager_employee_id = M.employee_id WHERE M.manager_employee_id IS NOT NULL;

[User] Which employees share the same department with at least one other employee? Please show the employee ID, full name, and department.

[Assistant]
SELECT e1.employee_id, e1.first_name || ' ' || e1.last_name AS full_name, e1.department
FROM government_services.employees e1
WHERE e1.department IS NOT NULL AND EXISTS (
    SELECT 1 FROM government_services.employees e2
    WHERE e2.department = e1.department AND e2.employee_id <> e1.employee_id
);

[User] How many employees have a manager assigned to them?

[Assistant]
SELECT COUNT(*) AS employee_count
FROM government_services.employees
WHERE manager_employee_id IS NOT NULL;


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. 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 train_station_management.platforms ( platform_id text, station_id text, platform_number text, track_number text, status text, length_meters numeric, accessible boolean )

[User] What is the maintenance schedule for platform 3 at station DEF for the next month?

[Assistant] I'm sorry, but I don't have access to the maintenance schedule for platforms. The data I have only includes static information about platform details such as ID, station, number, track, status, length, and accessibility. For maintenance schedules, you may need to consult the station management or relevant department.

[User] What is the average delay time for trains departing from platform 4 at station LMN during the past year?

[Assistant] I'm sorry, but I can't provide information on train delay times as this data is not stored in the platforms table. The table only contains details about platform characteristics such as ID, station, number, track, status, length, and accessibility. For delay statistics, you may need to refer to a different dataset or system.

[User] What is the history of incidents or accidents that occurred on platform 5 at station GHI?

[Assistant] I'm sorry, but I can't provide information about the history of incidents or accidents on platform 5 at station GHI. My data is limited to the structural and operational details of the platforms, such as platform ID, station ID, and status. For incident history, you may need to consult a different database or contact the relevant authorities.


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] List staff members who responded to public reviews with an overall rating of 3 or less. Include the staff member's first name, last name, and the review ID.

[Assistant] SELECT T1.first_name, T1.last_name, T2.review_id FROM staff AS T1 JOIN reviews AS T2 ON T1.staff_id = T2.response_staff_id WHERE T2.is_public = TRUE AND T2.rating_overall <= 3;

[User] Also, only show reviews where the cleanliness rating was 3 or less.

[Assistant] SELECT T1.first_name, T1.last_name, T2.review_id FROM staff AS T1 JOIN reviews AS T2 ON T1.staff_id = T2.response_staff_id WHERE T2.is_public = TRUE AND T2.rating_overall <= 3 AND T2.rating_cleanliness <= 3;

[User] Instead of listing each review, show the count of such reviews for each staff member.

[Assistant] SELECT T1.first_name, T1.last_name, COUNT(T2.review_id) AS review_count FROM staff AS T1 JOIN reviews AS T2 ON T1.staff_id = T2.response_staff_id WHERE T2.is_public = TRUE AND T2.rating_overall <= 3 AND T2.rating_cleanliness <= 3 GROUP BY T1.staff_id, T1.first_name, T1.last_name;

[User] List all staff members who processed payments for guest ID 'G123', including their first name, last name, and the payment ID.

[Assistant] SELECT T1.first_name, T1.last_name, T2.payment_id FROM staff AS T1 JOIN payments AS T2 ON T1.staff_id = T2.staff_id_processed WHERE T2.guest_id = 'G123';

[User] Show all public reviews that have a comment.

[Assistant] SELECT review_id, property_id, guest_id, rating_overall, comment FROM reviews WHERE is_public = TRUE AND comment IS NOT NULL AND comment != '';

[User] From those, only show reviews with an overall rating of 5.

[Assistant] SELECT review_id, property_id, guest_id, rating_overall, comment FROM reviews WHERE is_public = TRUE AND comment IS NOT NULL AND comment != '' AND rating_overall = 5;

[User] For each property in the 'USA' country, list the property name and the total count of services that cost more than 50.

[Assistant] SELECT T1.property_name, COUNT(T2.service_id) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.services AS T2 ON T1.property_id = T2.property_id WHERE T1.country_code = 'USA' AND T2.price > 50 GROUP BY T1.property_name;

[User] List all services, showing the service name, category, and the name of the property where it is offered.

[Assistant] SELECT T1.service_name, T1.category, T2.property_name FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id;

[User] Please filter the results to only include services that are currently available.

[Assistant] SELECT T1.service_name, T1.category, T2.property_name FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.is_available = TRUE;

[User] Can you also include the star rating of the property and order the results by property star rating descending?

[Assistant] SELECT T1.service_name, T1.category, T2.property_name, T2.star_rating FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.is_available = TRUE ORDER BY T2.star_rating 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 government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

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

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

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

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

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

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

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

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

[User] Find all notifications where the message subject contains the word 'Alert'.

[Assistant] SELECT notification_id, citizen_id, application_id, message_subject, message_body, channel, sent_at, status, related_entity_type, related_entity_id FROM government_services.notifications WHERE message_subject LIKE '%Alert%';

[User] List all notifications sent through the 'Email' channel, showing all columns.

[Assistant] SELECT notification_id, citizen_id, application_id, message_subject, message_body, channel, sent_at, status, related_entity_type, related_entity_id FROM government_services.notifications WHERE channel = 'Email';

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

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

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

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

[User] List the message subjects for all notifications sent via the 'Push' channel that have a 'Sent' status.

[Assistant] SELECT message_subject FROM government_services.notifications WHERE channel = 'Push' AND status = 'Sent';

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

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

[User] Find the application IDs for applications that have received notifications through both 'Email' and 'SMS' channels.

[Assistant] SELECT application_id FROM government_services.notifications WHERE channel IN ('Email', 'SMS') GROUP BY application_id HAVING COUNT(DISTINCT channel) = 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 web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )

[User] For each user, count the number of events emitted by smart contracts they deployed. Return user_id, username, and event_count, ordered by event_count descending.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(e.event_id) AS event_count
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
JOIN web3.contracts c ON w.address = c.deployer_address
LEFT JOIN web3.events e ON c.contract_id = e.contract_id
GROUP BY u.user_id, u.username
ORDER BY event_count DESC;

[User] For each block, get the count of failed transactions and the total gas used by these failed transactions. Show block_number, failed_tx_count, and total_failed_gas.

[Assistant]
SELECT block_number,
       COUNT(*) FILTER (WHERE status = 'failed') AS failed_tx_count,
       SUM(gas_used) FILTER (WHERE status = 'failed') AS total_failed_gas
FROM web3.transactions
GROUP BY block_number;

[User] Actually, I need only blocks with failed_tx_count greater than 10.

[Assistant]
SELECT block_number,
       COUNT(*) FILTER (WHERE status = 'failed') AS failed_tx_count,
       SUM(gas_used) FILTER (WHERE status = 'failed') AS total_failed_gas
FROM web3.transactions
GROUP BY block_number
HAVING COUNT(*) FILTER (WHERE status = 'failed') > 10;

[User] Show the wallet address, token symbol, and the total value received by each wallet for each token. Only include wallets that have received tokens.

[Assistant]
SELECT w.address AS wallet_address, t.token_symbol, SUM(tt.value) AS total_received_value
FROM web3.wallets w
JOIN web3.token_transfers tt ON w.address = tt.to_address
JOIN web3.tokens t ON tt.token_id = t.token_id
GROUP BY w.address, t.token_symbol
ORDER BY w.address, t.token_symbol;

[User] For each user, count the number of distinct smart contracts they have called. Return user_id, username, and contract_count, ordered by contract_count descending.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(DISTINCT tx.to_address) AS contract_count
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
JOIN web3.transactions tx ON w.address = tx.from_address
JOIN web3.contracts c ON tx.to_address = c.address
GROUP BY u.user_id, u.username
ORDER BY contract_count DESC;

[User] List the username, registration date, and address of all users who have created a wallet.

[Assistant]
SELECT u.username, u.created_at AS registration_date, w.address AS wallet_address
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
ORDER BY u.username, w.created_at;

[User] Can you also include how many wallets each user has created in the result?

[Assistant]
SELECT u.username, u.created_at AS registration_date, COUNT(w.wallet_id) AS wallet_count
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
GROUP BY u.user_id, u.username, u.created_at
ORDER BY u.username;

[User] Find the wallet address, user ID, and the contract address of any contract where that wallet is listed as the deployer.

[Assistant]
SELECT w.address AS wallet_address, w.user_id, c.address AS contract_address
FROM web3.wallets w
JOIN web3.contracts c ON w.address = c.deployer_address;

[User] List all failed transactions along with the from and to addresses, and the gas used.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used FROM web3.transactions WHERE status = 'failed';

[User] Actually, I also need to see the block number and timestamp for these failed transactions.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used, block_number, timestamp FROM web3.transactions WHERE status = 'failed';

[User] There's a typo in your SQL, it should be 'timestamp' not 'timestamp'. Also, sort the results by block number in descending order.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used, block_number, timestamp FROM web3.transactions WHERE status = 'failed' ORDER BY block_number DESC;

[User] Now filter to only show transactions with gas used greater than 100,000.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used, block_number, timestamp FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000 ORDER BY block_number DESC;

[User] List all transactions that include an event with the name 'Transfer', showing the transaction ID, the event name, and the transaction's value.

[Assistant] SELECT t.transaction_id, e.event_name, t.value FROM web3.transactions AS t JOIN web3.events AS e ON t.transaction_id = e.transaction_id WHERE e.event_name = 'Transfer';

[User] List all pairs of transactions where the recipient of the first transaction became the sender in the second, showing the first transaction_id, the second transaction_id, the shared address, and the timestamps of both transactions.

[Assistant] SELECT t1.transaction_id AS first_transaction_id, t2.transaction_id AS second_transaction_id, t1.to_address AS shared_address, t1.timestamp AS first_transaction_timestamp, t2.timestamp AS second_transaction_timestamp FROM web3.transactions AS t1 JOIN web3.transactions AS t2 ON t1.to_address = t2.from_address WHERE t1.transaction_id <> t2.transaction_id AND t2.timestamp > t1.timestamp;

[User] Show the transaction ID, the transaction value from the transactions table, and the sum of the value from token_transfers for all transactions that have at least one associated token transfer. Name the sum column total_token_transfer_value.

[Assistant] SELECT t.transaction_id, t.value AS transaction_native_value, SUM(tt.value) AS total_token_transfer_value FROM web3.transactions t JOIN web3.token_transfers tt ON t.transaction_id = tt.transaction_id GROUP BY t.transaction_id, t.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 legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )

[User] Show me the names and websites of all law firms founded before 2000, along with their managing partner IDs.

[Assistant] SELECT firm_name, website, managing_partner_id FROM legal_services.law_firms WHERE founded_date < '2000-01-01';

[User] List all law firms whose address contains 'Avenue'.

[Assistant] SELECT firm_id, firm_name, address FROM legal_services.law_firms WHERE address LIKE '%Avenue%';

[User] Retrieve each managing partner who oversees more than one firm, showing the managing_partner_id and the count of firms they manage.

[Assistant]
SELECT managing_partner_id, COUNT(*) AS firm_count
FROM legal_services.law_firms
GROUP BY managing_partner_id
HAVING COUNT(*) > 1;

[User] Actually, I want to include the names of the firms under each managing partner, separated by commas.

[Assistant]
SELECT managing_partner_id,
       COUNT(*) AS firm_count,
       STRING_AGG(firm_name, ', ') AS firms
FROM legal_services.law_firms
GROUP BY managing_partner_id
HAVING COUNT(*) > 1;

[User] Also, exclude any records where the managing_partner_id is null and sort the results by firm_count descending.

[Assistant]
SELECT managing_partner_id,
       COUNT(*) AS firm_count,
       STRING_AGG(firm_name, ', ') AS firms
FROM legal_services.law_firms
WHERE managing_partner_id IS NOT NULL
GROUP BY managing_partner_id
HAVING COUNT(*) > 1
ORDER BY firm_count DESC;

[User] Find all pairs of law firms founded in the same year, showing both firm names and the shared founding year.

[Assistant]
SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS founding_year
FROM legal_services.law_firms f1
JOIN legal_services.law_firms f2
  ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date)
  AND f1.firm_id < f2.firm_id;

[User] Show me the names and phone numbers of all law firms founded in the same city.

[Assistant]
SELECT lf1.firm_name AS firm1_name, lf1.phone AS firm1_phone, lf2.firm_name AS firm2_name, lf2.phone AS firm2_phone, lf1.address
FROM legal_services.law_firms lf1
JOIN legal_services.law_firms lf2 ON lf1.address = lf2.address AND lf1.firm_id < lf2.firm_id;

[User] Show me law firms that were founded after 2018 and have a website provided.

[Assistant]
SELECT firm_name, founded_date, website
FROM legal_services.law_firms
WHERE founded_date > '2018-12-31' AND website IS NOT NULL AND website <> '';

[User] Actually, only include firms where the phone number starts with '+1'.

[Assistant]
SELECT firm_name, founded_date, website, phone
FROM legal_services.law_firms
WHERE founded_date > '2018-12-31' AND website IS NOT NULL AND website <> '' AND phone LIKE '+1%';

[User] Also add the firm address and sort the results by founded_date descending.

[Assistant]
SELECT firm_name, founded_date, website, phone, address
FROM legal_services.law_firms
WHERE founded_date > '2018-12-31' AND website IS NOT NULL AND website <> '' AND phone LIKE '+1%'
ORDER BY founded_date DESC;

[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] List all law firms that do not have a managing partner listed.

[Assistant]
SELECT firm_name, phone, address, founded_date
FROM legal_services.law_firms
WHERE managing_partner_id IS NULL;

[User] Which law firms were founded in the same year and share the same managing partner? Show the firm names, founding year, and managing partner ID.

[Assistant]
SELECT f1.firm_name AS firm_name_1, f2.firm_name AS firm_name_2, EXTRACT(YEAR FROM f1.founded_date) AS founding_year, f1.managing_partner_id
FROM legal_services.law_firms f1
JOIN legal_services.law_firms f2
  ON f1.firm_id <> f2.firm_id
  AND EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date)
  AND f1.managing_partner_id = f2.managing_partner_id
ORDER BY founding_year, f1.firm_name, f2.firm_name;

[User] Show the names and phone numbers of all law firms whose website ends with '.org'.

[Assistant]
SELECT firm_name, phone
FROM legal_services.law_firms
WHERE website LIKE '%.org';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)

[User] List the total number of appointments for each status and also show the latest appointment_time for each status.

[Assistant]
SELECT status, COUNT(*) AS total_appointments, MAX(appointment_time) AS latest_appointment_time
FROM healthcare.appointments
GROUP BY status;

[User] List the appointment_id, patient_id, and reason for all appointments where the notes mention 'urgent'.

[Assistant]
SELECT appointment_id, patient_id, reason
FROM healthcare.appointments
WHERE notes ILIKE '%urgent%';

[User] Show me the total number of appointments grouped by each unique duration in minutes. Include only durations with more than 5 appointments.

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

[User] Can you also show, for each of these durations, the earliest and latest appointment_time?

[Assistant]
SELECT duration_minutes, COUNT(*) AS appointment_count,
       MIN(appointment_time) AS earliest_appointment,
       MAX(appointment_time) AS latest_appointment
FROM healthcare.appointments
GROUP BY duration_minutes
HAVING COUNT(*) > 5;

[User] List all appointments with a non-empty notes field. Return appointment_id, appointment_time, and doctor_id.

[Assistant]
SELECT appointment_id, appointment_time, doctor_id
FROM healthcare.appointments
WHERE notes IS NOT NULL AND notes <> '';

[User] Could you further filter to only appointments where status is 'No-show'?

[Assistant]
SELECT appointment_id, appointment_time, doctor_id
FROM healthcare.appointments
WHERE notes IS NOT NULL AND notes <> ''
  AND status = 'No-show';

[User] Show me all appointments for doctor 'doctor_100' in June 2024, including the appointment time and the patient ID.

[Assistant]
SELECT appointment_id, patient_id, appointment_time
FROM healthcare.appointments
WHERE doctor_id = 'doctor_100'
  AND appointment_time >= '2024-06-01'::timestamp
  AND appointment_time < '2024-07-01'::timestamp;

[User] Can you also add the appointment status and sort by appointment_time ascending?

[Assistant]
SELECT appointment_id, patient_id, appointment_time, status
FROM healthcare.appointments
WHERE doctor_id = 'doctor_100'
  AND appointment_time >= '2024-06-01'::timestamp
  AND appointment_time < '2024-07-01'::timestamp
ORDER BY appointment_time ASC;

[User] Now, only include the appointments with status 'Completed'.

[Assistant]
SELECT appointment_id, patient_id, appointment_time, status
FROM healthcare.appointments
WHERE doctor_id = 'doctor_100'
  AND appointment_time >= '2024-06-01'::timestamp
  AND appointment_time < '2024-07-01'::timestamp
  AND status = 'Completed'
ORDER BY appointment_time ASC;

[User] I got an empty result, but I expected at least one appointment. Could you check if the status value is in lowercase instead?

[Assistant]
SELECT appointment_id, patient_id, appointment_time, status
FROM healthcare.appointments
WHERE doctor_id = 'doctor_100'
  AND appointment_time >= '2024-06-01'::timestamp
  AND appointment_time < '2024-07-01'::timestamp
  AND LOWER(status) = 'completed'
ORDER BY appointment_time ASC;

[User] List all appointments that were marked as 'No-show'. Show appointment ID, patient ID, and appointment time.

[Assistant] SELECT appointment_id, patient_id, appointment_time FROM healthcare.appointments WHERE status = 'No-show';

[User] Can you find all appointments where the duration is less than 20 minutes and the status is not 'Cancelled'? For each, show the appointment_id, appointment_time, status, and doctor_id.

[Assistant]
SELECT appointment_id, appointment_time, status, doctor_id
FROM healthcare.appointments
WHERE duration_minutes < 20
  AND status <> 'Cancelled';

[User] Now, only show appointments that took place at locations with an ID starting with 'CLINIC'.

[Assistant]
SELECT appointment_id, appointment_time, status, doctor_id, location_id
FROM healthcare.appointments
WHERE duration_minutes < 20
  AND status <> 'Cancelled'
  AND location_id LIKE 'CLINIC%';

[User] Can you also add the notes field to the output and sort results by appointment_time ascending?

[Assistant]
SELECT appointment_id, appointment_time, status, doctor_id, location_id, notes
FROM healthcare.appointments
WHERE duration_minutes < 20
  AND status <> 'Cancelled'
  AND location_id LIKE 'CLINIC%'
ORDER BY appointment_time ASC;

[User] Show me all appointments scheduled to last exactly 60 minutes.

[Assistant]
SELECT appointment_id, patient_id, doctor_id, appointment_time, duration_minutes, status
FROM healthcare.appointments
WHERE duration_minutes = 60;

[User] List the medical record ID and record date for all medical records that are linked to an appointment whose duration was longer than the average duration of all appointments.

[Assistant] SELECT T1.record_id, T1.record_date FROM healthcare.medical_records AS T1 JOIN healthcare.appointments AS T2 ON T1.appointment_id = T2.appointment_id WHERE T2.duration_minutes > (SELECT AVG(duration_minutes) FROM healthcare.appointments);

[User] List the first name, last name, prescription ID, diagnosis code, and diagnosis description for patients who have both an ongoing prescription and an active chronic diagnosis.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T2.prescription_id, T3.diagnosis_code, T3.description FROM healthcare.patients AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.diagnoses AS T3 ON T1.patient_id = T3.patient_id WHERE (T2.end_date IS NULL OR T2.end_date > CURRENT_DATE) AND T3.is_chronic IS TRUE AND T3.status = 'Active';

[User] Refine the results to include only those cases where the prescription started within 30 days before or on the diagnosis date.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T2.prescription_id, T3.diagnosis_code, T3.description FROM healthcare.patients AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.diagnoses AS T3 ON T1.patient_id = T3.patient_id WHERE (T2.end_date IS NULL OR T2.end_date > CURRENT_DATE) AND T3.is_chronic IS TRUE AND T3.status = 'Active' AND T2.start_date BETWEEN T3.diagnosis_date - INTERVAL '30 days' AND T3.diagnosis_date;

[User] Add the full names of the doctor who wrote the prescription and the doctor who made the diagnosis to the results.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T2.prescription_id, T3.diagnosis_code, T3.description, T4.first_name AS prescribing_doctor_first_name, T4.last_name AS prescribing_doctor_last_name, T5.first_name AS diagnosing_doctor_first_name, T5.last_name AS diagnosing_doctor_last_name FROM healthcare.patients AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.diagnoses AS T3 ON T1.patient_id = T3.patient_id JOIN healthcare.doctors AS T4 ON T2.doctor_id = T4.doctor_id JOIN healthcare.doctors AS T5 ON T3.doctor_id = T5.doctor_id WHERE (T2.end_date IS NULL OR T2.end_date > CURRENT_DATE) AND T3.is_chronic IS TRUE AND T3.status = 'Active' AND T2.start_date BETWEEN T3.diagnosis_date - INTERVAL '30 days' AND T3.diagnosis_date;

[User] Filter the results to only include diagnoses with a code type of 'ICD-9' and where either the prescribing or diagnosing doctor has a specialty in 'Cardiology'.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T2.prescription_id, T3.diagnosis_code, T3.description, T4.first_name AS prescribing_doctor_first_name, T4.last_name AS prescribing_doctor_last_name, T5.first_name AS diagnosing_doctor_first_name, T5.last_name AS diagnosing_doctor_last_name FROM healthcare.patients AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.diagnoses AS T3 ON T1.patient_id = T3.patient_id JOIN healthcare.doctors AS T4 ON T2.doctor_id = T4.doctor_id JOIN healthcare.doctors AS T5 ON T3.doctor_id = T5.doctor_id WHERE (T2.end_date IS NULL OR T2.end_date > CURRENT_DATE) AND T3.is_chronic IS TRUE AND T3.status = 'Active' AND T2.start_date BETWEEN T3.diagnosis_date - INTERVAL '30 days' AND T3.diagnosis_date AND T3.code_type = 'ICD-9' AND (T4.specialty = 'Cardiology' OR T5.specialty = 'Cardiology');


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )

[User] Show me all medications, their manufacturer, and NDC code for medications manufactured by 'Johnson & Johnson' or 'Roche'.

[Assistant] SELECT medication_name, manufacturer, ndc_code FROM healthcare.medications WHERE manufacturer IN ('Johnson & Johnson', 'Roche');

[User] Actually, only include medications where the NDC code ends with '99'.

[Assistant] SELECT medication_name, manufacturer, ndc_code FROM healthcare.medications WHERE manufacturer IN ('Johnson & Johnson', 'Roche') AND ndc_code LIKE '%99';

[User] Also return the description and sort the result by medication_name ascending.

[Assistant] SELECT medication_name, manufacturer, ndc_code, description FROM healthcare.medications WHERE manufacturer IN ('Johnson & Johnson', 'Roche') AND ndc_code LIKE '%99' ORDER BY medication_name ASC;

[User] How many medications does each manufacturer have?

[Assistant]
SELECT manufacturer, COUNT(*) AS med_count
FROM healthcare.medications
GROUP BY manufacturer;

[User] Only include manufacturers with more than 10 medications.

[Assistant]
SELECT manufacturer, COUNT(*) AS med_count
FROM healthcare.medications
GROUP BY manufacturer
HAVING COUNT(*) > 10;

[User] List the NDC code and description for any medication that has an NDC code starting with '5'.

[Assistant] SELECT ndc_code, description FROM healthcare.medications WHERE ndc_code LIKE '5%';

[User] Show me the names and manufacturers of all medications that have a description provided.

[Assistant] SELECT medication_name, manufacturer FROM healthcare.medications WHERE description IS NOT NULL;

[User] Now, only show those manufactured by 'Pfizer'.

[Assistant] SELECT medication_name, manufacturer FROM healthcare.medications WHERE description IS NOT NULL AND manufacturer = 'Pfizer';

[User] Further filter to medications whose generic name contains 'statin'.

[Assistant] SELECT medication_name, manufacturer FROM healthcare.medications WHERE description IS NOT NULL AND manufacturer = 'Pfizer' AND generic_name LIKE '%statin%';

[User] Instead, just show the medication ID and NDC code for these.

[Assistant] SELECT medication_id, ndc_code FROM healthcare.medications WHERE description IS NOT NULL AND manufacturer = 'Pfizer' AND generic_name LIKE '%statin%';

[User] Which medications do not have a generic name listed? Show their medication_id, medication_name, and manufacturer.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE generic_name IS NULL OR generic_name = '';

[User] Could you also include the description for each medication?

[Assistant] SELECT medication_id, medication_name, manufacturer, description FROM healthcare.medications WHERE generic_name IS NULL OR generic_name = '';

[User] Show the medication_id, medication_name, and manufacturer for all medication entries.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications;

[User] Filter to show only those where the manufacturer is specified (not null).

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE manufacturer IS NOT NULL;

[User] Also, include only medications where the generic name contains 'acid'.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE manufacturer IS NOT NULL AND generic_name LIKE '%acid%';

[User] Can you add the NDC code to the result?

[Assistant] SELECT medication_id, medication_name, manufacturer, ndc_code FROM healthcare.medications WHERE manufacturer IS NOT NULL AND generic_name LIKE '%acid%';

[User] List all details for medications whose description contains the word 'pain'.

[Assistant] SELECT * FROM healthcare.medications WHERE description LIKE '%pain%';

[User] List all combinations of manufacturers and generic names. For each combination, display the manufacturer, generic_name, and the number of medications.

[Assistant] SELECT manufacturer, generic_name, COUNT(*) AS medication_count FROM healthcare.medications GROUP BY manufacturer, generic_name;

[User] Only show combinations where there are at least 3 medications and exclude rows where generic_name is missing.

[Assistant] SELECT manufacturer, generic_name, COUNT(*) AS medication_count FROM healthcare.medications WHERE generic_name IS NOT NULL AND generic_name <> '' GROUP BY manufacturer, generic_name HAVING COUNT(*) >= 3;

[User] Show me the medication_id, medication_name, and manufacturer for all medications where the generic_name contains the word 'azole'.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE generic_name ILIKE '%azole%';

[User] Can you also include the ndc_code and only show medications where the manufacturer field is not null?

[Assistant] SELECT medication_id, medication_name, manufacturer, ndc_code FROM healthcare.medications WHERE generic_name ILIKE '%azole%' AND manufacturer IS NOT NULL;

[User] Show the medication ID, medication name, and manufacturer for all entries where the generic name is not listed.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE generic_name IS NULL OR generic_name = '';

[User] For all medications, list the medication name, generic name, and the length of the description, but only for descriptions longer than 50 characters.

[Assistant] SELECT medication_name, generic_name, LENGTH(description) AS description_length FROM healthcare.medications WHERE LENGTH(description) > 50;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )

[User] Show me all vehicles that had maintenance in the past month, including their make, model, maintenance service_date, and depot name.

[Assistant]
SELECT v.vehicle_id,
       v.make,
       v.model,
       m.service_date,
       l.name AS depot_name
FROM transportation.maintenance_logs AS m
JOIN transportation.vehicles AS v
  ON m.vehicle_id = v.vehicle_id
LEFT JOIN transportation.locations AS l
  ON v.depot_id = l.location_id
WHERE m.service_date >= CURRENT_DATE - INTERVAL '1 month';

[User] Now, include only those records where the maintenance cost is greater than 500, and order the results by cost descending.

[Assistant]
SELECT v.vehicle_id,
       v.make,
       v.model,
       m.service_date,
       m.cost,
       l.name AS depot_name
FROM transportation.maintenance_logs AS m
JOIN transportation.vehicles AS v
  ON m.vehicle_id = v.vehicle_id
LEFT JOIN transportation.locations AS l
  ON v.depot_id = l.location_id
WHERE m.service_date >= CURRENT_DATE - INTERVAL '1 month'
  AND m.cost > 500
ORDER BY m.cost DESC;

[User] List each depot name and the total number of vehicles assigned to it, but only include depots with at least 5 vehicles.

[Assistant]
SELECT l.name AS depot_name,
       COUNT(v.vehicle_id) AS total_vehicles
FROM transportation.locations AS l
JOIN transportation.vehicles AS v
  ON v.depot_id = l.location_id
GROUP BY l.name
HAVING COUNT(v.vehicle_id) >= 5;

[User] Actually, could you also include the average capacity and the most recent acquisition year of vehicles for each depot?

[Assistant]
SELECT l.name AS depot_name,
       COUNT(v.vehicle_id) AS total_vehicles,
       AVG(v.capacity) AS average_capacity,
       MAX(v.year)   AS latest_acquisition_year
FROM transportation.locations AS l
JOIN transportation.vehicles AS v
  ON v.depot_id = l.location_id
GROUP BY l.name
HAVING COUNT(v.vehicle_id) >= 5;

[User] Now filter the results to only show depots located in California (state_province = 'CA') and sort by total number of vehicles descending.

[Assistant]
SELECT l.name AS depot_name,
       COUNT(v.vehicle_id) AS total_vehicles,
       AVG(v.capacity) AS average_capacity,
       MAX(v.year)   AS latest_acquisition_year
FROM transportation.locations AS l
JOIN transportation.vehicles AS v
  ON v.depot_id = l.location_id
WHERE l.state_province = 'CA'
GROUP BY l.name
HAVING COUNT(v.vehicle_id) >= 5
ORDER BY total_vehicles DESC;

[User] Can you provide the total number of fuel refueling events and the sum of total_cost at each fueling location, including the location name and city?

[Assistant]
SELECT l.location_id, l.name, l.city, COUNT(fl.fuel_log_id) AS num_refuels, SUM(fl.total_cost) AS total_cost
FROM transportation.fuel_logs fl
JOIN transportation.locations l ON fl.location_id = l.location_id
GROUP BY l.location_id, l.name, l.city;

[User] I want to see the total fare and number of bookings for each passenger.

[Assistant]
SELECT b.passenger_id, COUNT(b.booking_id) AS booking_count, SUM(b.fare) AS total_fare
FROM transportation.bookings b
GROUP BY b.passenger_id;

[User] Only show passengers whose total fare exceeds 200.

[Assistant]
SELECT b.passenger_id, COUNT(b.booking_id) AS booking_count, SUM(b.fare) AS total_fare
FROM transportation.bookings b
GROUP BY b.passenger_id
HAVING SUM(b.fare) > 200;

[User] Also include the latest booking_time for each of those passengers.

[Assistant]
SELECT b.passenger_id, COUNT(b.booking_id) AS booking_count, SUM(b.fare) AS total_fare, MAX(b.booking_time) AS last_booking
FROM transportation.bookings b
GROUP BY b.passenger_id
HAVING SUM(b.fare) > 200;

[User] Exclude any bookings with status 'Cancelled'.

[Assistant]
SELECT b.passenger_id, COUNT(b.booking_id) AS booking_count, SUM(b.fare) AS total_fare, MAX(b.booking_time) AS last_booking
FROM transportation.bookings b
WHERE b.status <> 'Cancelled'
GROUP BY b.passenger_id
HAVING SUM(b.fare) > 200;

[User] Show the average maintenance cost for each service type per vehicle.

[Assistant]
SELECT vehicle_id,
       service_type,
       AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY vehicle_id, service_type;

[User] Actually, only include those averages greater than 300.

[Assistant]
SELECT vehicle_id,
       service_type,
       AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY vehicle_id, service_type
HAVING AVG(cost) > 300;

[User] Also include the number of services for each of those.

[Assistant]
SELECT vehicle_id,
       service_type,
       COUNT(*) AS service_count,
       AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY vehicle_id, service_type
HAVING AVG(cost) > 300;

[User] Sort the results by avg_cost descending and limit to the top 5.

[Assistant]
SELECT vehicle_id,
       service_type,
       COUNT(*) AS service_count,
       AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY vehicle_id, service_type
HAVING AVG(cost) > 300
ORDER BY avg_cost DESC
LIMIT 5;

[User] List each vehicle along with the city of the station where it had its most recent fueling and the timestamp of that fueling.

[Assistant]
SELECT v.vehicle_id,
       v.license_plate,
       l.city AS last_fuel_city,
       MAX(f.log_timestamp) AS last_fuel_time
FROM transportation.vehicles v
JOIN transportation.fuel_logs f
  ON v.vehicle_id = f.vehicle_id
JOIN transportation.locations l
  ON f.location_id = l.location_id
GROUP BY v.vehicle_id, v.license_plate, l.city
ORDER BY last_fuel_time DESC;

[User] Retrieve each vehicle's make and model along with the date and description of its latest maintenance service.

[Assistant]
SELECT v.vehicle_id,
       v.make,
       v.model,
       m.service_date,
       m.description
FROM transportation.vehicles v
JOIN (
  SELECT vehicle_id,
         MAX(service_date) AS max_date
  FROM transportation.maintenance_logs
  GROUP BY vehicle_id
) latest
  ON v.vehicle_id = latest.vehicle_id
JOIN transportation.maintenance_logs m
  ON m.vehicle_id = latest.vehicle_id
 AND m.service_date = latest.max_date;

[User] List all drivers whose licenses expire in the next 30 days, along with their contact information.

[Assistant] SELECT driver_id, first_name, last_name, license_number, license_expiry_date, contact_number, email FROM transportation.drivers WHERE license_expiry_date BETWEEN CURRENT_DATE AND DATE_ADD(CURRENT_DATE, INTERVAL 30 DAY);

[User] Now include the count of trips each of these drivers has completed in the past month.

[Assistant] SELECT d.driver_id, d.first_name, d.last_name, d.license_number, d.license_expiry_date, d.contact_number, d.email, COUNT(t.trip_id) AS trips_last_month FROM transportation.drivers d LEFT JOIN transportation.trips t ON d.driver_id = t.driver_id AND t.status = 'completed' AND t.actual_departure_time >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) WHERE d.license_expiry_date BETWEEN CURRENT_DATE AND DATE_ADD(CURRENT_DATE, INTERVAL 30 DAY) GROUP BY d.driver_id, d.first_name, d.last_name, d.license_number, d.license_expiry_date, d.contact_number, d.email;

[User] Can you filter this to only show drivers who have completed more than 10 trips in the past month?

[Assistant] SELECT d.driver_id, d.first_name, d.last_name, d.license_number, d.license_expiry_date, d.contact_number, d.email, COUNT(t.trip_id) AS trips_last_month FROM transportation.drivers d LEFT JOIN transportation.trips t ON d.driver_id = t.driver_id AND t.status = 'completed' AND t.actual_departure_time >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) WHERE d.license_expiry_date BETWEEN CURRENT_DATE AND DATE_ADD(CURRENT_DATE, INTERVAL 30 DAY) GROUP BY d.driver_id, d.first_name, d.last_name, d.license_number, d.license_expiry_date, d.contact_number, d.email HAVING COUNT(t.trip_id) > 10;

[User] Now order the results by license expiry date with the soonest expiring first.

[Assistant] SELECT d.driver_id, d.first_name, d.last_name, d.license_number, d.license_expiry_date, d.contact_number, d.email, COUNT(t.trip_id) AS trips_last_month FROM transportation.drivers d LEFT JOIN transportation.trips t ON d.driver_id = t.driver_id AND t.status = 'completed' AND t.actual_departure_time >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) WHERE d.license_expiry_date BETWEEN CURRENT_DATE AND DATE_ADD(CURRENT_DATE, INTERVAL 30 DAY) GROUP BY d.driver_id, d.first_name, d.last_name, d.license_number, d.license_expiry_date, d.contact_number, d.email HAVING COUNT(t.trip_id) > 10 ORDER BY d.license_expiry_date ASC;

[User] Show me the date of birth and email for all passengers.

[Assistant] SELECT date_of_birth, email FROM transportation.passengers;

[User] Can you also include their phone number and creation date?

[Assistant] SELECT date_of_birth, email, phone_number, created_at FROM transportation.passengers;

[User] Only show passengers who were created after '2022-06-01'.

[Assistant] SELECT date_of_birth, email, phone_number, created_at FROM transportation.passengers WHERE created_at >= '2022-06-01';

[User] Order the results by creation date in descending order and limit to 10.

[Assistant] SELECT date_of_birth, email, phone_number, created_at FROM transportation.passengers WHERE created_at >= '2022-06-01' ORDER BY created_at 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 web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[User] For each user, what is the average time difference in days between their wallet creations? Return user_id and avg_diff_days.

[Assistant]
WITH diffs AS (
  SELECT
    user_id,
    EXTRACT(EPOCH FROM (created_at - LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at))) / 86400 AS diff_days
  FROM web3.wallets
)
SELECT
  user_id,
  AVG(diff_days) AS avg_diff_days
FROM diffs
WHERE diff_days IS NOT NULL
GROUP BY user_id;

[User] Actually, only include users who have created more than 2 wallets.

[Assistant]
WITH diffs AS (
  SELECT
    user_id,
    EXTRACT(EPOCH FROM (created_at - LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at))) / 86400 AS diff_days
  FROM web3.wallets
)
SELECT
  user_id,
  AVG(diff_days) AS avg_diff_days
FROM diffs
WHERE diff_days IS NOT NULL
GROUP BY user_id
HAVING COUNT(diff_days) > 1;

[User] For each user, show the date of their earliest and latest wallet creation.

[Assistant]
SELECT user_id,
       MIN(created_at) AS first_created,
       MAX(created_at) AS last_created
FROM web3.wallets
GROUP BY user_id;

[User] Actually, also include the count of wallets each user has created.

[Assistant]
SELECT user_id,
       MIN(created_at) AS first_created,
       MAX(created_at) AS last_created,
       COUNT(*) AS wallet_count
FROM web3.wallets
GROUP BY user_id;

[User] What is the total number of wallets recorded?

[Assistant] SELECT COUNT(*) FROM web3.wallets;

[User] Can you show me the number of wallets created on each distinct date?

[Assistant] SELECT DATE(created_at), COUNT(*) FROM web3.wallets GROUP BY DATE(created_at);

[User] For each wallet, find the previous wallet created by the same user. Show current wallet_id, previous_wallet_id, user_id, and the difference in days between their creation dates.

[Assistant]
SELECT
  wallet_id AS current_wallet_id,
  LAG(wallet_id) OVER (PARTITION BY user_id ORDER BY created_at) AS previous_wallet_id,
  user_id,
  EXTRACT(EPOCH FROM (
    created_at - LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at)
  )) / 86400 AS diff_days
FROM web3.wallets;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)

[User] List all room numbers, their type names, and base rates for rooms located on floor 5.

[Assistant] SELECT T1.room_number, T2.type_name, T2.base_rate FROM hospitality_technology.rooms AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.room_type_id = T2.room_type_id WHERE T1.floor = 5;

[User] Now, only include those with the feature 'Sea View' and are currently 'Available'. Sort the results by base rate ascending.

[Assistant] SELECT T1.room_number, T2.type_name, T2.base_rate FROM hospitality_technology.rooms AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.room_type_id = T2.room_type_id WHERE T1.floor = 5 AND T1.features LIKE '%Sea View%' AND T1.status = 'Available' ORDER BY T2.base_rate ASC;

[User] List all reservations made by guests from 'US', showing the reservation ID, guest first name, last name, and the property name.

[Assistant] SELECT T1.reservation_id, T2.first_name, T2.last_name, T3.property_name FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T2.country_code = 'US';

[User] Only show reservations with status 'Confirmed'.

[Assistant] SELECT T1.reservation_id, T2.first_name, T2.last_name, T3.property_name FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T2.country_code = 'US' AND T1.status = 'Confirmed';

[User] Also include the check-in and check-out dates, and order by check-in date descending.

[Assistant] SELECT T1.reservation_id, T2.first_name, T2.last_name, T3.property_name, T1.check_in_date, T1.check_out_date FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T2.country_code = 'US' AND T1.status = 'Confirmed' ORDER BY T1.check_in_date DESC;

[User] List all rooms, showing their room number, type name, and the name of the property they are in.

[Assistant] SELECT T1.room_number, T2.type_name, T3.property_name FROM hospitality_technology.rooms AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.room_type_id = T2.room_type_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id;

[User] Show me all rooms with their room number, the type name, and the maximum occupancy for each room.

[Assistant]
SELECT r.room_id, r.room_number, rt.type_name, rt.max_occupancy
FROM hospitality_technology.rooms r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id;

[User] List all rooms, including their room number, the name of the property they belong to, and their room type name, specifically for rooms with 'Maintenance' status.

[Assistant] SELECT T1.room_number, T2.property_name, T3.type_name FROM rooms AS T1 JOIN properties AS T2 ON T1.property_id = T2.property_id JOIN room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.status = 'Maintenance'

[User] Also include the floor number and filter to only show rooms located on floors 5 or higher. Sort the results by property name and then by floor.

[Assistant] SELECT T1.room_number, T2.property_name, T3.type_name, T1.floor FROM rooms AS T1 JOIN properties AS T2 ON T1.property_id = T2.property_id JOIN room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.status = 'Maintenance' AND T1.floor >= 5 ORDER BY T2.property_name, T1.floor

[User] Show me the room number, floor, and the name of the property for all rooms located in properties in Texas.

[Assistant] SELECT T1.room_number, T1.floor, T2.property_name FROM hospitality_technology.rooms AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T2.state_province = 'Texas';

[User] Now, only include rooms with status 'Available' that are non-smoking.

[Assistant] SELECT T1.room_number, T1.floor, T2.property_name FROM hospitality_technology.rooms AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T2.state_province = 'Texas' AND T1.status = 'Available' AND T1.is_smoking = false;

[User] Only show those rooms on floors 1 through 3 and order the results by property name then room number.

[Assistant] SELECT T1.room_number, T1.floor, T2.property_name FROM hospitality_technology.rooms AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T2.state_province = 'Texas' AND T1.status = 'Available' AND T1.is_smoking = false AND T1.floor BETWEEN 1 AND 3 ORDER BY T2.property_name ASC, T1.room_number ASC;

[User] Retrieve the guest_id, first_name, last_name, and loyalty_member_id for all guests who have communication_consent enabled.

[Assistant]
SELECT guest_id, first_name, last_name, loyalty_member_id
FROM hospitality_technology.guests
WHERE communication_consent = true;

[User] Now, only include those guests with a non-null loyalty_member_id and sort by last_name ascending.

[Assistant]
SELECT guest_id, first_name, last_name, loyalty_member_id
FROM hospitality_technology.guests
WHERE communication_consent = true
  AND loyalty_member_id IS NOT NULL
ORDER BY last_name ASC;

[User] Show me all non-smoking rooms on the first floor, including their room number and the property name.

[Assistant]
SELECT r.room_number, p.property_name
FROM hospitality_technology.rooms r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.is_smoking = false AND r.floor = 1;

[User] Actually, also include the status of each room in the results.

[Assistant]
SELECT r.room_number, p.property_name, r.status
FROM hospitality_technology.rooms r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.is_smoking = false AND r.floor = 1;

[User] Show me each room's number and the total amount of payments processed for that room.

[Assistant]
SELECT r.room_number, SUM(p.amount) AS total_payments
FROM hospitality_technology.rooms r
JOIN hospitality_technology.payments p ON r.room_id = p.reservation_id
GROUP BY r.room_number;

[User] Include only rooms where the total_payments is greater than 1000.

[Assistant]
SELECT r.room_number, SUM(p.amount) AS total_payments
FROM hospitality_technology.rooms r
JOIN hospitality_technology.payments p ON r.room_id = p.reservation_id
GROUP BY r.room_number
HAVING SUM(p.amount) > 1000;

[User] List all guests who placed a service order with a total price greater than 200, including their first name, last name, and the order ID.

[Assistant] SELECT T1.first_name, T1.last_name, T2.order_id FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.service_orders AS T2 ON T1.guest_id = T2.guest_id WHERE T2.total_price > 200;


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[User] For each policy, find its immediate predecessor policy for the same customer. Return customer_id, predecessor policy_number, current policy_number, predecessor end_date, and current start_date.

[Assistant]
WITH ranked AS (
  SELECT p2.customer_id,
         p2.policy_number          AS current_policy,
         p2.start_date             AS current_start,
         p1.policy_number          AS prev_policy,
         p1.end_date               AS prev_end,
         ROW_NUMBER() OVER (
           PARTITION BY p2.customer_id, p2.policy_number
           ORDER BY p1.end_date DESC
         )                       AS rn
  FROM insurance.policies p2
  JOIN insurance.policies p1
    ON p1.customer_id = p2.customer_id
   AND p1.end_date < p2.start_date
)
SELECT customer_id,
       prev_policy AS predecessor_policy,
       current_policy,
       prev_end      AS predecessor_end_date,
       current_start AS current_start_date
FROM ranked
WHERE rn = 1;

[User] Only include those where the gap between predecessor end_date and current start_date is less than 7 days.

[Assistant]
WITH ranked AS (
  SELECT p2.customer_id,
         p2.policy_number          AS current_policy,
         p2.start_date             AS current_start,
         p1.policy_number          AS prev_policy,
         p1.end_date               AS prev_end,
         ROW_NUMBER() OVER (
           PARTITION BY p2.customer_id, p2.policy_number
           ORDER BY p1.end_date DESC
         )                       AS rn
  FROM insurance.policies p2
  JOIN insurance.policies p1
    ON p1.customer_id = p2.customer_id
   AND p1.end_date < p2.start_date
)
SELECT customer_id,
       prev_policy    AS predecessor_policy,
       current_policy,
       prev_end       AS predecessor_end_date,
       current_start  AS current_start_date
FROM ranked
WHERE rn = 1
  AND (current_start - prev_end) < INTERVAL '7 days';

[User] Also filter to include only customers whose customer_id starts with 'CUST'.

[Assistant]
WITH ranked AS (
  SELECT p2.customer_id,
         p2.policy_number          AS current_policy,
         p2.start_date             AS current_start,
         p1.policy_number          AS prev_policy,
         p1.end_date               AS prev_end,
         ROW_NUMBER() OVER (
           PARTITION BY p2.customer_id, p2.policy_number
           ORDER BY p1.end_date DESC
         )                       AS rn
  FROM insurance.policies p2
  JOIN insurance.policies p1
    ON p1.customer_id = p2.customer_id
   AND p1.end_date < p2.start_date
)
SELECT customer_id,
       prev_policy    AS predecessor_policy,
       current_policy,
       prev_end       AS predecessor_end_date,
       current_start  AS current_start_date
FROM ranked
WHERE rn = 1
  AND (current_start - prev_end) < INTERVAL '7 days'
  AND customer_id LIKE 'CUST%';

[User] Finally, order the results by customer_id and current_start_date descending, limit to 10 rows.

[Assistant]
WITH ranked AS (
  SELECT p2.customer_id,
         p2.policy_number          AS current_policy,
         p2.start_date             AS current_start,
         p1.policy_number          AS prev_policy,
         p1.end_date               AS prev_end,
         ROW_NUMBER() OVER (
           PARTITION BY p2.customer_id, p2.policy_number
           ORDER BY p1.end_date DESC
         )                       AS rn
  FROM insurance.policies p2
  JOIN insurance.policies p1
    ON p1.customer_id = p2.customer_id
   AND p1.end_date < p2.start_date
)
SELECT customer_id,
       prev_policy    AS predecessor_policy,
       current_policy,
       prev_end       AS predecessor_end_date,
       current_start  AS current_start_date
FROM ranked
WHERE rn = 1
  AND (current_start - prev_end) < INTERVAL '7 days'
  AND customer_id LIKE 'CUST%'
ORDER BY customer_id, current_start DESC
LIMIT 10;

[User] Show the agent_id and the total number of policies managed by each agent, but only include agents with at least 5 policies.

[Assistant] SELECT agent_id, COUNT(*) AS policy_count FROM insurance.policies GROUP BY agent_id HAVING COUNT(*) >= 5;

[User] For those agents, can you also show the total combined premium_amount across all their policies, labeled as total_premium?

[Assistant] SELECT agent_id, COUNT(*) AS policy_count, SUM(premium_amount) AS total_premium FROM insurance.policies GROUP BY agent_id HAVING COUNT(*) >= 5;

[User] For policies issued in the current year, show me the total premium_amount and the average deductible grouped by policy status.

[Assistant]
SELECT status,
       SUM(premium_amount) AS total_premium,
       AVG(deductible)     AS average_deductible
FROM insurance.policies
WHERE EXTRACT(YEAR FROM issued_at) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY status;

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

[Assistant] SELECT policy_id, product_id, premium_amount FROM insurance.policies WHERE end_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND CURRENT_DATE AND status = 'expired';

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

[Assistant] SELECT policy_id, product_id, premium_amount, deductible FROM insurance.policies WHERE end_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND CURRENT_DATE AND status = 'expired' AND deductible >= 1000;

[User] List pairs of policies for the same customer where one policy starts exactly one day after another policy ends. Return customer_id, the earlier policy_number, the later policy_number, earlier end_date, and later start_date.

[Assistant]
SELECT p1.customer_id,
       p1.policy_number AS earlier_policy,
       p2.policy_number AS later_policy,
       p1.end_date,
       p2.start_date
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p2.start_date = p1.end_date + INTERVAL '1 day';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.securities ( security_id text PRIMARY KEY, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )

[User] I want to list each security alongside another security issued by the same issuer.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS other_security_id, b.ticker_symbol AS other_ticker, a.issuer_name
FROM financial_services.securities a
JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.security_id <> b.security_id;

[User] Only include cases where the issuer has issued more than one security.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS other_security_id, b.ticker_symbol AS other_ticker, a.issuer_name
FROM financial_services.securities a
JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.security_id <> b.security_id
WHERE a.issuer_name IN (
  SELECT issuer_name
  FROM financial_services.securities
  GROUP BY issuer_name
  HAVING COUNT(*) > 1
);

[User] Sort the result by issuer_name, then by a.ticker_symbol.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS other_security_id, b.ticker_symbol AS other_ticker, a.issuer_name
FROM financial_services.securities a
JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.security_id <> b.security_id
WHERE a.issuer_name IN (
  SELECT issuer_name
  FROM financial_services.securities
  GROUP BY issuer_name
  HAVING COUNT(*) > 1
)
ORDER BY a.issuer_name, a.ticker_symbol;

[User] What is the count of securities for each security_type in the 'Technology' sector?

[Assistant] SELECT security_type, COUNT(*) as count FROM financial_services.securities WHERE sector = 'Technology' GROUP BY security_type;

[User] Can you provide a summary of how many securities exist for each combination of exchange and sector?

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
GROUP BY exchange, sector;

[User] Please exclude any records where sector is NULL.

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
WHERE sector IS NOT NULL
GROUP BY exchange, sector;

[User] Finally, sort the output by total_count in descending order.

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
WHERE sector IS NOT NULL
GROUP BY exchange, sector
ORDER BY total_count DESC;

[User] List all securities (security_id, ticker_symbol, security_name) that have a currency of 'EUR' and were last updated within the last 30 days, along with their exchange and sector information.

[Assistant] SELECT security_id, ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE currency = 'EUR' AND last_updated >= CURRENT_DATE - INTERVAL '30 days';

[User] List all securities issued by 'Morgan Stanley' along with their ticker_symbol, security_name, and exchange. Then also show the sector for each.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley';

[User] Only include those securities that are traded on the NASDAQ exchange.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley' AND exchange = 'NASDAQ';

[User] Add another filter: the security_type must be 'Equity'.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley' AND exchange = 'NASDAQ' AND security_type = 'Equity';

[User] Finally, sort the results by ticker_symbol in ascending order.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley' AND exchange = 'NASDAQ' AND security_type = 'Equity' ORDER BY ticker_symbol ASC;

[User] I’d like to find all pairs of securities that belong to the same sector.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector
WHERE a.security_id < b.security_id;

[User] Actually, only include pairs where the two securities are listed on different exchanges.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange;

[User] Also, I want the results sorted by sector, then by exchange_a.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange
ORDER BY a.sector, a.exchange;

[User] One more thing: include both exchanges in the ORDER BY so that within each sector it’s sorted by exchange_a then exchange_b.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange
ORDER BY a.sector, a.exchange, b.exchange;

[User] Show me the count of securities and the average length of their names for each security_type.

[Assistant] SELECT security_type, COUNT(*) AS securities_count, AVG(LENGTH(security_name)) AS avg_name_length FROM financial_services.securities GROUP BY security_type;

[User] Only include security types that have more than 5 securities.

[Assistant] SELECT security_type, COUNT(*) AS securities_count, AVG(LENGTH(security_name)) AS avg_name_length FROM financial_services.securities GROUP BY security_type HAVING COUNT(*) > 5;

[User] Sort the results by avg_name_length descending.

[Assistant] SELECT security_type, COUNT(*) AS securities_count, AVG(LENGTH(security_name)) AS avg_name_length FROM financial_services.securities GROUP BY security_type HAVING COUNT(*) > 5 ORDER BY avg_name_length DESC;

[User] Find all pairs of securities that are issued by the same issuer but listed on different exchanges.

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

[User] Also include the currency for both securities in the result.

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

[User] Filter the pairs to only include issuers in the 'Financials' sector.

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

[User] Finally, sort the output by issuer_name ascending and symbol_a ascending.

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

[User] For each security, find any other security within the same sector that has a later last_updated timestamp. Return a.ticker_symbol, b.ticker_symbol, and b.last_updated.

[Assistant] SELECT a.ticker_symbol AS symbol_a, b.ticker_symbol AS symbol_b, b.last_updated AS later_update FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND b.last_updated > a.last_updated AND a.security_id <> b.security_id;

[User] Exclude cases where b.last_updated is more than 30 days after a.last_updated.

[Assistant] SELECT a.ticker_symbol AS symbol_a, b.ticker_symbol AS symbol_b, b.last_updated AS later_update FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND b.last_updated > a.last_updated AND a.security_id <> b.security_id AND b.last_updated <= a.last_updated + INTERVAL '30 days';

[User] Sort the result by symbol_a then by later_update in descending order.

[Assistant] SELECT a.ticker_symbol AS symbol_a, b.ticker_symbol AS symbol_b, b.last_updated AS later_update FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND b.last_updated > a.last_updated AND a.security_id <> b.security_id AND b.last_updated <= a.last_updated + INTERVAL '30 days' ORDER BY a.ticker_symbol ASC, later_update DESC;

[User] List pairs of securities that belong to the same sector but have different currencies.

[Assistant] SELECT a.sector, a.ticker_symbol AS symbol_a, a.currency AS currency_a, b.ticker_symbol AS symbol_b, b.currency AS currency_b FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND a.currency <> b.currency;

[User] Filter the pairs to only include sector = 'Healthcare'.

[Assistant] SELECT a.sector, a.ticker_symbol AS symbol_a, a.currency AS currency_a, b.ticker_symbol AS symbol_b, b.currency AS currency_b FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND a.currency <> b.currency WHERE a.sector = 'Healthcare';

[User] Ensure uniqueness by only showing symbol_a < symbol_b.

[Assistant] SELECT a.sector, a.ticker_symbol AS symbol_a, a.currency AS currency_a, b.ticker_symbol AS symbol_b, b.currency AS currency_b FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND a.currency <> b.currency AND a.ticker_symbol < b.ticker_symbol WHERE a.sector = 'Healthcare';