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 train_station_management.train_cars (
    car_id character varying(64) NOT NULL, -- Unique identifier for the train car
    train_id character varying(64) NOT NULL, -- Foreign key referencing trains
    car_number character varying(10) NOT NULL, -- Identifier of the car within the train set
    car_type character varying(64) NOT NULL, -- e.g., Locomotive, Passenger, Sleeper, Dining, Baggage
    class character varying(32), -- e.g., First, Business, Economy (null for non-passenger cars)
    capacity integer, -- Passenger capacity of this specific car (null for non-passenger cars)
    features text, -- Comma-separated list of features (e.g., 'WiFi', 'Power Outlet', 'Accessible Restroom')
    PRIMARY KEY (car_id),
    FOREIGN KEY (train_id) REFERENCES train_station_management.trains(train_id)
)
CREATE TABLE train_station_management.routes (
    route_id character varying(64) NOT NULL, -- Unique identifier for the route
    route_name character varying(128) NOT NULL, -- Name of the route (e.g., 'Northeast Corridor')
    description text, -- Description of the route
    origin_station_id character varying(64) NOT NULL, -- Starting station
    destination_station_id character varying(64) NOT NULL, -- Final station
    is_active boolean NOT NULL DEFAULT true, -- Is the route currently operational?
    PRIMARY KEY (route_id),
    FOREIGN KEY (origin_station_id) REFERENCES train_station_management.stations(station_id),
    FOREIGN KEY (destination_station_id) REFERENCES train_station_management.stations(station_id)
)
CREATE TABLE train_station_management.tickets (
    ticket_id character varying(64) NOT NULL, -- Unique identifier for the ticket
    booking_id character varying(64) NOT NULL, -- Foreign key referencing the booking
    car_id character varying(64) NOT NULL, -- Foreign key referencing the train car
    seat_number character varying(10), -- Assigned seat number (e.g., '12A')
    ticket_type character varying(32) NOT NULL DEFAULT 'Adult', -- e.g., Adult, Child, Senior, Student
    price numeric(10, 2) NOT NULL, -- Price of this specific ticket
    is_checked_in boolean NOT NULL DEFAULT false, -- Has the passenger checked in with this ticket?
    qr_code_data text, -- Data for generating a QR code for the ticket
    PRIMARY KEY (ticket_id),
    FOREIGN KEY (booking_id) REFERENCES train_station_management.bookings(booking_id),
    FOREIGN KEY (car_id) REFERENCES train_station_management.train_cars(car_id)
)

[User] Can you help me find the total passenger capacity for each train car on a specific route with route_id 'RT123'?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL;

[User] Can you modify the query to include only passenger cars with a capacity greater than 50?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL AND tc.capacity > 50;

[User] Can you also add the route name and description to the result?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity, r.route_name, r.description
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL AND tc.capacity > 50;

[User] Can you retrieve the total number of tickets sold for each car type?

[Assistant]
SELECT tc.car_type, COUNT(t.ticket_id) AS total_tickets
FROM train_station_management.train_cars tc
JOIN train_station_management.tickets t ON tc.car_id = t.car_id
GROUP BY tc.car_type;

[User] I need to find all tickets for a specific route 'RT456' along with the car details and route information.

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456';

[User] Can you filter this to show only tickets that have been checked in?

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456' AND t.is_checked_in = true;

[User] Can you also add the ticket type to the results?

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, t.ticket_type, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456' AND t.is_checked_in = true;

[User] Can you assist me in finding all staff members assigned to schedules for a specific route with route_id 'RT456', including the train details and schedule status?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.schedules s ON s.train_id = st.primary_station_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456';

[User] I noticed the query might not be correct. Can you revise it to ensure it connects staff to schedules properly through their primary station or related data?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.route_stations rs ON st.primary_station_id = rs.station_id
JOIN train_station_management.schedules s ON s.route_id = rs.route_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456';

[User] Can you filter the results to include only staff with the role of 'Engineer' and schedules with status 'On Time'?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.route_stations rs ON st.primary_station_id = rs.station_id
JOIN train_station_management.schedules s ON s.route_id = rs.route_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456' AND st.role = 'Engineer' AND s.status = 'On Time';

[User] Can you help me get the total number of passenger cars for each train car type in the database?

[Assistant]
SELECT car_type, COUNT(*) as total_cars
FROM train_station_management.train_cars
WHERE car_type = 'Passenger'
GROUP BY car_type;

[User] Can you help me retrieve the details of all bookings for a specific route with route_id 'RT789', including the passenger names and the scheduled departure times?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
WHERE s.route_id = 'RT789';

[User] Can you modify the query to include only bookings with a status of 'Pending'?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending';

[User] Can you also add the route name and origin station ID to the results?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price, r.route_name, r.origin_station_id
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
JOIN train_station_management.routes r ON s.route_id = r.route_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending';

[User] Can you sort the results by departure datetime in descending order?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price, r.route_name, r.origin_station_id
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
JOIN train_station_management.routes r ON s.route_id = r.route_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending'
ORDER BY s.departure_datetime DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )

[User] For each location, what is the average appointment duration? Show location_id and the average duration.

[Assistant] SELECT location_id, AVG(duration_minutes) FROM healthcare.appointments GROUP BY location_id;

[User] Show all appointments that have 'follow-up' mentioned in the notes field.

[Assistant] SELECT * FROM healthcare.appointments WHERE notes LIKE '%follow-up%';

[User] For each patient, find the next appointment after each one. Return patient_id, appointment_id AS current_appointment, next_appointment_id, and waiting_time in minutes.

[Assistant]
SELECT a.patient_id,
       a.appointment_id AS current_appointment,
       b.appointment_id AS next_appointment_id,
       EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 AS waiting_time
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.patient_id = b.patient_id
 AND b.appointment_time = (
     SELECT MIN(appointment_time)
     FROM healthcare.appointments
     WHERE patient_id = a.patient_id
       AND appointment_time > a.appointment_time
 ) ;

[User] Only include waiting times less than 30 minutes.

[Assistant]
SELECT a.patient_id,
       a.appointment_id AS current_appointment,
       b.appointment_id AS next_appointment_id,
       EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 AS waiting_time
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.patient_id = b.patient_id
 AND b.appointment_time = (
     SELECT MIN(appointment_time)
     FROM healthcare.appointments
     WHERE patient_id = a.patient_id
       AND appointment_time > a.appointment_time
 )
WHERE EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 < 30;

[User] Get the total number of appointments grouped by status.

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

[User] Now filter to include only statuses with more than 50 appointments.

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

[User] Find overlapping appointments for each doctor. Return doctor_id, appointment_id_1, appointment_id_2, and overlap duration in minutes.

[Assistant]
SELECT a.doctor_id,
       a.appointment_id AS appointment_id_1,
       b.appointment_id AS appointment_id_2,
       EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60 AS overlap_minutes
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.doctor_id = b.doctor_id
 AND a.appointment_id < b.appointment_id
WHERE a.appointment_time < b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes)
  AND b.appointment_time < a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes);

[User] Exclude overlaps less than 15 minutes.

[Assistant]
SELECT a.doctor_id,
       a.appointment_id AS appointment_id_1,
       b.appointment_id AS appointment_id_2,
       EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60 AS overlap_minutes
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.doctor_id = b.doctor_id
 AND a.appointment_id < b.appointment_id
WHERE a.appointment_time < b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes)
  AND b.appointment_time < a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes)
HAVING (EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60) >= 15;

[User] Also only include overlaps where status is 'Scheduled' for both appointments.

[Assistant]
SELECT a.doctor_id,
       a.appointment_id AS appointment_id_1,
       b.appointment_id AS appointment_id_2,
       EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60 AS overlap_minutes
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.doctor_id = b.doctor_id
 AND a.appointment_id < b.appointment_id
