System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)

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

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

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

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

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

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

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

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

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

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

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

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

[User] How many UTXOs have the 'spent' flag set to false?

[Assistant]
SELECT COUNT(*) AS unspent_utxo_count
FROM trading_platform.utxos
WHERE spent = false;

[User] Show all DApps that have metadata linked to an asset with a key of 'category', including the DApp name, URL, and the associated asset_id.

[Assistant]
SELECT d.name, d.url, m.asset_id
FROM trading_platform.dapps d
JOIN trading_platform.metadata m ON d.dapp_id = m.asset_id
WHERE m.key = 'category';

[User] Instead, list the DApp name, URL, and also include the metadata value as 'category' in the result.

[Assistant]
SELECT d.name, d.url, m.value AS category
FROM trading_platform.dapps d
JOIN trading_platform.metadata m ON d.dapp_id = m.asset_id
WHERE m.key = 'category';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] Find the latest three posts with their content and posting users' full names.

[Assistant]
SELECT p.content, u.full_name, p.created_at
FROM social_media.posts p
JOIN social_media.users u ON p.user_id = u.user_id
ORDER BY p.created_at DESC
LIMIT 3;

[User] List all comments on a given post along with the commenter’s username and the comment time.

[Assistant]
SELECT c.comment_id, c.content, u.username, c.created_at
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
WHERE c.post_id = '<POST_ID_PLACEHOLDER>';

[User] Please also indicate if the comment is a reply by showing the parent_comment_id as well.

[Assistant]
SELECT c.comment_id, c.content, u.username, c.created_at, c.parent_comment_id
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
WHERE c.post_id = '<POST_ID_PLACEHOLDER>';

[User] Filter to only show the top-level comments (those without a parent_comment_id).

[Assistant]
SELECT c.comment_id, c.content, u.username, c.created_at, c.parent_comment_id
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
WHERE c.post_id = '<POST_ID_PLACEHOLDER>'
  AND c.parent_comment_id IS NULL;

[User] List all hashtags and for each, show how many different users have created posts using that hashtag.

[Assistant]
SELECT ph.hashtag_id, COUNT(DISTINCT p.user_id) AS unique_user_count
FROM social_media.post_hashtags ph
JOIN social_media.posts p ON ph.post_id = p.post_id
GROUP BY ph.hashtag_id;

[User] Only include hashtags used by at least 3 users.

[Assistant]
SELECT ph.hashtag_id, COUNT(DISTINCT p.user_id) AS unique_user_count
FROM social_media.post_hashtags ph
JOIN social_media.posts p ON ph.post_id = p.post_id
GROUP BY ph.hashtag_id
HAVING COUNT(DISTINCT p.user_id) >= 3;

[User] Show the number of followers for each user who is following others, listing their user_id and follower count.

[Assistant]
SELECT following_user_id AS user_id, COUNT(follower_user_id) AS follower_count
FROM social_media.follows
GROUP BY following_user_id;

[User] List group conversation names and the number of messages sent in each conversation after January 1, 2023.

[Assistant] SELECT c.group_name, COUNT(m.message_id) FROM social_media.conversations c JOIN social_media.messages m ON c.conversation_id = m.conversation_id WHERE c.is_group_chat = true AND m.sent_at >= '2023-01-01' GROUP BY c.conversation_id, c.group_name;

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

[Assistant] SELECT c.group_name, COUNT(m.message_id) FROM social_media.conversations c JOIN social_media.messages m ON c.conversation_id = m.conversation_id WHERE c.is_group_chat = true AND m.sent_at >= '2023-01-01' GROUP BY c.conversation_id, c.group_name HAVING COUNT(m.message_id) > 100;

[User] How many unique conversations have messages?

[Assistant] SELECT COUNT(DISTINCT conversation_id) FROM social_media.messages;


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.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )

[User] Which services have 'Eligibility' mentioned in their eligibility_criteria field?

[Assistant]
SELECT service_name, eligibility_criteria
FROM government_services.services
WHERE eligibility_criteria ILIKE '%Eligibility%';

[User] Show the IDs and registration dates of all verified citizens who could be eligible for at least one active service. Display the citizen ID and registration date.

[Assistant]
SELECT DISTINCT c.citizen_id, c.registration_date
FROM government_services.citizens c
JOIN government_services.services s ON s.is_active = true
WHERE c.is_verified = true;

[User] Show the full names and contact emails of all citizens who have applied for services with a standard fee greater than 100.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.services s ON c.citizen_id IS NOT NULL -- Replace with actual application linking table if exists
WHERE s.standard_fee > 100;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.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.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] List all services along with the count of service orders for each service and the corresponding property name.

[Assistant]
SELECT s.service_id, s.service_name, p.property_name, COUNT(so.order_id) AS order_count
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
LEFT JOIN hospitality_technology.service_orders so ON so.service_id = s.service_id
GROUP BY s.service_id, s.service_name, p.property_name;

[User] Can you filter to only show services with at least 2 orders and order the result by order_count descending?

[Assistant]
SELECT s.service_id, s.service_name, p.property_name, COUNT(so.order_id) AS order_count
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
LEFT JOIN hospitality_technology.service_orders so ON so.service_id = s.service_id
GROUP BY s.service_id, s.service_name, p.property_name
HAVING COUNT(so.order_id) >= 2
ORDER BY order_count DESC;

[User] I also want the average total_price for each service included in the results.

[Assistant]
SELECT s.service_id, s.service_name, p.property_name, COUNT(so.order_id) AS order_count, AVG(so.total_price) AS avg_total_price
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
LEFT JOIN hospitality_technology.service_orders so ON so.service_id = s.service_id
GROUP BY s.service_id, s.service_name, p.property_name
HAVING COUNT(so.order_id) >= 2
ORDER BY order_count DESC;

[User] List each property along with the total revenue generated from all delivered service orders, including the property name and total revenue.

[Assistant]
SELECT p.property_id, p.property_name, SUM(so.total_price) AS total_revenue
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON s.property_id = p.property_id
JOIN hospitality_technology.service_orders so ON so.service_id = s.service_id
WHERE so.status = 'delivered'
GROUP BY p.property_id, p.property_name;

[User] List the full name (first name and last name) and position of all staff members working at properties located in 'California'. Include the name of the property they work at.

[Assistant] SELECT T1.first_name, T1.last_name, T1.position, T2.property_name FROM hospitality_technology.staff AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T2.state_province = 'California'

[User] Show the reservation ID, property name, and room type name for all reservations with a status of 'Confirmed'.

[Assistant] SELECT T1.reservation_id, T2.property_name, T3.type_name FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.status = 'Confirmed'

[User] Actually, only show reservations from properties located in 'Florida' and sort the results by the check-in date.

[Assistant] SELECT T1.reservation_id, T2.property_name, T3.type_name FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.status = 'Confirmed' AND T2.state_province = 'Florida' ORDER BY T1.check_in_date

[User] List all service orders along with the quantity, unit price, and total price for each order. Filter for orders placed on or after the start of the year 2023.

[Assistant] SELECT order_id, quantity, unit_price, total_price FROM hospitality_technology.service_orders WHERE order_timestamp >= '2023-01-01 00:00:00'