WHERE a.status = 'Scheduled'
  AND b.status = 'Scheduled'
  AND a.appointment_time < b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes)
  AND b.appointment_time < a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes)
HAVING (EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60) >= 15;

[User] For each patient, find the next appointment after each one. Return patient_id, appointment_id, next_appointment_id, and the waiting time in minutes between them.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   );

[User] Now include only the pairs where the waiting time is less than 30 minutes.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   )
WHERE EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 < 30;


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.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
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] List the content and comment ID for all comments made by users with private profiles.

[Assistant] SELECT c.comment_id, c.content FROM social_media.comments AS c JOIN social_media.user_settings AS us ON c.user_id = us.user_id WHERE us.private_profile = TRUE;

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

[Assistant] SELECT c.comment_id, c.content FROM social_media.comments AS c JOIN social_media.user_settings AS us ON c.user_id = us.user_id WHERE us.private_profile = TRUE AND c.created_at >= '2024-01-01' AND c.created_at < '2025-01-01';

[User] List the conversation IDs and user IDs for participants who have email notifications enabled.

[Assistant] SELECT cp.conversation_id, cp.user_id FROM social_media.conversation_participants AS cp JOIN social_media.user_settings AS us ON cp.user_id = us.user_id WHERE us.email_notifications_enabled = TRUE;

[User] Now, only include those users whose profile is set to private.

[Assistant] SELECT cp.conversation_id, cp.user_id FROM social_media.conversation_participants AS cp JOIN social_media.user_settings AS us ON cp.user_id = us.user_id WHERE us.email_notifications_enabled = TRUE AND us.private_profile = TRUE;

[User] Also, filter the results to include only participants who joined after a specific date, say '2023-01-01'.

[Assistant] SELECT cp.conversation_id, cp.user_id FROM social_media.conversation_participants AS cp JOIN social_media.user_settings AS us ON cp.user_id = us.user_id WHERE us.email_notifications_enabled = TRUE AND us.private_profile = TRUE AND cp.joined_at > '2023-01-01';

[User] Instead of user ID, can you show their theme setting and order the results by the join date ascending?

[Assistant] SELECT cp.conversation_id, us.theme, cp.joined_at FROM social_media.conversation_participants AS cp JOIN social_media.user_settings AS us ON cp.user_id = us.user_id WHERE us.email_notifications_enabled = TRUE AND us.private_profile = TRUE AND cp.joined_at > '2023-01-01' ORDER BY cp.joined_at ASC;

[User] Show me the content and creation time of comments made on posts authored by the user with ID 'user_X'.

[Assistant] SELECT T1.content, T1.created_at FROM social_media.comments AS T1 JOIN social_media.posts AS T2 ON T1.post_id = T2.post_id WHERE T2.user_id = 'user_X';

[User] Can you also include the username of the user who made each comment?

[Assistant] SELECT T1.content, T1.created_at, T3.username FROM social_media.comments AS T1 JOIN social_media.posts AS T2 ON T1.post_id = T2.post_id JOIN social_media.users AS T3 ON T1.user_id = T3.user_id WHERE T2.user_id = 'user_X';

[User] List the usernames of users who have commented on posts that are not replies to other comments.

[Assistant] SELECT DISTINCT T2.username FROM social_media.comments AS T1 JOIN social_media.users AS T2 ON T1.user_id = T2.user_id WHERE T1.parent_comment_id IS NULL;

[User] Can you filter this to only include users who have made more than one such comment?

[Assistant] SELECT T2.username FROM social_media.comments AS T1 JOIN social_media.users AS T2 ON T1.user_id = T2.user_id WHERE T1.parent_comment_id IS NULL GROUP BY T2.username HAVING COUNT(T1.comment_id) > 1;

[User] Also, show the total count of these top-level comments for each user and order the results by the count descending.

[Assistant] SELECT T2.username, COUNT(T1.comment_id) AS top_level_comment_count FROM social_media.comments AS T1 JOIN social_media.users AS T2 ON T1.user_id = T2.user_id WHERE T1.parent_comment_id IS NULL GROUP BY T2.username HAVING COUNT(T1.comment_id) > 1 ORDER BY top_level_comment_count DESC;

[User] Count the number of comments that have been updated since they were first created.

[Assistant] SELECT COUNT(*) FROM social_media.comments WHERE updated_at > created_at;

[User] List all comment IDs that have not received any likes.

[Assistant] SELECT T1.comment_id FROM social_media.comments AS T1 LEFT JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id WHERE T2.like_id IS NULL;

[User] Can you also include the content of these comments and the post_id they belong to?

[Assistant] SELECT T1.comment_id, T1.content, T1.post_id FROM social_media.comments AS T1 LEFT JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id WHERE T2.like_id IS NULL;


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.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)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)

[User] Show me the names and URLs of all DApps, and for each DApp, list the KYC status and last review date for all users who have an audit entry.

[Assistant]
SELECT d.name AS dapp_name, d.url, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
ORDER BY d.name, k.user_id;

[User] I only want DApps whose name includes the word 'market', and for KYC audits, show only those with status 'approved'.

[Assistant]
SELECT d.name AS dapp_name, d.url, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.name ILIKE '%market%' AND k.status = 'approved'
ORDER BY d.name, k.user_id;

[User] List the names of all DApps whose description contains the word 'auction' along with the user IDs of anyone who has had a KYC audit.

[Assistant]
SELECT d.name AS dapp_name, k.user_id
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
ORDER BY d.name, k.user_id;

[User] Just show KYC audits with a status that is not 'approved'.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
ORDER BY d.name, k.user_id;

[User] Actually, I want to include the reviewed_at time for each audit result too.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
ORDER BY d.name, k.user_id, k.reviewed_at;

[User] Filter further to only show audits reviewed after January 1, 2024.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
  AND k.reviewed_at > '2024-01-01'
ORDER BY d.name, k.user_id, k.reviewed_at;

[User] How many unique users have a KYC audit record with status 'pending'?

[Assistant]
SELECT COUNT(DISTINCT user_id) AS pending_kyc_users
FROM trading_platform.kyc_audit
WHERE status = 'pending';

[User] Show me all KYC audit records for user ID 'user_abc_123'.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123';

[User] From those, list only the ones with status 'pending'.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending';

[User] Order the results by the review date in ascending order.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending' ORDER BY reviewed_at ASC;

[User] Just show the latest pending audit for that user, displaying the user_id, status, and reviewed_at date.

[Assistant] SELECT user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending' ORDER BY reviewed_at DESC LIMIT 1;

[User] Show me the top 5 users with the most KYC audits, along with their latest audit status.

[Assistant] SELECT user_id, status, COUNT(*) as audit_count FROM trading_platform.kyc_audit GROUP BY user_id, status ORDER BY audit_count DESC LIMIT 5;

[User] Now modify the query to show only users whose latest KYC status was rejected.

[Assistant] WITH latest_audit AS (SELECT user_id, status, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY reviewed_at DESC) as rn FROM trading_platform.kyc_audit) SELECT user_id, status FROM latest_audit WHERE rn = 1 AND status = 'rejected' LIMIT 5;

[User] Actually, I want to see the count of rejected audits per user instead of just the latest status.

[Assistant] SELECT user_id, COUNT(*) as rejected_count FROM trading_platform.kyc_audit WHERE status = 'rejected' GROUP BY user_id ORDER BY rejected_count 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 trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
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.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)

[User] Count the number of metadata entries for each asset.

[Assistant]
SELECT asset_id, COUNT(*) AS metadata_count
FROM trading_platform.metadata
GROUP BY asset_id;