[User] Get each property's name and the number of distinct service categories it offers.

[Assistant]
SELECT p.property_name,
       COUNT(DISTINCT s.category) AS category_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.services s
  ON p.property_id = s.property_id
GROUP BY p.property_name;

[User] Now only include properties that offer more than 2 categories.

[Assistant]
SELECT p.property_name,
       COUNT(DISTINCT s.category) AS category_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.services s
  ON p.property_id = s.property_id
GROUP BY p.property_name
HAVING COUNT(DISTINCT s.category) > 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 trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text PRIMARY KEY, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] How many unread notifications does each user have?

[Assistant]
SELECT user_id,
       COUNT(*) AS unread_notifications
FROM trading_platform.notifications
WHERE read_at IS NULL
GROUP BY user_id;

[User] List each user's username, email, and the total count of log entries they have recorded.

[Assistant] SELECT T1.username, T1.email, count(T2.log_id) FROM users AS T1 LEFT JOIN logs AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username, T1.email

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

[Assistant] SELECT T1.username, T1.email, count(T2.log_id), max(T2.logged_at) FROM users AS T1 LEFT JOIN logs AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username, T1.email

[User] Show each user's username and the total number of notifications they have received.

[Assistant] SELECT T1.username, count(T2.notification_id) FROM users AS T1 LEFT JOIN notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username

[User] Filter the results to only include users who have received notifications.

[Assistant] SELECT T1.username, count(T2.notification_id) FROM users AS T1 JOIN notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username

[User] Only show users who have received notifications AND have at least one log entry.

[Assistant] SELECT T1.username, count(distinct T2.notification_id), count(distinct T3.log_id) FROM users AS T1 JOIN notifications AS T2 ON T1.user_id = T2.user_id JOIN logs AS T3 ON T1.user_id = T3.user_id GROUP BY T1.user_id, T1.username

[User] The previous query excluded users who have notifications but no logs, or logs but no notifications. Please include all users who have either received notifications OR have logged an action. Show their username, total notification count (0 if none), and total log count (0 if none).

[Assistant] SELECT T1.username, count(distinct T2.notification_id), count(distinct T3.log_id) FROM users AS T1 LEFT JOIN notifications AS T2 ON T1.user_id = T2.user_id LEFT JOIN logs AS T3 ON T1.user_id = T3.user_id GROUP BY T1.user_id, T1.username

[User] Provide a list of order_id and notification_id for all orders and notifications that occurred on the same day for each user.

[Assistant]
SELECT o.order_id,
       n.notification_id
FROM trading_platform.orders o
JOIN trading_platform.notifications n
  ON o.user_id = n.user_id
  AND DATE(o.created_at) = DATE(n.sent_at);

[User] Now refine it to include only notifications that have been read and orders with status 'completed'.

[Assistant]
SELECT o.order_id,
       n.notification_id
FROM trading_platform.orders o
JOIN trading_platform.notifications n
  ON o.user_id = n.user_id
  AND DATE(o.created_at) = DATE(n.sent_at)
WHERE o.status = 'completed'
  AND n.read_at IS NOT NULL;

[User] Include the order's quantity and notification message in the result, and sort by n.read_at descending.

[Assistant]
SELECT o.order_id,
       o.quantity,
       n.notification_id,
       n.message,
       n.read_at
FROM trading_platform.orders o
JOIN trading_platform.notifications n
  ON o.user_id = n.user_id
  AND DATE(o.created_at) = DATE(n.sent_at)
WHERE o.status = 'completed'
  AND n.read_at IS NOT NULL
ORDER BY n.read_at DESC;

[User] Limit the output to the top 5 records.

[Assistant]
SELECT o.order_id,
       o.quantity,
       n.notification_id,
       n.message,
       n.read_at
FROM trading_platform.orders o
JOIN trading_platform.notifications n
  ON o.user_id = n.user_id
  AND DATE(o.created_at) = DATE(n.sent_at)
WHERE o.status = 'completed'
  AND n.read_at IS NOT NULL
ORDER BY n.read_at DESC
LIMIT 5;


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

[User] Show the user_id, username, and email for users who registered at the same timestamp as another user.

[Assistant] SELECT u1.user_id, u1.username, u1.email FROM web3.users u1 JOIN web3.users u2 ON u1.created_at = u2.created_at AND u1.user_id <> u2.user_id;

[User] Show all users who registered before 2023-01-01, along with their usernames and registration dates.

[Assistant]
SELECT user_id, username, created_at
FROM web3.users
WHERE created_at < '2023-01-01';

[User] Can you additionally include their email addresses in the result?

[Assistant]
SELECT user_id, username, email, created_at
FROM web3.users
WHERE created_at < '2023-01-01';

[User] Show me all users whose username contains 'dev', including their user_id and email address.

[Assistant] SELECT user_id, username, email FROM web3.users WHERE username ILIKE '%dev%';

[User] Can you also show the registration date for each of those users?

[Assistant] SELECT user_id, username, email, created_at FROM web3.users WHERE username ILIKE '%dev%';

[User] List all users whose usernames start with 'alice' and show their creation dates.

[Assistant] SELECT username, created_at FROM web3.users WHERE username LIKE 'alice%';

[User] There's a typo in your SQL, it should be 'alice%' not 'alice%'. Also, sort the results by created_at in ascending order.

[Assistant] SELECT username, created_at FROM web3.users WHERE username LIKE 'alice%' ORDER BY created_at ASC;

[User] Actually, I need to see their email addresses too.

[Assistant] SELECT username, email, created_at FROM web3.users WHERE username LIKE 'alice%' ORDER BY created_at ASC;

[User] Now filter to only show users created in 2023.

[Assistant] SELECT username, email, created_at FROM web3.users WHERE username LIKE 'alice%' AND created_at BETWEEN '2023-01-01' AND '2023-12-31' ORDER BY created_at ASC;

[User] Find pairs of users who registered on the same weekday but in different years. List the user ID and registration date for both users, and the weekday name.

[Assistant] SELECT u1.user_id, u1.created_at AS user1_created_at, u2.user_id, u2.created_at AS user2_created_at, TO_CHAR(u1.created_at, 'Day') AS registration_weekday FROM web3.users u1 JOIN web3.users u2 ON TO_CHAR(u1.created_at, 'Day') = TO_CHAR(u2.created_at, 'Day') AND EXTRACT(YEAR FROM u1.created_at) <> EXTRACT(YEAR FROM u2.created_at) AND u1.user_id < u2.user_id ORDER BY TO_CHAR(u1.created_at, 'D'), u1.created_at;

[User] Show the usernames and registration dates for all users whose email ends with '@gmail.com'.

[Assistant] SELECT username, created_at FROM web3.users WHERE email LIKE '%@gmail.com';

[User] Actually, can you also include how many such users there are in total in the result?

[Assistant] SELECT username, created_at, COUNT(*) OVER() AS total_gmail_users FROM web3.users WHERE email LIKE '%@gmail.com';


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) )

[User] List all contracts with status 'active' and include their deployment timestamp and network ID.