[User] List all peers with their IP addresses who have not been seen in the last 7 days.

[Assistant]
SELECT peer_id, ip_address, port, last_seen
FROM trading_platform.peers
WHERE last_seen < NOW() - INTERVAL '7 days';

[User] Show me, for each wallet address, the total sum of amounts for all unspent UTXOs, along with the user ID who owns the wallet.

[Assistant]
SELECT w.address, w.user_id, COALESCE(SUM(u.amount), 0) AS total_unspent_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address AND (u.spent = FALSE OR u.spent IS NULL)
GROUP BY w.address, w.user_id;

[User] Now, include only the wallets where the total unspent amount is greater than 50, and show the wallet_id as well.

[Assistant]
SELECT w.wallet_id, w.address, w.user_id, COALESCE(SUM(u.amount), 0) AS total_unspent_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address AND (u.spent = FALSE OR u.spent IS NULL)
GROUP BY w.wallet_id, w.address, w.user_id
HAVING COALESCE(SUM(u.amount), 0) > 50;

[User] Show me each user's username, their wallet address, and the total quantity of open orders they have placed, along with the name of the asset for each order.

[Assistant]
SELECT u.username, w.address, o.asset_id, SUM(o.quantity) AS total_open_quantity
FROM trading_platform.users u
JOIN trading_platform.wallets w ON u.user_id = w.user_id
JOIN trading_platform.orders o ON w.wallet_id = o.wallet_id
WHERE o.status = 'open'
GROUP BY u.username, w.address, o.asset_id
ORDER BY u.username, w.address, o.asset_id;

[User] Can you also include the email address for each user and only show those with at least 2 open orders?

[Assistant]
SELECT u.username, u.email, w.address, o.asset_id, SUM(o.quantity) AS total_open_quantity, COUNT(o.order_id) AS open_order_count
FROM trading_platform.users u
JOIN trading_platform.wallets w ON u.user_id = w.user_id
JOIN trading_platform.orders o ON w.wallet_id = o.wallet_id
WHERE o.status = 'open'
GROUP BY u.username, u.email, w.address, o.asset_id
HAVING COUNT(o.order_id) >= 2
ORDER BY u.username, w.address, o.asset_id;

[User] For each asset, show the asset_id, the number of associated metadata entries, and the quantity of orders placed for that asset.

[Assistant]
SELECT a.asset_id,
       COUNT(DISTINCT m.metadata_id) AS metadata_count,
       COUNT(o.order_id) AS order_count
FROM (SELECT DISTINCT asset_id FROM trading_platform.metadata
      UNION
      SELECT DISTINCT asset_id FROM trading_platform.orders) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
ORDER BY a.asset_id;

[User] The query failed because some assets do not have metadata. Please ensure all assets from the orders table are included, with metadata_count as 0 when none exist.

[Assistant]
SELECT a.asset_id,
       COALESCE(COUNT(m.metadata_id), 0) AS metadata_count,
       COUNT(o.order_id) AS order_count
FROM (
    SELECT DISTINCT asset_id FROM trading_platform.orders
) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
ORDER BY a.asset_id;

[User] Thanks. Now, could you also show the total number of unique users who have placed orders for each asset?

[Assistant]
SELECT a.asset_id,
       COALESCE(COUNT(m.metadata_id), 0) AS metadata_count,
       COUNT(o.order_id) AS order_count,
       COUNT(DISTINCT o.user_id) AS unique_user_count
FROM (
    SELECT DISTINCT asset_id FROM trading_platform.orders
) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
ORDER BY a.asset_id;

[User] Only include assets with at least 3 different users placing orders, and show the results ordered by unique_user_count descending.

[Assistant]
SELECT a.asset_id,
       COALESCE(COUNT(m.metadata_id), 0) AS metadata_count,
       COUNT(o.order_id) AS order_count,
       COUNT(DISTINCT o.user_id) AS unique_user_count
FROM (
    SELECT DISTINCT asset_id FROM trading_platform.orders
) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
HAVING COUNT(DISTINCT o.user_id) >= 3
ORDER BY unique_user_count DESC;

[User] I want each user with the date and action of their most recent log entry, along with how many log entries they have in the last 7 days.

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
)
SELECT u.user_id,
       u.username,
       rl.logged_at   AS latest_log_date,
       rl.action      AS latest_action,
       COUNT(l.*)     AS log_count
FROM trading_platform.users u
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1
LEFT JOIN trading_platform.logs l
  ON u.user_id = l.user_id
  AND l.logged_at >= NOW() - INTERVAL '7 days'
GROUP BY u.user_id, u.username, rl.logged_at, rl.action;

[User] Actually, I only care about log actions that contain the word 'trade'.

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
)
SELECT u.user_id,
       u.username,
       rl.logged_at   AS latest_log_date,
       rl.action      AS latest_action,
       COUNT(l.*)     AS log_count
FROM trading_platform.users u
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1
LEFT JOIN trading_platform.logs l
  ON u.user_id = l.user_id
  AND l.logged_at >= NOW() - INTERVAL '7 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username, rl.logged_at, rl.action;

[User] Include users who have no such logs, showing null for latest_action and latest_log_date, and zero for log_count.

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
)
SELECT u.user_id,
       u.username,
       rl.logged_at   AS latest_log_date,
       rl.action      AS latest_action,
       COALESCE(cnt.log_count, 0) AS log_count
FROM trading_platform.users u
LEFT JOIN a recent AS (
  SELECT user_id, COUNT(*) AS log_count
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
  GROUP BY user_id
) cnt ON u.user_id = cnt.user_id
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1;

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

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
),
log_counts AS (
  SELECT user_id, COUNT(*) AS log_count
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
  GROUP BY user_id
)
SELECT u.user_id,
       u.username,
       rl.logged_at    AS latest_log_date,
       rl.action       AS latest_action,
       COALESCE(lc.log_count, 0) AS log_count
FROM trading_platform.users u
LEFT JOIN log_counts lc
  ON u.user_id = lc.user_id
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1
ORDER BY log_count 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 trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
CREATE TABLE trading_platform.notifications ( notification_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, message text NOT NULL, sent_at timestamp NOT NULL, read_at timestamp, PRIMARY KEY (notification_id) )

[User] Show all peers, listing their ID, IP address, and port.

[Assistant] SELECT peer_id, ip_address, port FROM trading_platform.peers;

[User] Display the username and the total number of wallets for each user.

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

[User] Refine that to only show users with more than one wallet.

[Assistant] SELECT u.username, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.username HAVING COUNT(w.wallet_id) > 1;

[User] List all users, showing their user ID, username, and the total number of wallets they have created. Include users who have no wallets.

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

[User] Now, filter the results to only include users who have created at least 2 wallets.

[Assistant] SELECT u.user_id, u.username, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.user_id, u.username HAVING COUNT(w.wallet_id) >= 2;

[User] Also, for these users (with >= 2 wallets), show the address of their earliest created wallet.

[Assistant] WITH UserWalletCounts AS ( SELECT u.user_id, u.username, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.user_id, u.username HAVING COUNT(w.wallet_id) >= 2 ), EarliestWallets AS ( SELECT w.user_id, w.address AS earliest_wallet_address, ROW_NUMBER() OVER(PARTITION BY w.user_id ORDER BY w.created_at ASC) as rn FROM trading_platform.wallets w ) SELECT uwc.user_id, uwc.username, uwc.wallet_count, ew.earliest_wallet_address FROM UserWalletCounts uwc JOIN EarliestWallets ew ON uwc.user_id = ew.user_id WHERE ew.rn = 1;

[User] Finally, order the results by the count of wallets in descending order and limit to the top 5 users.