[Assistant] SELECT address, deployed_at, network_id FROM web3.contracts WHERE status = 'active';

[User] Actually, I need to see only contracts deployed in the last 30 days.

[Assistant] SELECT address, deployed_at, network_id FROM web3.contracts WHERE status = 'active' AND deployed_at >= NOW() - INTERVAL '30 days';

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

[Assistant] SELECT address, deployed_at, network_id FROM web3.contracts WHERE status = 'active' AND deployed_at >= NOW() - INTERVAL '30 days' ORDER BY deployed_at DESC;

[User] Now filter to only show contracts on the 'polygon' network.

[Assistant] SELECT address, deployed_at, network_id FROM web3.contracts WHERE status = 'active' AND deployed_at >= NOW() - INTERVAL '30 days' AND network_id = 'polygon' ORDER BY deployed_at DESC;

[User] Provide a count of contracts for each unique combination of network ID and status.

[Assistant] SELECT network_id, status, COUNT(*) FROM web3.contracts GROUP BY network_id, status;

[User] Now, only show the network IDs from the previous result that have contracts in more than one distinct status.

[Assistant] SELECT network_id FROM web3.contracts GROUP BY network_id HAVING COUNT(DISTINCT status) > 1;

[User] Show all contracts that share the same deployment date, along with their contract IDs and the corresponding deployment date.

[Assistant]
SELECT a.contract_id AS contract_id_1, b.contract_id AS contract_id_2, a.deployed_at::date AS deployment_date
FROM web3.contracts a
JOIN web3.contracts b
  ON a.deployed_at::date = b.deployed_at::date AND a.contract_id < b.contract_id;

[User] Actually, I only want to see such pairs where the contracts were deployed by different deployer addresses.

[Assistant]
SELECT a.contract_id AS contract_id_1, b.contract_id AS contract_id_2, a.deployed_at::date AS deployment_date
FROM web3.contracts a
JOIN web3.contracts b
  ON a.deployed_at::date = b.deployed_at::date
  AND a.contract_id < b.contract_id
  AND a.deployer_address <> b.deployer_address;

[User] List the contract ID, address, and deployer address for all contracts deployed on the 'mainnet' network.

[Assistant] SELECT contract_id, address, deployer_address FROM web3.contracts WHERE network_id = 'mainnet';

[User] Count the number of contracts for each network_id.

[Assistant] SELECT network_id, COUNT(*) FROM web3.contracts GROUP BY network_id;

[User] Now, only show networks with more than 100 contracts.

[Assistant] SELECT network_id, COUNT(*) FROM web3.contracts GROUP BY network_id HAVING COUNT(*) > 100;

[User] Find all pairs of contracts that were deployed on the same network but by different deployer addresses. List the network ID, the addresses of both contracts, and the addresses of their respective deployers.

[Assistant] SELECT c1.network_id, c1.address AS contract1_address, c2.address AS contract2_address, c1.deployer_address AS contract1_deployer, c2.deployer_address AS contract2_deployer FROM web3.contracts c1 JOIN web3.contracts c2 ON c1.network_id = c2.network_id AND c1.deployer_address != c2.deployer_address WHERE c1.contract_id < c2.contract_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.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.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id 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.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
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 trips along with the city name of their origin and the scheduled departure time.

[Assistant]
SELECT t.trip_id, l.name AS origin_city, t.scheduled_departure
FROM transportation.trips t
JOIN transportation.locations l ON t.origin_location_id = l.location_id;

[User] Can you add the destination city name as well?

[Assistant]
SELECT t.trip_id, l1.name AS origin_city, l2.name AS destination_city, t.scheduled_departure
FROM transportation.trips t
JOIN transportation.locations l1 ON t.origin_location_id = l1.location_id
JOIN transportation.locations l2 ON t.destination_location_id = l2.location_id;

[User] Only show trips where the origin city is different from the destination city.

[Assistant]
SELECT t.trip_id, l1.name AS origin_city, l2.name AS destination_city, t.scheduled_departure
FROM transportation.trips t
JOIN transportation.locations l1 ON t.origin_location_id = l1.location_id
JOIN transportation.locations l2 ON t.destination_location_id = l2.location_id
WHERE l1.city <> l2.city;

[User] Instead of city names, show the actual full addresses for both origin and destination.

[Assistant]
SELECT t.trip_id, l1.address_line1 AS origin_address, l2.address_line1 AS destination_address, t.scheduled_departure
FROM transportation.trips t
JOIN transportation.locations l1 ON t.origin_location_id = l1.location_id
JOIN transportation.locations l2 ON t.destination_location_id = l2.location_id
WHERE l1.city <> l2.city;

[User] Show a list of all fuel refueling events for each trip, including the trip ID, fuel type, quantity, total cost, and the name of the refueling location.

[Assistant]
SELECT fl.trip_id, fl.fuel_type, fl.quantity, fl.total_cost, l.name AS location_name
FROM transportation.fuel_logs fl
JOIN transportation.locations l ON fl.location_id = l.location_id;

[User] Retrieve the passenger_id, first_name, last_name, and total number of bookings each passenger has made in 2023, including only those with at least one booking.

[Assistant]
SELECT p.passenger_id, p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2023-01-01' AND b.booking_time < '2024-01-01'
GROUP BY p.passenger_id, p.first_name, p.last_name
HAVING COUNT(b.booking_id) > 0;

[User] Also, include the sum of fares paid by each passenger and order by total_fares descending.

[Assistant]
SELECT p.passenger_id, p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, SUM(b.fare) AS total_fares
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2023-01-01' AND b.booking_time < '2024-01-01'
GROUP BY p.passenger_id, p.first_name, p.last_name
HAVING COUNT(b.booking_id) > 0
ORDER BY total_fares DESC;

[User] For each trip that has associated bookings, show the trip ID, the total number of passengers recorded for the trip, and the total fare collected from all bookings for that trip.

[Assistant] SELECT T1.trip_id, T1.passenger_count, SUM(T2.fare) FROM transportation.trips AS T1 JOIN transportation.bookings AS T2 ON T1.trip_id = T2.trip_id GROUP BY T1.trip_id, T1.passenger_count;

[User] For all trips, show the trip ID, the route number, and the make and model of the vehicle used.

[Assistant]
SELECT t.trip_id, r.route_number, v.make, v.model
FROM transportation.fuel_logs t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
JOIN transportation.routes r ON t.trip_id = r.route_id;

[User] Actually, show only those trips where the vehicle type is 'Bus'.

[Assistant]
SELECT t.trip_id, r.route_number, v.make, v.model
FROM transportation.fuel_logs t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
JOIN transportation.routes r ON t.trip_id = r.route_id
WHERE v.type = 'Bus';

[User] Add the odometer reading from the fuel log and only include trips where this value exceeds 50000.

[Assistant]
SELECT t.trip_id, r.route_number, v.make, v.model, t.odometer_reading
FROM transportation.fuel_logs t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
JOIN transportation.routes r ON t.trip_id = r.route_id
WHERE v.type = 'Bus' AND t.odometer_reading > 50000;

[User] Show the full name and email of each driver and the number of vehicles currently assigned to their depot.