[Assistant] WITH UserWalletCounts AS ( SELECT u.user_id, u.username, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.user_id, u.username HAVING COUNT(w.wallet_id) >= 2 ), EarliestWallets AS ( SELECT w.user_id, w.address AS earliest_wallet_address, ROW_NUMBER() OVER(PARTITION BY w.user_id ORDER BY w.created_at ASC) as rn FROM trading_platform.wallets w ) SELECT uwc.user_id, uwc.username, uwc.wallet_count, ew.earliest_wallet_address FROM UserWalletCounts uwc JOIN EarliestWallets ew ON uwc.user_id = ew.user_id WHERE ew.rn = 1 ORDER BY uwc.wallet_count DESC LIMIT 5;

[User] Show me the top 5 users who have interacted with DApps, along with the count of distinct DApps they interacted with and their email addresses.

[Assistant] SELECT u.user_id, u.email, COUNT(DISTINCT l.details) AS dapp_count FROM trading_platform.users u JOIN trading_platform.logs l ON u.user_id = l.user_id WHERE l.action = 'dapp_interaction' GROUP BY u.user_id, u.email ORDER BY dapp_count DESC LIMIT 5;

[User] Now modify the query to only include interactions that happened in the last 30 days and show the DApp names instead of just counts.

[Assistant] SELECT u.user_id, u.email, d.name AS dapp_name FROM trading_platform.users u JOIN trading_platform.logs l ON u.user_id = l.user_id JOIN trading_platform.dapps d ON l.details = d.dapp_id WHERE l.action = 'dapp_interaction' AND l.logged_at >= NOW() - INTERVAL '30 days' ORDER BY l.logged_at DESC LIMIT 5;

[User] Actually, I want to see the total number of interactions per user instead of distinct DApps, and include their wallet addresses.

[Assistant] SELECT u.user_id, u.email, w.address AS wallet_address, COUNT(l.log_id) AS interaction_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id JOIN trading_platform.logs l ON u.user_id = l.user_id WHERE l.action = 'dapp_interaction' AND l.logged_at >= NOW() - INTERVAL '30 days' GROUP BY u.user_id, u.email, w.address ORDER BY interaction_count DESC LIMIT 5;

[User] List each user’s user_id and username along with their total trading value (sum of quantity * price from trades) as a buyer for trades executed in June 2024. Show the top 5 users by total value descending.

[Assistant]
SELECT u.user_id, u.username, SUM(t.quantity * t.price) AS total_value
FROM trading_platform.users u
JOIN trading_platform.trades t ON u.user_id = t.buyer_id
WHERE t.traded_at >= '2024-06-01' AND t.traded_at < '2024-07-01'
GROUP BY u.user_id, u.username
ORDER BY total_value DESC
LIMIT 5;

[User] Refine the query to include only users whose most recent KYC audit status is 'approved'.

[Assistant]
SELECT u.user_id, u.username, SUM(t.quantity * t.price) AS total_value
FROM trading_platform.users u
JOIN trading_platform.trades t ON u.user_id = t.buyer_id
JOIN (
  SELECT user_id, status
  FROM trading_platform.kyc_audit
  WHERE (user_id, reviewed_at) IN (
    SELECT user_id, MAX(reviewed_at) FROM trading_platform.kyc_audit GROUP BY user_id
  )
) ka ON u.user_id = ka.user_id AND ka.status = 'approved'
WHERE t.traded_at >= '2024-06-01' AND t.traded_at < '2024-07-01'
GROUP BY u.user_id, u.username
ORDER BY total_value DESC
LIMIT 5;

[User] Get the number of log entries for each user where the action contains 'fail' in the last 30 days.

[Assistant]
SELECT l.user_id, COUNT(*) AS fail_count
FROM trading_platform.logs l
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY l.user_id;

[User] Only include users with at least 3 such log entries.

[Assistant]
SELECT l.user_id, COUNT(*) AS fail_count
FROM trading_platform.logs l
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY l.user_id
HAVING COUNT(*) >= 3;

[User] Also include the username from the users table.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS fail_count
FROM trading_platform.users u
JOIN trading_platform.logs l ON u.user_id = l.user_id
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY u.user_id, u.username
HAVING COUNT(l.log_id) >= 3;

[User] Order the results by fail_count descending and limit to the top 5 users.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS fail_count
FROM trading_platform.users u
JOIN trading_platform.logs l ON u.user_id = l.user_id
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY u.user_id, u.username
HAVING COUNT(l.log_id) >= 3
ORDER BY fail_count 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 social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )

[User] Show me all replies to comments, including the reply's comment ID, the parent comment ID, and the content.

[Assistant] SELECT comment_id, parent_comment_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL;

[User] I also want to see which post each reply was made on. Can you include the post ID as well?

[Assistant] SELECT comment_id, parent_comment_id, post_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL;

[User] Now, only show replies made after June 1, 2024.

[Assistant] SELECT comment_id, parent_comment_id, post_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL AND created_at > '2024-06-01';

[User] Show me all comments that have non-empty content, including their ID, post ID, user ID, and content.

[Assistant] SELECT comment_id, post_id, user_id, content FROM social_media.comments WHERE content IS NOT NULL AND content != '';

[User] List all top-level comments, showing their ID, post ID, user ID, and content.

[Assistant] SELECT comment_id, post_id, user_id, content FROM social_media.comments WHERE parent_comment_id IS NULL;

[User] From those, show only the ones made after June 1st, 2024.

[Assistant] SELECT comment_id, post_id, user_id, content FROM social_media.comments WHERE parent_comment_id IS NULL AND created_at > '2024-06-01';

[User] Now, for these top-level comments, can you list any replies they have received, showing the reply's ID, content, and the user ID of the reply author?

[Assistant] SELECT c.comment_id AS top_level_comment_id, r.comment_id AS reply_id, r.content AS reply_content, r.user_id AS reply_user_id FROM social_media.comments c JOIN social_media.comments r ON c.comment_id = r.parent_comment_id WHERE c.parent_comment_id IS NULL AND c.created_at > '2024-06-01';

[User] Show me the number of comments each user has made on each post.

[Assistant] SELECT post_id, user_id, COUNT(*) AS comment_count FROM social_media.comments GROUP BY post_id, user_id;

[User] Can you also show the creation time of the most recent comment for each post by each user?

[Assistant] SELECT post_id, user_id, COUNT(*) AS comment_count, MAX(created_at) AS latest_comment_time FROM social_media.comments GROUP BY post_id, user_id;

[User] Can you list all replies along with their parent comment content for post_id 'P100'?

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL;

[User] Actually, I only want replies made after '2024-07-01'.

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL AND reply.created_at > '2024-07-01';

[User] Now include the original comment's created_at timestamp as well.

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, parent.created_at AS parent_created_at, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL AND reply.created_at > '2024-07-01';

[User] Finally, order the results by reply creation time ascending.

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, parent.created_at AS parent_created_at, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL AND reply.created_at > '2024-07-01' ORDER BY reply.created_at ASC;

[User] Show me the number of direct replies each top-level comment has on post 'P200'.

[Assistant] SELECT c.comment_id, COUNT(r.comment_id) AS reply_count FROM comments AS c LEFT JOIN comments AS r ON r.parent_comment_id = c.comment_id WHERE c.post_id = 'P200' AND c.parent_comment_id IS NULL GROUP BY c.comment_id;

[User] Order by reply_count descending and limit to top 5.

[Assistant] SELECT c.comment_id, COUNT(r.comment_id) AS reply_count FROM comments AS c LEFT JOIN comments AS r ON r.parent_comment_id = c.comment_id WHERE c.post_id = 'P200' AND c.parent_comment_id IS NULL GROUP BY c.comment_id ORDER BY reply_count DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    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, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)

[User] Show the count of citizens grouped by their verification status.

[Assistant] SELECT is_verified, COUNT(*) FROM government_services.citizens GROUP BY is_verified;

[User] Now, only include citizens who registered after January 1, 2023.

[Assistant] SELECT is_verified, COUNT(*) FROM government_services.citizens WHERE registration_date >= '2023-01-01' GROUP BY is_verified;

[User] Find all pairs of citizens who share the same first name and gender but have different last names. Display the shared first name, gender, the full name of the first citizen in the pair, and the full name of the second citizen.

[Assistant] SELECT c1.first_name, c1.gender, c1.first_name || ' ' || c1.last_name AS citizen1_full_name, c2.first_name || ' ' || c2.last_name AS citizen2_full_name FROM government_services.citizens AS c1 JOIN government_services.citizens AS c2 ON c1.first_name = c2.first_name AND c1.gender = c2.gender AND c1.last_name <> c2.last_name AND c1.citizen_id < c2.citizen_id;

[User] List the first name and last name of citizens who have scheduled appointments at accessible service locations, along with the scheduled start time of the appointment and the location name.

[Assistant] SELECT c.first_name, c.last_name, a.scheduled_start_time, sl.location_name FROM government_services.citizens AS c JOIN government_services.appointments AS a ON c.citizen_id = a.citizen_id JOIN government_services.service_locations AS sl ON a.location_id = sl.location_id WHERE sl.is_accessible = TRUE;

[User] Only include appointments scheduled in the year 2024.

[Assistant] SELECT c.first_name, c.last_name, a.scheduled_start_time, sl.location_name FROM government_services.citizens AS c JOIN government_services.appointments AS a ON c.citizen_id = a.citizen_id JOIN government_services.service_locations AS sl ON a.location_id = sl.location_id WHERE sl.is_accessible = TRUE AND EXTRACT(YEAR FROM a.scheduled_start_time) = 2024;

[User] List pairs of verified citizens who share the same primary address city. Show the city, the full name of the first citizen, and the full name of the second citizen.

[Assistant] SELECT SPLIT_PART(c1.primary_address, ', ', 2) AS city, c1.first_name || ' ' || c1.last_name AS citizen1_full_name, c2.first_name || ' ' || c2.last_name AS citizen2_full_name FROM government_services.citizens AS c1 JOIN government_services.citizens AS c2 ON SPLIT_PART(c1.primary_address, ', ', 2) = SPLIT_PART(c2.primary_address, ', ', 2) AND c1.citizen_id < c2.citizen_id WHERE c1.is_verified = TRUE AND c2.is_verified = TRUE;

[User] Provide a count of citizens registered per calendar year.

[Assistant] SELECT CAST(EXTRACT(YEAR FROM registration_date) AS INTEGER) AS registration_year, COUNT(*) AS citizen_count FROM government_services.citizens GROUP BY 1 ORDER BY 1;

[User] Count the number of active services provided by each agency. Show the agency name and the count.

[Assistant] SELECT a.agency_name, COUNT(s.service_id) AS active_service_count FROM government_services.agencies AS a JOIN government_services.services AS s ON a.agency_id = s.agency_id WHERE s.is_active = TRUE GROUP BY a.agency_name;

[User] Only include agencies with more than 5 active services.

[Assistant] SELECT a.agency_name, COUNT(s.service_id) AS active_service_count FROM government_services.agencies AS a JOIN government_services.services AS s ON a.agency_id = s.agency_id WHERE s.is_active = TRUE GROUP BY a.agency_name HAVING COUNT(s.service_id) > 5;

[User] Also show the total standard fee for the active services provided by these agencies.

[Assistant] SELECT a.agency_name, COUNT(s.service_id) AS active_service_count, SUM(s.standard_fee) AS total_standard_fee FROM government_services.agencies AS a JOIN government_services.services AS s ON a.agency_id = s.agency_id WHERE s.is_active = TRUE GROUP BY a.agency_name HAVING COUNT(s.service_id) > 5;

[User] Order the results by the total standard fee in descending order.

[Assistant] SELECT a.agency_name, COUNT(s.service_id) AS active_service_count, SUM(s.standard_fee) AS total_standard_fee FROM government_services.agencies AS a JOIN government_services.services AS s ON a.agency_id = s.agency_id WHERE s.is_active = TRUE GROUP BY a.agency_name HAVING COUNT(s.service_id) > 5 ORDER BY total_standard_fee DESC;


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

[User] Find documents that have the same document_name but are associated with different cases. Show the document name and the two different case IDs.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id;

[User] Actually, only show pairs where at least one of the documents is of document_type 'Contract'.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract');

[User] Also, only include pairs where both documents were uploaded in the year 2024.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract') AND YEAR(d1.upload_timestamp) = 2024 AND YEAR(d2.upload_timestamp) = 2024;

[User] List document names, types, and upload timestamps for documents uploaded after '2024-01-01'.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01'

[User] Filter the results to only include documents of type 'Contract'.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract'

[User] Only show documents with version 3.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract' AND version  =  3

[User] Remove the version filter, add the document description, and order by upload timestamp.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp ,  description FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract' ORDER BY upload_timestamp

[User] List the document name, upload timestamp, and the full name of the lawyer who uploaded it, for all documents associated with case number 'CASE123'.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123'

[User] Only include documents of type 'Pleading'.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123' AND T1.document_type  =  'Pleading'

[User] Also show the version and restrict results to documents with version greater than 1.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T1.version ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123' AND T1.document_type  =  'Pleading' AND T1.version  >  1

[User] Find pairs of documents within the same case that were uploaded on the same day but by different lawyers. Show the case_id, upload_date, document_id and uploader_id for both documents in the pair.

[Assistant] SELECT d1.case_id, DATE(d1.upload_timestamp) AS upload_date, d1.document_id AS document1_id, d1.uploaded_by_lawyer_id AS lawyer1_id, d2.document_id AS document2_id, d2.uploaded_by_lawyer_id AS lawyer2_id FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.case_id = d2.case_id AND DATE(d1.upload_timestamp) = DATE(d2.upload_timestamp) AND d1.uploaded_by_lawyer_id <> d2.uploaded_by_lawyer_id WHERE d1.document_id < d2.document_id;

[User] List the case number, case name, and the full name of the client for cases that have uploaded documents.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

[User] Also include the full name of the lead lawyer for these cases.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name AS client_name ,  T4.full_name AS lawyer_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T4 ON T1.lead_lawyer_id  =  T4.lawyer_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

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

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

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

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

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

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


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.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )

[User] How many users have followed more than one person in total?

[Assistant]
SELECT follower_user_id, COUNT(DISTINCT following_user_id) AS following_count
FROM social_media.follows
GROUP BY follower_user_id
HAVING COUNT(DISTINCT following_user_id) > 1;

[User] Find users who followed at least two different people on the same calendar day. For each such user, list their ID, the IDs of the two people they followed, and the creation times of those two follow events.

[Assistant] SELECT f1.follower_user_id, f1.following_user_id AS followed_user_1_id, f2.following_user_id AS followed_user_2_id, f1.created_at AS follow_1_created_at, f2.created_at AS follow_2_created_at FROM social_media.follows AS f1 JOIN social_media.follows AS f2 ON f1.follower_user_id = f2.follower_user_id WHERE f1.following_user_id != f2.following_user_id AND DATE(f1.created_at) = DATE(f2.created_at);

[User] Also, only include pairs of follows where the two follow events happened within 30 minutes of each other on that same day.