[Assistant]
SELECT d.first_name, d.last_name, d.email, COUNT(v.vehicle_id) AS vehicles_at_depot
FROM transportation.drivers d
JOIN transportation.vehicles v ON d.driver_id = v.vehicle_id
JOIN transportation.locations l ON v.depot_id = l.location_id
GROUP BY d.driver_id, d.first_name, d.last_name, d.email;

[User] I think the join is incorrect—drivers don’t have vehicle_id. Can you instead count all vehicles per depot and show each driver's full name, email, and the count for their assigned depot, assuming drivers and vehicles share depot assignments by depot_id?

[Assistant]
SELECT d.first_name, d.last_name, d.email, COUNT(v.vehicle_id) AS vehicles_at_depot
FROM transportation.drivers d
JOIN transportation.vehicles v ON d.status = 'Active' AND d.driver_id IS NOT NULL AND v.depot_id = (
    SELECT v2.depot_id FROM transportation.vehicles v2 WHERE v2.vehicle_id = v.vehicle_id LIMIT 1
)
GROUP BY d.driver_id, d.first_name, d.last_name, d.email;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL DEFAULT 'USA', phone_number character varying(30), email character varying(128) UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, status character varying(20) NOT NULL DEFAULT 'Active', PRIMARY KEY (customer_id) )
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )

[User] Count the number of premium payments that have a null payment method.

[Assistant]
SELECT COUNT(*) AS null_payment_method_count
FROM insurance.premium_payments
WHERE payment_method IS NULL;

[User] Show me the first name, last name, and policy number for all customers who have filed a claim with an estimated loss over $50,000, along with the agent's full name who sold the policy.

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, a.first_name AS agent_first_name, a.last_name AS agent_last_name
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
JOIN insurance.agents a ON p.agent_id = a.agent_id
WHERE cl.estimated_loss > 50000;

[User] Can you also include the policy's premium amount and status in the results?

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, p.premium_amount, p.status, a.first_name AS agent_first_name, a.last_name AS agent_last_name
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
JOIN insurance.agents a ON p.agent_id = a.agent_id
WHERE cl.estimated_loss > 50000;

[User] Actually, only show those claims where the policy's status is 'Active' and the agent is currently 'Active' as well.

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, p.premium_amount, p.status, a.first_name AS agent_first_name, a.last_name AS agent_last_name
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
JOIN insurance.agents a ON p.agent_id = a.agent_id
WHERE cl.estimated_loss > 50000 AND p.status = 'Active' AND a.status = 'Active';

[User] I want to list all claims with their claim_id, incident_date, and the customer's full name for claims where estimated_loss is above 10000.

[Assistant]
SELECT cl.claim_id, cl.incident_date, c.first_name || ' ' || c.last_name AS customer_name
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
WHERE cl.estimated_loss > 10000;

[User] Actually, I also need the policy_number associated with each claim.

[Assistant]
SELECT cl.claim_id, cl.incident_date, c.first_name || ' ' || c.last_name AS customer_name, p.policy_number
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
WHERE cl.estimated_loss > 10000;

[User] Additionally, only include claims that are still open (status = 'Open') and order by incident_date descending.

[Assistant]
SELECT cl.claim_id, cl.incident_date, c.first_name || ' ' || c.last_name AS customer_name, p.policy_number
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
WHERE cl.estimated_loss > 10000
  AND cl.status = 'Open'
ORDER BY cl.incident_date DESC;

[User] That's good, but limit to the top 10 results.

[Assistant]
SELECT cl.claim_id, cl.incident_date, c.first_name || ' ' || c.last_name AS customer_name, p.policy_number
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
WHERE cl.estimated_loss > 10000
  AND cl.status = 'Open'
ORDER BY cl.incident_date DESC
LIMIT 10;

[User] Show me claim_id, incident_date, policy_number, and customer full name for all claims where settlement_amount is null.

[Assistant]
SELECT c.claim_id, c.incident_date, p.policy_number, cu.first_name || ' ' || cu.last_name AS customer_full_name
FROM insurance.claims c
JOIN insurance.policies p ON c.policy_id = p.policy_id
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
WHERE c.settlement_amount IS NULL;

[User] The query should only include claims reported in 2024.

[Assistant]
SELECT c.claim_id, c.incident_date, p.policy_number, cu.first_name || ' ' || cu.last_name AS customer_full_name
FROM insurance.claims c
JOIN insurance.policies p ON c.policy_id = p.policy_id
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
WHERE c.settlement_amount IS NULL
  AND c.incident_date >= '2024-01-01'
  AND c.incident_date < '2025-01-01';

[User] Also order the results by incident_date descending and limit the output to the top 10.

[Assistant]
SELECT c.claim_id, c.incident_date, p.policy_number, cu.first_name || ' ' || cu.last_name AS customer_full_name
FROM insurance.claims c
JOIN insurance.policies p ON c.policy_id = p.policy_id
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
WHERE c.settlement_amount IS NULL
  AND c.incident_date >= '2024-01-01'
  AND c.incident_date < '2025-01-01'
ORDER BY c.incident_date DESC
LIMIT 10;

[User] Actually, I need to include the agent_id who sold each policy in the output as well.

[Assistant]
SELECT c.claim_id, c.incident_date, p.policy_number, cu.first_name || ' ' || cu.last_name AS customer_full_name, p.agent_id
FROM insurance.claims c
JOIN insurance.policies p ON c.policy_id = p.policy_id
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
WHERE c.settlement_amount IS NULL
  AND c.incident_date >= '2024-01-01'
  AND c.incident_date < '2025-01-01'
ORDER BY c.incident_date DESC
LIMIT 10;

[User] Show all claim documents (document_id, file_name, and document_type) for claims that have a settlement amount greater than 5000.

[Assistant]
SELECT cd.document_id, cd.file_name, cd.document_type
FROM insurance.claim_documents cd
JOIN insurance.claims c ON cd.claim_id = c.claim_id
WHERE c.settlement_amount > 5000;

[User] Can you also add the claim_id and only include documents with a file size over 1MB (1048576 bytes)?

[Assistant]
SELECT cd.document_id, cd.claim_id, cd.file_name, cd.document_type
FROM insurance.claim_documents cd
JOIN insurance.claims c ON cd.claim_id = c.claim_id
WHERE c.settlement_amount > 5000 AND cd.file_size_bytes > 1048576;

[User] Instead, just show the claim_id and how many such documents meet these requirements for each claim.

[Assistant]
SELECT cd.claim_id, COUNT(*) AS document_count
FROM insurance.claim_documents cd
JOIN insurance.claims c ON cd.claim_id = c.claim_id
WHERE c.settlement_amount > 5000 AND cd.file_size_bytes > 1048576
GROUP BY cd.claim_id;

[User] Now, please order the results by document_count descending and limit to the top 5 claims.

[Assistant]
SELECT cd.claim_id, COUNT(*) AS document_count
FROM insurance.claim_documents cd
JOIN insurance.claims c ON cd.claim_id = c.claim_id
WHERE c.settlement_amount > 5000 AND cd.file_size_bytes > 1048576
GROUP BY cd.claim_id
ORDER BY document_count DESC
LIMIT 5;