[Assistant] SELECT f1.follower_user_id, f1.following_user_id AS followed_user_1_id, f2.following_user_id AS followed_user_2_id, f1.created_at AS follow_1_created_at, f2.created_at AS follow_2_created_at FROM social_media.follows AS f1 JOIN social_media.follows AS f2 ON f1.follower_user_id = f2.follower_user_id WHERE f1.following_user_id != f2.following_user_id AND DATE(f1.created_at) = DATE(f2.created_at) AND ABS(EXTRACT(EPOCH FROM (f1.created_at - f2.created_at))) <= 1800;

[User] List all unique pairs of users where one follows the other, showing both the follower and following user ID.

[Assistant]
SELECT DISTINCT follower_user_id, following_user_id
FROM social_media.follows;

[User] Only include pairs where the follower_user_id is alphabetically less than the following_user_id.

[Assistant]
SELECT DISTINCT follower_user_id, following_user_id
FROM social_media.follows
WHERE follower_user_id < following_user_id;

[User] Show me all users who started following someone in May 2024, along with both the user ID of the follower and the followed user.

[Assistant]
SELECT follower_user_id, following_user_id
FROM social_media.follows
WHERE created_at >= '2024-05-01' AND created_at < '2024-06-01';

[User] Can you also include the follow_id and the exact follow creation timestamp?

[Assistant]
SELECT follow_id, follower_user_id, following_user_id, created_at
FROM social_media.follows
WHERE created_at >= '2024-05-01' AND created_at < '2024-06-01';

[User] Now only show follows where both the follower and following user IDs start with 'U2'.

[Assistant]
SELECT follow_id, follower_user_id, following_user_id, created_at
FROM social_media.follows
WHERE created_at >= '2024-05-01' AND created_at < '2024-06-01'
  AND follower_user_id LIKE 'U2%' AND following_user_id LIKE 'U2%';

[User] Order them by the creation time in descending order.

[Assistant]
SELECT follow_id, follower_user_id, following_user_id, created_at
FROM social_media.follows
WHERE created_at >= '2024-05-01' AND created_at < '2024-06-01'
  AND follower_user_id LIKE 'U2%' AND following_user_id LIKE 'U2%'
ORDER BY created_at DESC;

[User] How many users does each user follow? Show the follower user ID and the count.

[Assistant] SELECT follower_user_id, count(*) FROM social_media.follows GROUP BY follower_user_id;

[User] Find pairs of user IDs (A, B) such that user A follows user B, and user B also follows user A (mutual follows). List user A's ID and user B's ID.

[Assistant] SELECT T1.follower_user_id AS user_a, T1.following_user_id AS user_b FROM social_media.follows AS T1 JOIN social_media.follows AS T2 ON T1.follower_user_id = T2.following_user_id AND T1.following_user_id = T2.follower_user_id;

[User] Only show pairs where user B started following user A after user A started following user B. Also include the follow dates for both.

[Assistant] SELECT T1.follower_user_id AS user_a, T1.following_user_id AS user_b, T1.created_at AS user_a_follows_b_date, T2.created_at AS user_b_follows_a_date FROM social_media.follows AS T1 JOIN social_media.follows AS T2 ON T1.follower_user_id = T2.following_user_id AND T1.following_user_id = T2.follower_user_id WHERE T2.created_at > T1.created_at;

[User] Order the results by the date user B followed user A, from oldest to newest.

[Assistant] SELECT T1.follower_user_id AS user_a, T1.following_user_id AS user_b, T1.created_at AS user_a_follows_b_date, T2.created_at AS user_b_follows_a_date FROM social_media.follows AS T1 JOIN social_media.follows AS T2 ON T1.follower_user_id = T2.following_user_id AND T1.following_user_id = T2.follower_user_id WHERE T2.created_at > T1.created_at ORDER BY user_b_follows_a_date ASC;


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

[User] List all medications with a description that includes the word 'antibiotic'.

[Assistant] SELECT * FROM healthcare.medications WHERE description ILIKE '%antibiotic%';

[User] Retrieve all pairs of medications that share the same generic_name but have different NDC codes. Show the first medication's ID, name, the second medication's ID, name, and the shared generic_name.

[Assistant] SELECT m1.medication_id AS med1_id, m1.medication_name AS med1_name, m2.medication_id AS med2_id, m2.medication_name AS med2_name, m1.generic_name FROM healthcare.medications m1 JOIN healthcare.medications m2 ON m1.generic_name = m2.generic_name AND m1.ndc_code <> m2.ndc_code WHERE m1.medication_id < m2.medication_id;

[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;

[User] I want to see pairs of medications that share the same manufacturer. Show each medication's name and its peer's medication_name along with the manufacturer.

[Assistant] SELECT t1.medication_name AS med1_name, t2.medication_name AS med2_name, t1.manufacturer FROM healthcare.medications t1 JOIN healthcare.medications t2 ON t1.manufacturer = t2.manufacturer;

[User] Exclude any rows where a medication is paired with itself.

[Assistant] SELECT t1.medication_name AS med1_name, t2.medication_name AS med2_name, t1.manufacturer FROM healthcare.medications t1 JOIN healthcare.medications t2 ON t1.manufacturer = t2.manufacturer AND t1.medication_id <> t2.medication_id;

[User] Now only include manufacturers 'Pfizer' or 'Moderna'.

[Assistant] SELECT t1.medication_name AS med1_name, t2.medication_name AS med2_name, t1.manufacturer FROM healthcare.medications t1 JOIN healthcare.medications t2 ON t1.manufacturer = t2.manufacturer AND t1.medication_id <> t2.medication_id WHERE t1.manufacturer IN ('Pfizer','Moderna');

[User] I’m seeing duplicate pairs for reversed order. Remove reversed duplicates.

[Assistant] SELECT t1.medication_name AS med1_name, t2.medication_name AS med2_name, t1.manufacturer FROM healthcare.medications t1 JOIN healthcare.medications t2 ON t1.manufacturer = t2.manufacturer AND t1.medication_id < t2.medication_id WHERE t1.manufacturer IN ('Pfizer','Moderna');

[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] List the medication IDs and names for all entries where the description is missing or empty.

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

[User] For those medications, please also show the manufacturer and sort the results by medication name in ascending order.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE description IS NULL OR description = '' ORDER BY medication_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.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.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )

[User] Show me the total hours spent by each lawyer for each case, along with the case number and lawyer ID.

[Assistant]
SELECT t.case_id, c.case_number, t.lawyer_id, SUM(t.hours_spent) AS total_hours
FROM legal_services.time_entries t
JOIN legal_services.cases c ON t.case_id = c.case_id
GROUP BY t.case_id, c.case_number, t.lawyer_id;

[User] Only include lawyers who have logged more than 10 hours on a given case.

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

[User] Additionally, restrict to cases that are currently 'Open'.

[Assistant]
SELECT t.case_id, c.case_number, t.lawyer_id, SUM(t.hours_spent) AS total_hours
FROM legal_services.time_entries t
JOIN legal_services.cases c ON t.case_id = c.case_id
WHERE c.status = 'Open'
GROUP BY t.case_id, c.case_number, t.lawyer_id
HAVING SUM(t.hours_spent) > 10;

[User] List all appointments with their subject and associated case number for appointments that have both a case_id and a non-null location.

[Assistant]
SELECT a.appointment_id, a.subject, a.case_id, c.case_number
FROM legal_services.appointments a
JOIN legal_services.cases c ON a.case_id = c.case_id
WHERE a.case_id IS NOT NULL AND a.location IS NOT NULL;

[User] Show only those appointments where the status is not 'cancelled'.

[Assistant]
SELECT a.appointment_id, a.subject, a.case_id, c.case_number
FROM legal_services.appointments a
JOIN legal_services.cases c ON a.case_id = c.case_id
WHERE a.case_id IS NOT NULL AND a.location IS NOT NULL AND (a.status IS NULL OR a.status <> 'cancelled');

[User] Also, only show appointments starting after June 1st, 2024.