[User] List the policy number, premium amount, and the product name for each policy, but only for policies where the associated insurance product is active and has a base premium greater than 1200.

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


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.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )

[User] Find all pairs of tokens that have the same contract_address but different token_symbols. Show both token_ids, each token's symbol, and the shared contract_address.

[Assistant] SELECT t1.token_id AS token_id_1, t2.token_id AS token_id_2, t1.token_symbol AS symbol_1, t2.token_symbol AS symbol_2, t1.contract_address FROM web3.tokens t1 JOIN web3.tokens t2 ON t1.contract_address = t2.contract_address AND t1.token_id < t2.token_id AND t1.token_symbol <> t2.token_symbol;

[User] List all tokens along with the contract addresses for symbols that appear more than once.

[Assistant]
SELECT t.token_id, t.token_symbol, t.contract_address
FROM web3.tokens t
JOIN (
  SELECT token_symbol
  FROM web3.tokens
  GROUP BY token_symbol
  HAVING COUNT(*) > 1
) dup ON t.token_symbol = dup.token_symbol;

[User] What is the average total_supply for each decimals value?

[Assistant]
SELECT decimals, AVG(total_supply) AS avg_supply
FROM web3.tokens
GROUP BY decimals;

[User] Actually, I only want to include tokens whose token_symbol starts with 'A'.

[Assistant]
SELECT decimals, AVG(total_supply) AS avg_supply
FROM web3.tokens
WHERE token_symbol LIKE 'A%'
GROUP BY decimals;

[User] Show all tokens where the total_supply is less than 10000, listing the token_id, token_symbol, and decimals.

[Assistant] SELECT token_id, token_symbol, decimals FROM web3.tokens WHERE total_supply < 10000;

[User] Actually, please also include the token_name in the result and order the results by total_supply ascending.

[Assistant] SELECT token_id, token_symbol, token_name, decimals FROM web3.tokens WHERE total_supply < 10000 ORDER BY total_supply ASC;

[User] Show me the token names and their contract addresses where the total supply is greater than 1 million, sorted by total supply in descending order.

[Assistant] SELECT token_name, contract_address FROM web3.tokens WHERE total_supply > 1000000 ORDER BY total_supply DESC;

[User] List all pairs of tokens (show token_id for both) that share the same contract address, excluding pairs where the token_id is the same.

[Assistant] SELECT t1.token_id AS token_id1, t2.token_id AS token_id2, t1.contract_address FROM web3.tokens AS t1 JOIN web3.tokens AS t2 ON t1.contract_address = t2.contract_address WHERE t1.token_id < t2.token_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 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 )

[User] Which staff members have terminated employment? Show their names, hire and termination dates, and the property ID.

[Assistant]
SELECT staff_id, first_name, last_name, hire_date, termination_date, property_id
FROM hospitality_technology.staff
WHERE termination_date IS NOT NULL;

[User] Only include those who worked at properties with an access_level of at least 4.

[Assistant]
SELECT staff_id, first_name, last_name, hire_date, termination_date, property_id
FROM hospitality_technology.staff
WHERE termination_date IS NOT NULL AND access_level >= 4;

[User] Actually, show only the staff whose employment lasted less than 2 years.

[Assistant]
SELECT staff_id, first_name, last_name, hire_date, termination_date, property_id
FROM hospitality_technology.staff
WHERE termination_date IS NOT NULL
  AND access_level >= 4
  AND (termination_date - hire_date) < INTERVAL '2 years';


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 smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )

[User] For each chain, show the total token_amount and usd_value for selling transactions (type=2).

[Assistant]
SELECT chain, SUM(token_amount) AS total_sold_amount, SUM(usd_value) AS total_sold_usd_value
FROM smart_money_token_inflow
WHERE type = 2
GROUP BY chain;

[User] Can you break down these results further by narrative as well?

[Assistant]
SELECT chain, narrative, SUM(token_amount) AS total_sold_amount, SUM(usd_value) AS total_sold_usd_value
FROM smart_money_token_inflow
WHERE type = 2
GROUP BY chain, narrative;

[User] Which token symbols have the highest number of addresses buying them on the Ethereum chain? Show the top 3 symbols, their total address_amount, and narrative.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
ORDER BY total_buying_addresses DESC
LIMIT 3;

[User] I got incorrect results. I only want results where the summed address_amount is at least 10.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
HAVING SUM(address_amount) >= 10
ORDER BY total_buying_addresses DESC
LIMIT 3;

[User] Please add the total usd_value spent on buying each of these tokens.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses, SUM(usd_value) AS total_buy_usd_value
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
HAVING SUM(address_amount) >= 10
ORDER BY total_buying_addresses DESC
LIMIT 3;

[User] Also include the average price (avg_price) for each token.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses, SUM(usd_value) AS total_buy_usd_value, AVG(avg_price) AS average_price
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
HAVING SUM(address_amount) >= 10
ORDER BY total_buying_addresses DESC
LIMIT 3;

[User] How many distinct tokens did smart money buy on the 'BSC' chain in 2023?

[Assistant]
SELECT COUNT(DISTINCT token_address) AS distinct_tokens_bought
FROM smart_money_token_inflow
WHERE type = 1
  AND chain = 'BSC'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') >= '2023-01-01'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') <= '2023-12-31';

[User] Can you break this down by narrative and show the count per narrative?

[Assistant]
SELECT narrative, COUNT(DISTINCT token_address) AS distinct_tokens_bought
FROM smart_money_token_inflow
WHERE type = 1
  AND chain = 'BSC'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') >= '2023-01-01'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') <= '2023-12-31'
GROUP BY narrative
ORDER BY distinct_tokens_bought DESC;

[User] List all token symbols related to the 'Gaming' narrative that had a net positive token inflow.

[Assistant] SELECT token_symbol FROM smart_money_token_inflow WHERE narrative = 'Gaming' AND usd_value > 0 GROUP BY token_symbol;

[User] Which narrative had the highest total USD token inflow during Q1 of 2024, and which chain did these inflows primarily occur on?

[Assistant] SELECT narrative, chain, SUM(usd_value) AS total_inflow FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(YEAR FROM CURRENT_DATE) = 2024 AND EXTRACT(MONTH FROM CURRENT_DATE) BETWEEN 1 AND 3 GROUP BY narrative, chain ORDER BY total_inflow DESC LIMIT 1;

[User] Could you modify the query to show the top 3 narratives by total inflow, along with their corresponding chains?

[Assistant] SELECT narrative, chain, SUM(usd_value) AS total_inflow FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(YEAR FROM CURRENT_DATE) = 2024 AND EXTRACT(MONTH FROM CURRENT_DATE) BETWEEN 1 AND 3 GROUP BY narrative, chain ORDER BY total_inflow DESC LIMIT 3;

[User] What are the top 3 narratives by average USD purchase value per address (for buy transactions) across all chains?

[Assistant]
SELECT narrative, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative
ORDER BY avg_usd_per_address DESC
LIMIT 3;

[User] Also include the chain in the output and compute results per narrative and chain.