[Assistant]
SELECT a.appointment_id, a.subject, a.case_id, c.case_number
FROM legal_services.appointments a
JOIN legal_services.cases c ON a.case_id = c.case_id
WHERE a.case_id IS NOT NULL
  AND a.location IS NOT NULL
  AND (a.status IS NULL OR a.status <> 'cancelled')
  AND a.start_time > '2024-06-01';

[User] Remove any appointments that are linked to cases with a status of 'Closed'.

[Assistant]
SELECT a.appointment_id, a.subject, a.case_id, c.case_number
FROM legal_services.appointments a
JOIN legal_services.cases c ON a.case_id = c.case_id
WHERE a.case_id IS NOT NULL
  AND a.location IS NOT NULL
  AND (a.status IS NULL OR a.status <> 'cancelled')
  AND a.start_time > '2024-06-01'
  AND c.status <> 'Closed';

[User] Show the total billed hours and total billed amount for each case that has at least one billed and billable time entry.

[Assistant]
SELECT t.case_id, c.case_number, SUM(t.hours_spent) AS total_billed_hours, SUM(t.hours_spent * t.billing_rate) AS total_billed_amount
FROM legal_services.time_entries t
JOIN legal_services.cases c ON t.case_id = c.case_id
WHERE t.is_billable = TRUE AND t.is_billed = TRUE
GROUP BY t.case_id, c.case_number
HAVING COUNT(*) >= 1;

[User] Show me all cases where the description contains the word 'agreement'. Display the case ID, case name, and description.

[Assistant] SELECT case_id, case_name, description FROM legal_services.cases WHERE description ILIKE '%agreement%';

[User] Also include cases where the description contains 'contract', and make sure the status is 'Pending'.

[Assistant] SELECT case_id, case_name, description FROM legal_services.cases WHERE (description ILIKE '%agreement%' OR description ILIKE '%contract%') AND status = 'Pending';

[User] Now, show only those cases from the previous list that were opened in the last 90 days.

[Assistant] SELECT case_id, case_name, description FROM legal_services.cases WHERE (description ILIKE '%agreement%' OR description ILIKE '%contract%') AND status = 'Pending' AND date_opened >= CURRENT_DATE - INTERVAL '90 days';

[User] Finally, order the results by date opened descending and only show the case name and description.

[Assistant] SELECT case_name, description FROM legal_services.cases WHERE (description ILIKE '%agreement%' OR description ILIKE '%contract%') AND status = 'Pending' AND date_opened >= CURRENT_DATE - INTERVAL '90 days' ORDER BY date_opened DESC;

[User] List the case ID, case number, and case name for all cases with status 'Open'.

[Assistant] SELECT case_id, case_number, case_name FROM legal_services.cases WHERE status = 'Open';

[User] Now, only show those cases opened in the year 2023.

[Assistant] SELECT case_id, case_number, case_name FROM legal_services.cases WHERE status = 'Open' AND EXTRACT(YEAR FROM date_opened) = 2023;

[User] Great, could you also show the lead lawyer ID and count how many open cases each of those lawyers has opened in 2023, displaying this count alongside the case details for each case? Order the results by date opened ascending.

[Assistant] SELECT c.case_id, c.case_number, c.case_name, c.lead_lawyer_id, lawyer_case_counts.case_count FROM legal_services.cases AS c JOIN ( SELECT lead_lawyer_id, COUNT(*) AS case_count FROM legal_services.cases WHERE status = 'Open' AND EXTRACT(YEAR FROM date_opened) = 2023 GROUP BY lead_lawyer_id ) AS lawyer_case_counts ON c.lead_lawyer_id = lawyer_case_counts.lead_lawyer_id WHERE c.status = 'Open' AND EXTRACT(YEAR FROM c.date_opened) = 2023 ORDER BY c.date_opened ASC;

[User] Calculate the average number of days cases stay open before being closed, grouped by case type. Only consider cases that have a date closed.

[Assistant] SELECT case_type, AVG(DATE_PART('day', date_closed - date_opened)) AS average_duration_days FROM legal_services.cases WHERE status = 'Closed' AND date_closed IS NOT NULL GROUP BY case_type;

[User] Exclude case types where the average duration is less than 100 days and order the results by average duration descending.

[Assistant] SELECT case_type, AVG(DATE_PART('day', date_closed - date_opened)) AS average_duration_days FROM legal_services.cases WHERE status = 'Closed' AND date_closed IS NOT NULL GROUP BY case_type HAVING AVG(DATE_PART('day', date_closed - date_opened)) >= 100 ORDER BY average_duration_days 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 smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )

[User] Show me the top 5 smart money addresses by profit on the Ethereum chain, along with their most profitable token and ROI, but only include addresses with a realized profit ratio above 70%.

[Assistant] SELECT address, most_profit_token, roi FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 70 ORDER BY profit DESC LIMIT 5;

[User] Can you also include their rank and filter to only show addresses with ROI greater than 50%?

[Assistant] SELECT address, most_profit_token, roi, rank FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 70 AND roi > 50 ORDER BY profit DESC LIMIT 5;

[User] How many distinct addresses achieved a realized_ratio higher than 0.9 last month?

[Assistant] SELECT COUNT(DISTINCT address) FROM smart_money_profit WHERE realized_ratio > 0.9;

[User] Can you also break down the count by chain?

[Assistant] SELECT chain, COUNT(DISTINCT address) AS address_count FROM smart_money_profit WHERE realized_ratio > 0.9 GROUP BY chain;

[User] Show the top 3 addresses by ROI on the Polygon chain, including profit and the most profitable token.

[Assistant] SELECT address, roi, profit, most_profit_token FROM smart_money_profit WHERE chain = 'Polygon' ORDER BY roi DESC LIMIT 3;

[User] Now, also include addresses from Arbitrum and display the chain in the results.

[Assistant] SELECT address, chain, roi, profit, most_profit_token FROM smart_money_profit WHERE chain IN ('Polygon', 'Arbitrum') ORDER BY roi DESC LIMIT 3;

[User] I got repeated addresses from both chains. Please show the top 3 per chain separately.

[Assistant] SELECT address, chain, roi, profit, most_profit_token FROM ( SELECT address, chain, roi, profit, most_profit_token, ROW_NUMBER() OVER (PARTITION BY chain ORDER BY roi DESC) AS rn FROM smart_money_profit WHERE chain IN ('Polygon', 'Arbitrum') ) t WHERE rn <= 3 ORDER BY chain, roi DESC;

[User] Add the last_trade_time to your output.

[Assistant] SELECT address, chain, roi, profit, most_profit_token, last_trade_time FROM ( SELECT address, chain, roi, profit, most_profit_token, last_trade_time, ROW_NUMBER() OVER (PARTITION BY chain ORDER BY roi DESC) AS rn FROM smart_money_profit WHERE chain IN ('Polygon', 'Arbitrum') ) t WHERE rn <= 3 ORDER BY chain, roi DESC;

[User] Calculate the average realized_ratio across all addresses.

[Assistant]
SELECT AVG(realized_ratio) AS average_realized_ratio
FROM smart_money_profit;

[User] Show me the top 5 smart money addresses by profit on the Ethereum chain, along with their most profitable token and ROI, but only include addresses with a realized profit ratio above 80%.

[Assistant] SELECT address, most_profit_token, roi FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 80 ORDER BY profit DESC LIMIT 5;

[User] Can you also include the last trade time for these addresses and filter to only show results with ROI greater than 100%?

[Assistant] SELECT address, most_profit_token, roi, last_trade_time FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 80 AND roi > 100 ORDER BY profit 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 transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] Count the number of passengers in each month of the year 2024 based on their created_at date.