[Assistant]
SELECT narrative, chain, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative, chain
ORDER BY avg_usd_per_address DESC
LIMIT 3;

[User] Only show combinations where the total address_amount is greater than 50.

[Assistant]
SELECT narrative, chain, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address, SUM(address_amount) AS total_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative, chain
HAVING SUM(address_amount) > 50
ORDER BY avg_usd_per_address DESC
LIMIT 3;

[User] Add the total usd_value for each narrative and chain as a column in the result.

[Assistant]
SELECT narrative, chain, SUM(usd_value) AS total_usd_value, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address, SUM(address_amount) AS total_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative, chain
HAVING SUM(address_amount) > 50
ORDER BY avg_usd_per_address DESC
LIMIT 3;


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.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )

[User] Find all applications that were submitted in 2023 but received a decision ('Approved' or 'Rejected') in 2024. List the application ID, submitted date, decision date, and status.

[Assistant] SELECT application_id, submitted_at, decision_date, status FROM government_services.applications WHERE submitted_at BETWEEN '2023-01-01 00:00:00' AND '2023-12-31 23:59:59' AND status IN ('Approved', 'Rejected') AND decision_date BETWEEN '2024-01-01' AND '2024-12-31';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )

[User] List all prescriptions with the corresponding patient's emergency contact name and phone number. Show prescription ID, patient full name, emergency contact name, and emergency contact phone.

[Assistant]
SELECT pr.prescription_id, p.first_name, p.last_name, p.emergency_contact_name, p.emergency_contact_phone
FROM healthcare.prescriptions pr
JOIN healthcare.patients p ON pr.patient_id = p.patient_id;

[User] Only include prescriptions where the emergency contact phone is not null and sort the results by the patient's last name.

[Assistant]
SELECT pr.prescription_id, p.first_name, p.last_name, p.emergency_contact_name, p.emergency_contact_phone
FROM healthcare.prescriptions pr
JOIN healthcare.patients p ON pr.patient_id = p.patient_id
WHERE p.emergency_contact_phone IS NOT NULL
ORDER BY p.last_name ASC;

[User] List all patients who have been prescribed medications manufactured by 'AstraZeneca', showing patient ID, first and last name, medication name, and manufacturer.

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

[User] Change the query to only show patients who have received more than one prescription for medications by 'AstraZeneca'. Show the patient ID, full name, manufacturer, and the prescription count.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, m.manufacturer, COUNT(pr.prescription_id) AS prescription_count
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE m.manufacturer = 'AstraZeneca'
GROUP BY p.patient_id, p.first_name, p.last_name, m.manufacturer
HAVING COUNT(pr.prescription_id) > 1;

[User] Can you add the latest prescription date for each patient in the results as well?

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, m.manufacturer, COUNT(pr.prescription_id) AS prescription_count, MAX(pr.prescription_date) AS latest_prescription_date
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE m.manufacturer = 'AstraZeneca'
GROUP BY p.patient_id, p.first_name, p.last_name, m.manufacturer
HAVING COUNT(pr.prescription_id) > 1;

[User] Show all doctors who have issued more than 10 prescriptions. Return doctor ID, first name, last name, and total prescription count.

[Assistant]
SELECT d.doctor_id, d.first_name, d.last_name, COUNT(pr.prescription_id) AS total_prescriptions
FROM healthcare.doctors d
JOIN healthcare.prescriptions pr ON d.doctor_id = pr.doctor_id
GROUP BY d.doctor_id, d.first_name, d.last_name
HAVING COUNT(pr.prescription_id) > 10;

[User] Also, can you include each doctor's phone number in the results?

[Assistant]
SELECT d.doctor_id, d.first_name, d.last_name, d.phone_number, COUNT(pr.prescription_id) AS total_prescriptions
FROM healthcare.doctors d
JOIN healthcare.prescriptions pr ON d.doctor_id = pr.doctor_id
GROUP BY d.doctor_id, d.first_name, d.last_name, d.phone_number
HAVING COUNT(pr.prescription_id) > 10;

[User] List patient_id, first_name, last_name, and date_of_birth for all patients older than 65 years.

[Assistant]
SELECT patient_id, first_name, last_name, date_of_birth
FROM healthcare.patients
WHERE date_of_birth < CURRENT_DATE - INTERVAL '65 years';

[User] Show me the top 5 most recent medical records with a fever recorded. Return record_id, patient_id, record_date, and the temperature value from vitals.

[Assistant]
SELECT record_id,
       patient_id,
       record_date,
       vitals->>'temperature' AS temperature
FROM healthcare.medical_records
WHERE (vitals->>'temperature')::numeric > 38
ORDER BY record_date DESC
LIMIT 5;

[User] Actually, include only records where assessment is not empty.

[Assistant]
SELECT record_id,
       patient_id,
       record_date,
       vitals->>'temperature' AS temperature
FROM healthcare.medical_records
WHERE (vitals->>'temperature')::numeric > 38
  AND assessment IS NOT NULL
  AND assessment <> ''
ORDER BY record_date DESC
LIMIT 5;

[User] List each patient's first and last name along with the insurance plan name they are enrolled in, including only primary policies. Return patient_id, first_name, last_name, and plan_name.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       ip.plan_name
FROM healthcare.patients AS p
JOIN healthcare.patient_insurance AS pi
  ON p.patient_id = pi.patient_id AND pi.is_primary = true
JOIN healthcare.insurance_plans AS ip ON pi.plan_id = ip.plan_id;

[User] Now limit to plans with plan_type 'EPO' and sort by patient last name ascending.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       ip.plan_name
FROM healthcare.patients AS p
JOIN healthcare.patient_insurance AS pi
  ON p.patient_id = pi.patient_id AND pi.is_primary = true
JOIN healthcare.insurance_plans AS ip ON pi.plan_id = ip.plan_id
WHERE ip.plan_type = 'EPO'
ORDER BY p.last_name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_id)
)
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
CREATE TABLE legal_services.law_firms (
    firm_id character varying(64) NOT NULL,  -- unique identifier for the law firm
    firm_name character varying(200) NOT NULL, -- official name of the law firm
    address text NOT NULL, -- primary address of the firm
    phone character varying(32), -- firm's main phone number
    website character varying(255), -- firm's website URL
    founded_date date, -- date the firm was established
    managing_partner_id character varying(64), -- FK to lawyers table (optional)
    PRIMARY KEY (firm_id)
)
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)

[User] Show all law firms with more than one partner assigned. Display the law firm name and the number of partners.

[Assistant]
SELECT lf.firm_name, COUNT(l.lawyer_id) AS partner_count
FROM legal_services.law_firms lf
JOIN legal_services.lawyers l ON lf.firm_id = l.firm_id
WHERE l.is_partner = true
GROUP BY lf.firm_name
HAVING COUNT(l.lawyer_id) > 1;

[User] List the full names and email addresses of all lawyers who have handled at least one appointment for a client from the company 'Innovatech Ltd', along with the company name.