[Assistant]
SELECT EXTRACT(MONTH FROM created_at) AS month, COUNT(*) AS passenger_count
FROM transportation.passengers
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01'
GROUP BY EXTRACT(MONTH FROM created_at)
ORDER BY month;

[User] Now, only include months where the passenger_count exceeds 50.

[Assistant]
SELECT EXTRACT(MONTH FROM created_at) AS month, COUNT(*) AS passenger_count
FROM transportation.passengers
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01'
GROUP BY EXTRACT(MONTH FROM created_at)
HAVING COUNT(*) > 50
ORDER BY month;

[User] I want to see how many passengers were created each month.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers GROUP BY month;

[User] Only include months after January 2021.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers WHERE created_at >= '2021-01-01' GROUP BY month;

[User] Also exclude records where email is NULL.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers WHERE created_at >= '2021-01-01' AND email IS NOT NULL GROUP BY month;

[User] Sort the results in descending order by passenger_count and limit to the top 6 months.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers WHERE created_at >= '2021-01-01' AND email IS NOT NULL GROUP BY month ORDER BY passenger_count DESC LIMIT 6;

[User] Show each pair of passengers who share the same loyalty_program_id but have different registration times. Return p1.first_name AS earlier, p2.first_name AS later, and loyalty_program_id.

[Assistant]
SELECT p1.first_name AS earlier, p2.first_name AS later, p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at;

[User] Actually, only include pairs where the earlier registration happened before '2023-01-01'.

[Assistant]
SELECT p1.first_name AS earlier, p2.first_name AS later, p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at
WHERE p1.created_at < '2023-01-01';

[User] List each passenger's first_name, last_name along with another passenger's first_name and last_name who share the same loyalty_program_id. Label them as member and peer.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id;

[User] I only want pairs where the member registered before the peer and include their created_at timestamps.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last,
       p1.created_at AS member_created, p2.created_at AS peer_created
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
  AND p1.created_at < p2.created_at;

[User] Then sort the result by member_created ascending and peer_created descending.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last,
       p1.created_at AS member_created, p2.created_at AS peer_created
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
  AND p1.created_at < p2.created_at
ORDER BY p1.created_at ASC, p2.created_at DESC;

[User] List pairs of passengers where one registered before another, including both their first names, created_at timestamps, and loyalty_program_id.

[Assistant]
SELECT p1.first_name AS earlier,
       p2.first_name AS later,
       p1.created_at AS earlier_created,
       p2.created_at AS later_created,
       p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at;

[User] Only include pairs where both passengers are in a loyalty_program and the time difference between their registrations is more than 30 days.

[Assistant]
SELECT p1.first_name AS earlier,
       p2.first_name AS later,
       p1.created_at AS earlier_created,
       p2.created_at AS later_created,
       p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at
WHERE p1.loyalty_program_id IS NOT NULL
  AND p2.loyalty_program_id IS NOT NULL
  AND p2.created_at - p1.created_at > INTERVAL '30 days';

[User] Now also order the results by the time difference descending and limit to the top 5.

[Assistant]
SELECT p1.first_name AS earlier,
       p2.first_name AS later,
       p1.created_at AS earlier_created,
       p2.created_at AS later_created,
       p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at
WHERE p1.loyalty_program_id IS NOT NULL
  AND p2.loyalty_program_id IS NOT NULL
  AND p2.created_at - p1.created_at > INTERVAL '30 days'
ORDER BY (p2.created_at - p1.created_at) DESC
LIMIT 5;

[User] List the first and last names of passengers who share the same loyalty_program_id with at least one other passenger.

[Assistant]
SELECT DISTINCT p1.first_name, p1.last_name
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id AND p1.passenger_id <> p2.passenger_id
WHERE p1.loyalty_program_id IS NOT NULL;

[User] Now refine this list to only include passengers who joined after January 1, 2023.

[Assistant]
SELECT DISTINCT p1.first_name, p1.last_name
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id AND p1.passenger_id <> p2.passenger_id
WHERE p1.loyalty_program_id IS NOT NULL
  AND p1.created_at >= '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Index 'suppliers'. Mapping: { properties: { supplier_id: { type: 'keyword' }, supplier_name: { type: 'text', fields: { keyword: { type: 'keyword', ignore_above: 256 } } }, address: { type: 'text' }, country: { type: 'keyword' }, contact_person: { type: 'text', index: false }, contact_email: { type: 'keyword' }, quality_rating: { type: 'float' }, certified_date: { type: 'date' } } }. Document _id can be supplier_id.

[User] 특정 품질 등급 이상의 공급업체를 조회하고 싶습니다. 품질 등급, 공급업체 이름, 국가를 포함해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "range": {
      "quality_rating": {
        "gte": 4.0
      }
    }
  },
  "_source": ["supplier_name", "country", "quality_rating"]
}

[User] 특정 국가에 속한 공급업체만 추가로 필터링하고 싶습니다. 예를 들어, 일본 소속 공급업체로 제한하고 싶습니다.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "quality_rating": {
              "gte": 4.0
            }
          }
        },
        {
          "term": {
            "country": "Japan"
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "country", "quality_rating"]
}

[User] 연락처 담당자 이름과 인증 날짜도 결과에 포함해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "quality_rating": {
              "gte": 4.0
            }
          }
        },
        {
          "term": {
            "country": "Japan"
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "country", "quality_rating", "contact_person", "certified_date"]
}

[User] 인증 날짜를 기준으로 오름차순 정렬을 추가해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "quality_rating": {
              "gte": 4.0
            }
          }
        },
        {
          "term": {
            "country": "Japan"
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "country", "quality_rating", "contact_person", "certified_date"],
  "sort": [
    {
      "certified_date": {
        "order": "asc"
      }
    }
  ]
}

[User] 특정 국가의 모든 공급업체 정보를 조회하고 싶습니다. 국가 이름, 공급업체 이름, 주소, 품질 등급을 포함해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "term": {
      "country": "Korea"
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating"]
}

[User] 품질 등급이 3.5 이상인 공급업체만 보고 싶습니다. 어떻게 수정해야 하나요?

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating"]
}

[User] 인증 날짜가 2020년 이후인 공급업체만 추가로 필터링하고 싶습니다.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        },
        {
          "range": {
            "certified_date": {
              "gte": "2020-01-01"
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating", "certified_date"]
}

[User] 결과를 품질 등급 기준으로 내림차순 정렬해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        },
        {
          "range": {
            "certified_date": {
              "gte": "2020-01-01"
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating", "certified_date"],
  "sort": [
    {
      "quality_rating": {
        "order": "desc"
      }
    }
  ]
}

[User] 특정 공급업체 ID로 공급업체의 세부 정보를 조회하고 싶습니다. 모든 필드를 포함해 주세요.

[Assistant] GET suppliers/_doc/{supplier_id}

[User] 만약 여러 공급업체 ID를 한 번에 조회하고 싶다면 어떻게 해야 하나요?

[Assistant]
GET suppliers/_search
{
  "query": {
    "terms": {
      "supplier_id": ["id1", "id2", "id3"]
    }
  }
}

[User] 조회 결과에서 공급업체 이름과 연락처 이메일만 보고 싶습니다.

[Assistant]
GET suppliers/_search
{
  "query": {
    "terms": {
      "supplier_id": ["id1", "id2", "id3"]
    }
  },
  "_source": ["supplier_name", "contact_email"]
}

[User] 결과를 공급업체 이름 기준으로 오름차순 정렬해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "terms": {
      "supplier_id": ["id1", "id2", "id3"]
    }
  },
  "_source": ["supplier_name", "contact_email"],
  "sort": [
    {
      "supplier_name.keyword": {
        "order": "asc"
      }
    }
  ]
}