[Assistant]
SELECT DISTINCT l.first_name, l.last_name, l.email, c.company_name
FROM legal_services.appointments a
JOIN legal_services.lawyers l ON a.lawyer_id = l.lawyer_id
JOIN legal_services.clients c ON a.client_id = c.client_id
WHERE c.company_name = 'Innovatech Ltd';

[User] List the names of all clients that are associated with cases led by lawyers specializing in 'Intellectual Property'.

[Assistant]
SELECT DISTINCT c.first_name, c.last_name
FROM legal_services.cases cs
JOIN legal_services.clients c ON cs.client_id = c.client_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
WHERE l.specialization ILIKE '%Intellectual Property%';

[User] Actually, I also want to see the lawyer's full name and their specialization next to each client.

[Assistant]
SELECT DISTINCT c.first_name AS client_first_name, c.last_name AS client_last_name, l.first_name AS lawyer_first_name, l.last_name AS lawyer_last_name, l.specialization
FROM legal_services.cases cs
JOIN legal_services.clients c ON cs.client_id = c.client_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
WHERE l.specialization ILIKE '%Intellectual Property%';

[User] Can you further filter this to only show clients who registered after January 1, 2023?

[Assistant]
SELECT DISTINCT c.first_name AS client_first_name, c.last_name AS client_last_name, l.first_name AS lawyer_first_name, l.last_name AS lawyer_last_name, l.specialization
FROM legal_services.cases cs
JOIN legal_services.clients c ON cs.client_id = c.client_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
WHERE l.specialization ILIKE '%Intellectual Property%'
  AND c.date_registered > '2023-01-01';

[User] List all cases opened between '2024-01-01' and '2024-03-31' along with the client's name and the lead lawyer's email address.

[Assistant]
SELECT cs.case_name, cs.case_number, cl.first_name AS client_first_name, cl.last_name AS client_last_name, lw.email AS lawyer_email
FROM legal_services.cases cs
JOIN legal_services.clients cl ON cs.client_id = cl.client_id
JOIN legal_services.lawyers lw ON cs.lead_lawyer_id = lw.lawyer_id
WHERE cs.date_opened BETWEEN '2024-01-01' AND '2024-03-31';

[User] Actually, also include the case type and sort the results by the client's last name.

[Assistant]
SELECT cs.case_name, cs.case_number, cs.case_type, cl.first_name AS client_first_name, cl.last_name AS client_last_name, lw.email AS lawyer_email
FROM legal_services.cases cs
JOIN legal_services.clients cl ON cs.client_id = cl.client_id
JOIN legal_services.lawyers lw ON cs.lead_lawyer_id = lw.lawyer_id
WHERE cs.date_opened BETWEEN '2024-01-01' AND '2024-03-31'
ORDER BY cl.last_name;

[User] Now, only show cases where the client's status is 'active'.

[Assistant]
SELECT cs.case_name, cs.case_number, cs.case_type, cl.first_name AS client_first_name, cl.last_name AS client_last_name, lw.email AS lawyer_email
FROM legal_services.cases cs
JOIN legal_services.clients cl ON cs.client_id = cl.client_id
JOIN legal_services.lawyers lw ON cs.lead_lawyer_id = lw.lawyer_id
WHERE cs.date_opened BETWEEN '2024-01-01' AND '2024-03-31'
  AND cl.status = 'active'
ORDER BY cl.last_name;

[User] Which clients have not had any appointments scheduled? Please list their first name, last name, and email.

[Assistant]
SELECT c.first_name, c.last_name, c.email
FROM legal_services.clients c
LEFT JOIN legal_services.appointments a ON c.client_id = a.client_id
WHERE a.appointment_id IS NULL;

[User] Show me the full name of all partner lawyers and the total hours they have spent on all time entries.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_hours FROM legal_services.lawyers l JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id WHERE l.is_partner = true GROUP BY l.lawyer_id, l.first_name, l.last_name;

[User] Actually, only include hours logged in the year 2023.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_hours FROM legal_services.lawyers l JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id WHERE l.is_partner = true AND EXTRACT(YEAR FROM te.date_worked) = 2023 GROUP BY l.lawyer_id, l.first_name, l.last_name;

[User] Also, only show partners who logged more than 50 hours in 2023, and order the results by total hours descending.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_hours FROM legal_services.lawyers l JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id WHERE l.is_partner = true AND EXTRACT(YEAR FROM te.date_worked) = 2023 GROUP BY l.lawyer_id, l.first_name, l.last_name HAVING SUM(te.hours_spent) > 50 ORDER BY total_hours 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
// PUT /schedules
{
  "mappings": {
    "properties": {
      "schedule_id": { "type": "keyword" },
      "train_id": { "type": "keyword" }, // References trains index
      "route_id": { "type": "keyword" }, // References routes index
      "departure_datetime": { "type": "date" }, // ISO 8601 format recommended
      "arrival_datetime": { "type": "date" },
      "status": { "type": "keyword" },
      "notes": { "type": "text" }
    }
  }
}
// PUT /passengers
{
  "mappings": {
    "properties": {
      "passenger_id": { "type": "keyword" },
      "first_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 100 } }
      },
      "last_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 100 } }
       },
      "email": { "type": "keyword" }, // Often used for exact matches
      "phone_number": { "type": "keyword" },
      "date_of_birth": { "type": "date", "format": "yyyy-MM-dd" },
      "loyalty_program_id": { "type": "keyword" },
      "created_at": { "type": "date" }
    }
  }
}

[User] 能否帮我查询特定列车行程(schedule_id 为 'sched_001')的详细信息，包括列车出发和到达时间，以及该行程所属路线的ID和相关乘客信息？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001';

[User] 能否将结果限制在状态为‘Scheduled’的行程上，并且只显示乘客的姓名和电子邮件？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001' AND s.status = 'Scheduled';

[User] 能否再加入行程的备注信息，并按出发时间降序排列？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, s.notes, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001' AND s.status = 'Scheduled'
ORDER BY s.departure_datetime DESC;

[User] 如果没有关联的乘客信息，能否只显示行程信息？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, s.notes, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001' AND s.status = 'Scheduled'
ORDER BY s.departure_datetime DESC;

[User] 能否帮我查询特定路线(route_id 为 'RT001')的所有行程信息，并关联到乘客的联系方式？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.phone_number, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.route_id = 'RT001';

[User] 能否只显示状态为‘On Time’的行程，并按出发时间升序排列？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.phone_number, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.route_id = 'RT001' AND s.status = 'On Time'
ORDER BY s.departure_datetime ASC;

[User] 如果乘客信息为空，能否仍然显示行程信息，并限制结果前10条？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.phone_number, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.route_id = 'RT001' AND s.status = 'On Time'
ORDER BY s.departure_datetime ASC
LIMIT 10;

[User] 能否帮我统计数据库中所有乘客的数量，按忠诚计划ID分组？

[Assistant]
SELECT loyalty_program_id, COUNT(*) as passenger_count
FROM passengers
GROUP BY loyalty_program_id;

[User] Can you help me find all schedules for a specific route with route_id 'RT789' that includes the train details and the departure times?

[Assistant]
SELECT s.schedule_id, s.departure_datetime, s.arrival_datetime, s.status, t.train_id
FROM schedules s
JOIN train_cars t ON s.train_id = t.train_id
WHERE s.route_id = 'RT789';

[User] Can you filter the results to show only schedules with a status of 'Delayed'?

[Assistant]
SELECT s.schedule_id, s.departure_datetime, s.arrival_datetime, s.status, t.train_id
FROM schedules s
JOIN train_cars t ON s.train_id = t.train_id
WHERE s.route_id = 'RT789' AND s.status = 'Delayed';

[User] Can you also include the origin and destination station names for the route in the results?

[Assistant]
SELECT s.schedule_id, s.departure_datetime, s.arrival_datetime, s.status, t.train_id,
       os.station_name AS origin_station, ds.station_name AS destination_station
FROM schedules s
JOIN train_cars t ON s.train_id = t.train_id
JOIN routes r ON s.route_id = r.route_id
JOIN stations os ON r.origin_station_id = os.station_id
JOIN stations ds ON r.destination_station_id = ds.station_id
WHERE s.route_id = 'RT789' AND s.status = 'Delayed';

[User] Can you provide the total capacity of all train cars for a specific train with train_id 'TR789'?

[Assistant]
SELECT SUM(capacity) AS total_capacity
FROM train_cars
WHERE train_id = 'TR789';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )

[User] Can you list the names of agencies that do not have a parent agency assigned, ordered by their established date?

[Assistant]
SELECT agency_id, agency_name, established_date
FROM government_services.agencies
WHERE parent_agency_id IS NULL
ORDER BY established_date;

[User] How many agencies exist at each jurisdiction level?

[Assistant]
SELECT jurisdiction_level, COUNT(*) AS agency_count
FROM government_services.agencies
GROUP BY jurisdiction_level;

[User] Now exclude jurisdiction levels that have fewer than 5 agencies.

[Assistant]
SELECT jurisdiction_level, COUNT(*) AS agency_count
FROM government_services.agencies
GROUP BY jurisdiction_level
HAVING COUNT(*) >= 5;

[User] Also, show me the average establishment year for those jurisdiction levels.

[Assistant]
SELECT jurisdiction_level,
       COUNT(*) AS agency_count,
       AVG(EXTRACT(YEAR FROM established_date)) AS avg_established_year
FROM government_services.agencies
GROUP BY jurisdiction_level
HAVING COUNT(*) >= 5;

[User] Sort the results by agency_count descending and limit to 3.

[Assistant]
SELECT jurisdiction_level,
       COUNT(*) AS agency_count,
       AVG(EXTRACT(YEAR FROM established_date)) AS avg_established_year
FROM government_services.agencies
GROUP BY jurisdiction_level
HAVING COUNT(*) >= 5
ORDER BY agency_count DESC
LIMIT 3;

[User] I would like to see a list of agencies and the names of their respective parent agencies.

[Assistant]
SELECT a.agency_id, a.agency_name, p.agency_name AS parent_agency_name
FROM government_services.agencies a
LEFT JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id;

[User] Could you only show agencies that actually have a parent agency, and order the result by the agency name?

[Assistant]
SELECT a.agency_id, a.agency_name, p.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
ORDER BY a.agency_name;

[User] List each child agency ID and name along with its parent agency ID and name.

[Assistant]
SELECT c.agency_id AS child_id,
       c.agency_name AS child_name,
       p.agency_id AS parent_id,
       p.agency_name AS parent_name
FROM government_services.agencies AS c
JOIN government_services.agencies AS p
  ON c.parent_agency_id = p.agency_id;

[User] Show me all agencies established after 2020 and their jurisdiction level.

[Assistant]
SELECT agency_id, agency_name, jurisdiction_level, established_date
FROM government_services.agencies
WHERE established_date > '2020-12-31';

[User] Can you also include their parent agency's name in the result?

[Assistant]
SELECT a.agency_id, a.agency_name, a.jurisdiction_level, a.established_date, p.agency_name AS parent_agency_name
FROM government_services.agencies a
LEFT JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
WHERE a.established_date > '2020-12-31';

[User] Only show agencies where the parent agency's jurisdiction level is 'Federal'.

[Assistant]
SELECT a.agency_id, a.agency_name, a.jurisdiction_level, a.established_date, p.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
WHERE a.established_date > '2020-12-31' AND p.jurisdiction_level = 'Federal';

[User] Sort the list by established date descending and show only the top 5 agencies.

[Assistant]
SELECT a.agency_id, a.agency_name, a.jurisdiction_level, a.established_date, p.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
WHERE a.established_date > '2020-12-31' AND p.jurisdiction_level = 'Federal'
ORDER BY a.established_date DESC
LIMIT 5;

[User] Can you show me a list of all agencies along with their parent agency names?

[Assistant]
SELECT a.agency_id, a.agency_name, pa.agency_name AS parent_agency_name
FROM government_services.agencies a
LEFT JOIN government_services.agencies pa ON a.parent_agency_id = pa.agency_id;

[User] Only show agencies that actually have a parent agency.

[Assistant]
SELECT a.agency_id, a.agency_name, pa.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies pa ON a.parent_agency_id = pa.agency_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
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] Count the number of tokens for each contract address.

[Assistant] SELECT contract_address, COUNT(*) AS token_count FROM web3.tokens GROUP BY contract_address;

[User] Only show contracts that have more than 5 tokens.

[Assistant] SELECT contract_address, COUNT(*) AS token_count FROM web3.tokens GROUP BY contract_address HAVING COUNT(*) > 5;

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

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

[User] Find the contract ID, address, and deployer address for all contracts that have not emitted any events.

[Assistant] SELECT c.contract_id, c.address, c.deployer_address FROM web3.contracts AS c LEFT JOIN web3.events AS e ON c.contract_id = e.contract_id WHERE e.event_id IS NULL;

[User] List all users and the total value of all transactions they have initiated. Show user_id, username, and total_transaction_value.

[Assistant]
SELECT u.user_id, u.username, COALESCE(SUM(t.value), 0) AS total_transaction_value
FROM web3.users u
LEFT JOIN web3.wallets w ON u.user_id = w.user_id
LEFT JOIN web3.transactions t ON w.address = t.from_address
GROUP BY u.user_id, u.username;

[User] Actually, only show users who have initiated at least one transaction, and sort them by total_transaction_value descending.

[Assistant]
SELECT u.user_id, u.username, SUM(t.value) AS total_transaction_value
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
JOIN web3.transactions t ON w.address = t.from_address
GROUP BY u.user_id, u.username
HAVING SUM(t.value) > 0
ORDER BY total_transaction_value DESC;

[User] Show all contracts and the names of all events they have ever emitted. Include contract_id, contract address, and event_name.

[Assistant]
SELECT c.contract_id, c.address, e.event_name
FROM web3.contracts c
JOIN web3.events e ON c.contract_id = e.contract_id
ORDER BY c.contract_id, e.event_name;

[User] Show all contracts along with the number of events each contract has emitted. Include the contract address and the event count.

[Assistant]
SELECT c.address, COUNT(e.event_id) AS event_count
FROM web3.contracts c
LEFT JOIN web3.events e ON c.contract_id = e.contract_id
GROUP BY c.address;