System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] For each service category, find the total number of notifications sent related to applications of services in that category.

[Assistant]
SELECT s.category, COUNT(n.notification_id) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
JOIN government_services.services s ON a.service_id = s.service_id
GROUP BY s.category;

[User] Exclude notifications with status 'Failed' and 'Cancelled'.

[Assistant]
SELECT s.category, COUNT(n.notification_id) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE n.status NOT IN ('Failed', 'Cancelled')
GROUP BY s.category;

[User] Only include categories with at least 10 notifications.

[Assistant]
SELECT s.category, COUNT(n.notification_id) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE n.status NOT IN ('Failed', 'Cancelled')
GROUP BY s.category
HAVING COUNT(n.notification_id) >= 10;

[User] Also, order the results by notification_count descending and limit to the top 5 categories.

[Assistant]
SELECT s.category, COUNT(n.notification_id) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE n.status NOT IN ('Failed', 'Cancelled')
GROUP BY s.category
HAVING COUNT(n.notification_id) >= 10
ORDER BY notification_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.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )

[User] Show the number of wallets created each month in 2024, showing the year and month.

[Assistant] SELECT EXTRACT(YEAR FROM created_at) AS year, EXTRACT(MONTH FROM created_at) AS month, COUNT(*) FROM wallets WHERE EXTRACT(YEAR FROM created_at) = 2024 GROUP BY 1, 2 ORDER BY 1, 2


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_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.metadata ( metadata_id text, asset_id text, key text, value text )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] List all unspent UTXOs, including their utxo_id, address, amount, and transaction_id.

[Assistant]
SELECT utxo_id, address, amount, transaction_id
FROM trading_platform.utxos
WHERE spent = false;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
CREATE TABLE transportation.fuel_logs ( fuel_log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, trip_id character varying(64), log_timestamp timestamp with time zone NOT NULL, fuel_type character varying(32) NOT NULL, quantity numeric(10, 3) NOT NULL, unit character varying(16) NOT NULL, cost_per_unit numeric(8, 4), total_cost numeric(10, 2) NOT NULL, odometer_reading integer, location_id character varying(64), PRIMARY KEY (fuel_log_id) )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

[User] List all diesel fuel logs from the last 3 months with their vehicle details and total cost.

[Assistant] SELECT f.fuel_log_id, f.log_timestamp, v.vehicle_id, v.make, v.model, f.quantity, f.total_cost FROM transportation.fuel_logs f JOIN transportation.vehicles v ON f.vehicle_id = v.vehicle_id WHERE f.fuel_type = 'diesel' AND f.log_timestamp >= NOW() - INTERVAL '3 months' ORDER BY f.log_timestamp DESC;

[User] Include the trip ID and origin location ID for these fuel logs if available.

[Assistant] SELECT f.fuel_log_id, f.log_timestamp, v.vehicle_id, v.make, v.model, f.quantity, f.total_cost, f.trip_id, t.origin_location_id FROM transportation.fuel_logs f JOIN transportation.vehicles v ON f.vehicle_id = v.vehicle_id LEFT JOIN transportation.trips t ON f.trip_id = t.trip_id WHERE f.fuel_type = 'diesel' AND f.log_timestamp >= NOW() - INTERVAL '3 months' ORDER BY f.log_timestamp DESC;

[User] Now filter to only show logs where the quantity is more than 50 liters and include the location name if available.

[Assistant] SELECT f.fuel_log_id, f.log_timestamp, v.vehicle_id, v.make, v.model, f.quantity, f.total_cost, f.trip_id, t.origin_location_id, l.name AS location_name FROM transportation.fuel_logs f JOIN transportation.vehicles v ON f.vehicle_id = v.vehicle_id LEFT JOIN transportation.trips t ON f.trip_id = t.trip_id LEFT JOIN transportation.locations l ON f.location_id = l.location_id WHERE f.fuel_type = 'diesel' AND f.log_timestamp >= NOW() - INTERVAL '3 months' AND f.quantity > 50 ORDER BY f.log_timestamp DESC;

[User] Actually, I only want to see logs from vehicles that are currently active.

[Assistant] SELECT f.fuel_log_id, f.log_timestamp, v.vehicle_id, v.make, v.model, f.quantity, f.total_cost, f.trip_id, t.origin_location_id, l.name AS location_name FROM transportation.fuel_logs f JOIN transportation.vehicles v ON f.vehicle_id = v.vehicle_id LEFT JOIN transportation.trips t ON f.trip_id = t.trip_id LEFT JOIN transportation.locations l ON f.location_id = l.location_id WHERE f.fuel_type = 'diesel' AND f.log_timestamp >= NOW() - INTERVAL '3 months' AND f.quantity > 50 AND v.status = 'active' ORDER BY f.log_timestamp 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 web3.contracts (
    contract_id character varying(64) NOT NULL,  -- unique identifier for the contract
    address character varying(128) NOT NULL, -- address of the deployed contract
    abi text NOT NULL, -- application binary interface of the contract
    bytecode text NOT NULL, -- bytecode of the contract
    deployer_address character varying(128) NOT NULL, -- address of the deployer
    deployed_at timestamp NOT NULL, -- time when the contract was deployed
    network_id character varying(64) NOT NULL, -- identifier of the network where the contract is deployed
    status character varying(32) NOT NULL, -- status of the contract (e.g., active, deprecated)
    PRIMARY KEY (contract_id)
)

[User] For each distinct deployer address, how many contracts have they deployed and what is the most recent deployment time? Please show deployer_address, contract_count, and latest_deployed_at.

[Assistant]
SELECT deployer_address, COUNT(*) AS contract_count, MAX(deployed_at) AS latest_deployed_at
FROM web3.contracts
GROUP BY deployer_address;


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
// db.createCollection('stations')
// Optional: Add unique index: db.stations.createIndex({ station_id: 1 }, { unique: true })
{
  _id: ObjectId(), // Auto-generated MongoDB ID
  station_id: "station_xyz", // String (unique identifier, corresponds to SQL PK)
  station_name: "Grand Central Terminal", // String
  city: "New York", // String
  state_province: "NY", // String
  country_code: "USA", // String
  address: "89 E 42nd St, New York, NY 10017", // String
  timezone: "America/New_York", // String
  number_of_platforms: 44, // Int32
  created_at: ISODate("2023-01-15T10:00:00Z"), // Date
  last_updated_at: ISODate("2023-10-28T15:30:00Z") // Date
}
// db.createCollection('trains')
// Optional: db.trains.createIndex({ train_id: 1 }, { unique: true })
// Optional: db.trains.createIndex({ train_number: 1 }, { unique: true })
{
  _id: ObjectId(),
  train_id: "train_789", // String (unique)
  train_number: "Acela 2151", // String (unique)
  model: "Siemens Velaro", // String
  manufacturer: "Siemens", // String
  year_manufactured: 2010, // Int32
  capacity: 304, // Int32
  status: "Active", // String ('Active', 'Maintenance', 'Retired')
  last_maintenance_date: ISODate("2023-09-15"), // Date (Date part only relevant)
  next_maintenance_date: ISODate("2024-03-15") // Date (Date part only relevant)
}
// db.createCollection('bookings')
// Optional: db.bookings.createIndex({ booking_id: 1 }, { unique: true })
// Optional: db.bookings.createIndex({ passenger_id: 1 })
// Optional: db.bookings.createIndex({ schedule_id: 1 })
{
  _id: ObjectId(),
  booking_id: "book_zyx", // String (unique)
  passenger_id: "pass_pqr", // String (references passengers.passenger_id)
  schedule_id: "sched_1122", // String (references schedules.schedule_id)
  booking_datetime: ISODate("2024-04-15T14:30:00Z"), // Date
  status: "Confirmed", // String ('Confirmed', 'Cancelled', 'Pending')
  total_price: 150.75, // Decimal128 or Double
  currency_code: "USD", // String
  special_requests: "Wheelchair assistance required at origin" // String
}
// db.createCollection('staff')
// Optional: db.staff.createIndex({ staff_id: 1 }, { unique: true })
// Optional: db.staff.createIndex({ employee_number: 1 }, { unique: true })
// Optional: db.staff.createIndex({ contact_email: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  staff_id: "staff_mno", // String (unique)
  first_name: "Bob", // String
  last_name: "Jones", // String
  role: "Conductor", // String
  primary_station_id: null, // String (references stations.station_id, nullable)
  employee_number: "E12345", // String (unique)
  hire_date: ISODate("2018-06-01"), // Date
  contact_email: "bob.jones@example-rail.com", // String (unique, sparse)
  contact_phone: "+15559876543", // String
  is_active: true // Boolean
}

[User] Can you assist me in finding all staff members assigned to a specific station with station_id 'station_xyz', including the station details and their roles?

[Assistant]
db.staff.aggregate([
    {
        $lookup: {
            from: 'stations',
            localField: 'primary_station_id',
            foreignField: 'station_id',
            as: 'station_details'
        }
    },
    {
        $match: {
            'primary_station_id': 'station_xyz'
        }
    },
    {
        $project: {
            staff_id: 1,
            first_name: 1,
            last_name: 1,
            role: 1,
            'station_details.station_name': 1,
            'station_details.city': 1
        }
    }
]);

[User] I noticed that some staff might not have a primary station assigned. Can you revise the query to include staff who might be associated with the station in other ways, if possible?

[Assistant]
db.staff.aggregate([
    {
        $lookup: {
            from: 'stations',
            localField: 'primary_station_id',
            foreignField: 'station_id',
            as: 'station_details'
        }
    },
    {
        $match: {
            $or: [
                { 'primary_station_id': 'station_xyz' },
                { 'primary_station_id': null }
            ]
        }
    },
    {
        $project: {
            staff_id: 1,
            first_name: 1,
            last_name: 1,
            role: 1,
            'station_details.station_name': 1,
            'station_details.city': 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 trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )

[User] Show each order with its previous order timestamp for the same user.

[Assistant]
SELECT o.order_id, o.user_id, o.created_at AS current_time, MAX(prev.created_at) AS previous_time
FROM trading_platform.orders o
LEFT JOIN trading_platform.orders prev
  ON o.user_id = prev.user_id
  AND prev.created_at < o.created_at
GROUP BY o.order_id, o.user_id, o.created_at
ORDER BY o.user_id, o.created_at;

[User] Filter to include only those orders where the gap between current_time and previous_time exceeds one day.

[Assistant]
SELECT *
FROM (
  SELECT o.order_id,
         o.user_id,
         o.created_at AS current_time,
         MAX(prev.created_at) AS previous_time
  FROM trading_platform.orders o
  LEFT JOIN trading_platform.orders prev
    ON o.user_id = prev.user_id
    AND prev.created_at < o.created_at
  GROUP BY o.order_id, o.user_id, o.created_at
) t
WHERE t.current_time - t.previous_time > INTERVAL '1 day'
ORDER BY t.user_id, t.current_time;


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.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)

[User] List all post IDs and the corresponding hashtag names where posts were created near latitude 40.0 and longitude -74.0.

[Assistant]
SELECT p.post_id, h.tag_name
FROM social_media.posts p
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE ABS(p.location_lat - 40.0) < 0.1 AND ABS(p.location_lon + 74.0) < 0.1;

[User] Only show the results where the hashtag name contains the word 'event'.

[Assistant]
SELECT p.post_id, h.tag_name
FROM social_media.posts p
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE ABS(p.location_lat - 40.0) < 0.1 AND ABS(p.location_lon + 74.0) < 0.1
  AND h.tag_name ILIKE '%event%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id character varying(64) NOT NULL, invoice_number character varying(100) UNIQUE NOT NULL, client_id character varying(64) NOT NULL, case_id character varying(64), issue_date date NOT NULL, due_date date NOT NULL, total_amount numeric(12, 2) NOT NULL, amount_paid numeric(12, 2) DEFAULT 0.00, status character varying(50) NOT NULL, payment_date timestamp, notes text, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (invoice_id) )

[User] List all pairs of invoices for the same client where one invoice is overdue and the other is paid. Show the client_id, the overdue invoice number, and the paid invoice number.

[Assistant]
SELECT i1.client_id, i1.invoice_number AS overdue_invoice, i2.invoice_number AS paid_invoice
FROM legal_services.invoices i1
JOIN legal_services.invoices i2 ON i1.client_id = i2.client_id
WHERE i1.status = 'Overdue'
  AND i2.status = 'Paid';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, 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] Show me the usernames and email addresses of all users who have commented on posts that contain the hashtag 'music'.

[Assistant]
SELECT DISTINCT u.username, u.email
FROM social_media.comments c
JOIN social_media.posts p ON c.post_id = p.post_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
JOIN social_media.users u ON c.user_id = u.user_id
WHERE h.tag_name = 'music';

[User] Only include users whose profile has a location specified.

[Assistant]
SELECT DISTINCT u.username, u.email
FROM social_media.comments c
JOIN social_media.posts p ON c.post_id = p.post_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
JOIN social_media.users u ON c.user_id = u.user_id
WHERE h.tag_name = 'music'
  AND u.location IS NOT NULL;

[User] Now, also show their full names and sort the results alphabetically by full name.

[Assistant]
SELECT DISTINCT u.username, u.email, u.full_name
FROM social_media.comments c
JOIN social_media.posts p ON c.post_id = p.post_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
JOIN social_media.users u ON c.user_id = u.user_id
WHERE h.tag_name = 'music'
  AND u.location IS NOT NULL
ORDER BY u.full_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 gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] Find players who own items with rarity 'Rare' or higher ('Epic', 'Legendary') and list their usernames.

[Assistant] SELECT DISTINCT T1.username FROM players AS T1 INNER JOIN player_inventory AS T2 ON T1.player_id = T2.player_id INNER JOIN items AS T3 ON T2.item_id = T3.item_id WHERE T3.rarity IN ('Rare', 'Epic', 'Legendary');

[User] Filter this list further to only include players who acquired these items after '2024-01-01'.

[Assistant] SELECT DISTINCT T1.username FROM players AS T1 INNER JOIN player_inventory AS T2 ON T1.player_id = T2.player_id INNER JOIN items AS T3 ON T2.item_id = T3.item_id WHERE T3.rarity IN ('Rare', 'Epic', 'Legendary') AND T2.acquired_at > '2024-01-01';


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

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

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


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.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] List the accessible service locations and active services offered by the same agency where the service's average processing time is under 5 days. Include the location name, city, state, service name, and processing time.

[Assistant]
SELECT
  sl.location_name,
  sl.city,
  sl.state,
  s.service_name,
  s.average_processing_time_days
FROM
  government_services.service_locations sl
  JOIN government_services.services s
    ON sl.agency_id = s.agency_id
WHERE
  sl.is_accessible = TRUE
  AND s.is_active = TRUE
  AND s.average_processing_time_days < 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 healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text PRIMARY KEY, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] Show me the full names and specialties of all doctors who have issued a prescription for a patient enrolled in an insurance plan provided by 'Global Health'.

[Assistant]
SELECT DISTINCT d.first_name, d.last_name, d.specialty
FROM healthcare.doctors d
JOIN healthcare.prescriptions p ON p.doctor_id = d.doctor_id
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE ip.insurance_provider = 'Global Health';

[User] Instead, only show those doctors who prescribed medication in 2024.

[Assistant]
SELECT DISTINCT d.first_name, d.last_name, d.specialty
FROM healthcare.doctors d
JOIN healthcare.prescriptions p ON p.doctor_id = d.doctor_id
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE ip.insurance_provider = 'Global Health'
AND EXTRACT(YEAR FROM p.prescription_date) = 2024;

[User] I just want to see the specialties and count how many such doctors issued prescriptions for these patients in 2024.

[Assistant]
SELECT d.specialty, COUNT(DISTINCT d.doctor_id) AS doctor_count
FROM healthcare.doctors d
JOIN healthcare.prescriptions p ON p.doctor_id = d.doctor_id
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE ip.insurance_provider = 'Global Health'
AND EXTRACT(YEAR FROM p.prescription_date) = 2024
GROUP BY d.specialty;

[User] Sorry, can you only count those doctors with at least 3 prescriptions for patients on 'Global Health' plans in 2024?

[Assistant]
SELECT d.specialty, COUNT(DISTINCT d.doctor_id) AS doctor_count
FROM healthcare.doctors d
JOIN healthcare.prescriptions p ON p.doctor_id = d.doctor_id
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE ip.insurance_provider = 'Global Health'
AND EXTRACT(YEAR FROM p.prescription_date) = 2024
GROUP BY d.specialty
HAVING COUNT(*) >= 3;


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

[User] What is the highest score achieved in any session for each player on each game?

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id;

[User] Show only the player/game combinations where the highest score is at least 500.

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500;

[User] Also include the number of sessions for each player/game pair.

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score, COUNT(*) AS session_count FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), address text NOT NULL, city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, status character varying(32) NOT NULL, risk_profile character varying(50), PRIMARY KEY (customer_id) )
CREATE TABLE financial_services.accounts ( account_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, account_number character varying(128) NOT NULL UNIQUE, account_type character varying(50) NOT NULL, balance numeric(19, 4) NOT NULL DEFAULT 0.00, currency character varying(3) NOT NULL, opened_date date NOT NULL, status character varying(32) NOT NULL, interest_rate numeric(5, 4), last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) )
CREATE TABLE financial_services.securities ( security_id character varying(64) NOT NULL, ticker_symbol character varying(20) NOT NULL UNIQUE, isin_code character varying(12) UNIQUE, cusip_code character varying(9) UNIQUE, security_name text NOT NULL, security_type character varying(50) NOT NULL, exchange character varying(50), currency character varying(3) NOT NULL, issuer_name character varying(255), sector character varying(100), last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (security_id) )
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, department character varying(100), branch_id character varying(64), email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, manager_id character varying(64), status character varying(32) NOT NULL, PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )

[User] List the first name, last name, and job title for all employees.

[Assistant] SELECT first_name, last_name, job_title FROM financial_services.employees;

[User] Only show employees who are currently active.

[Assistant] SELECT first_name, last_name, job_title FROM financial_services.employees WHERE status = 'Active';

[User] Additionally, include their email address in the result.

[Assistant] SELECT first_name, last_name, job_title, email FROM financial_services.employees WHERE status = 'Active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )

[User] For each route that originates from a location of type 'Port', list the route number, the name of the origin location, and the total distance accumulated from all completed trips on this route.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name;

[User] Now, only include routes where the accumulated distance is greater than 5000 kilometers and order the results by accumulated distance descending.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name
HAVING
  SUM(t.distance_km) > 5000
ORDER BY
  total_accumulated_distance DESC;

[User] Also include the number of completed trips for each of these routes and filter further to only show routes that have had more than 5 completed trips.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance,
  COUNT(t.trip_id) AS completed_trip_count
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name
HAVING
  SUM(t.distance_km) > 5000 AND COUNT(t.trip_id) > 5
ORDER BY
  total_accumulated_distance DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )

[User] I want to find pairs of developers who share the same website domain. Show each pair's names and the domain.

[Assistant]
SELECT d1.name AS dev1,
       d2.name AS dev2,
       SPLIT_PART(SPLIT_PART(d1.website, '://', 2), '/', 1) AS domain
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON SPLIT_PART(SPLIT_PART(d1.website, '://', 2), '/', 1) = SPLIT_PART(SPLIT_PART(d2.website, '://', 2), '/', 1)
 AND d1.developer_id < d2.developer_id;

[User] Now only include domains that have at least 3 developers.

[Assistant]
WITH base AS (
  SELECT developer_id, name,
         SPLIT_PART(SPLIT_PART(website, '://', 2), '/', 1) AS domain
  FROM gaming_technology.developers
  WHERE website IS NOT NULL
    AND website <> ''
), popular AS (
  SELECT domain
  FROM base
  GROUP BY domain
  HAVING COUNT(*) >= 3
)
SELECT b1.name AS dev1,
       b2.name AS dev2,
       b1.domain
FROM base b1
JOIN base b2
  ON b1.domain = b2.domain
 AND b1.developer_id < b2.developer_id
JOIN popular p
  ON b1.domain = p.domain;

[User] Exclude the 'localhost' domain.

[Assistant]
WITH base AS (
  SELECT developer_id, name,
         SPLIT_PART(SPLIT_PART(website, '://', 2), '/', 1) AS domain
  FROM gaming_technology.developers
  WHERE website IS NOT NULL
    AND website <> ''
), popular AS (
  SELECT domain
  FROM base
  GROUP BY domain
  HAVING COUNT(*) >= 3
)
SELECT b1.name AS dev1,
       b2.name AS dev2,
       b1.domain
FROM base b1
JOIN base b2
  ON b1.domain = b2.domain
 AND b1.developer_id < b2.developer_id
JOIN popular p
  ON b1.domain = p.domain
WHERE b1.domain <> 'localhost';

[User] Order the results by domain ascending and limit to 10 rows.

[Assistant]
WITH base AS (
  SELECT developer_id, name,
         SPLIT_PART(SPLIT_PART(website, '://', 2), '/', 1) AS domain
  FROM gaming_technology.developers
  WHERE website IS NOT NULL
    AND website <> ''
), popular AS (
  SELECT domain
  FROM base
  GROUP BY domain
  HAVING COUNT(*) >= 3
)
SELECT b1.name AS dev1,
       b2.name AS dev2,
       b1.domain
FROM base b1
JOIN base b2
  ON b1.domain = b2.domain
 AND b1.developer_id < b2.developer_id
JOIN popular p
  ON b1.domain = p.domain
WHERE b1.domain <> 'localhost'
ORDER BY b1.domain ASC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] List application reference numbers and the total amount paid for each application that has at least one completed payment.

[Assistant] SELECT a.reference_number, SUM(p.amount) AS total_paid FROM government_services.applications AS a JOIN government_services.payments AS p ON a.application_id = p.application_id WHERE p.status = 'Completed' GROUP BY a.reference_number;

[User] Also include the citizen's first and last name who submitted the application.

[Assistant] SELECT c.first_name, c.last_name, a.reference_number, SUM(p.amount) AS total_paid FROM government_services.applications AS a JOIN government_services.payments AS p ON a.application_id = p.application_id JOIN government_services.citizens AS c ON a.citizen_id = c.citizen_id WHERE p.status = 'Completed' GROUP BY c.first_name, c.last_name, a.reference_number;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )

[User] Find the top 3 staff members who have responded to the most public reviews. Include their staff_id, first_name, last_name, and the count of responses.

[Assistant]
SELECT
  s.staff_id,
  s.first_name,
  s.last_name,
  COUNT(*) AS response_count
FROM hospitality_technology.staff AS s
JOIN hospitality_technology.reviews AS r
  ON s.staff_id = r.response_staff_id
WHERE r.is_public = TRUE
  AND r.response_staff_id IS NOT NULL
GROUP BY s.staff_id, s.first_name, s.last_name
ORDER BY response_count DESC
LIMIT 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )

[User] Can you write a query that retrieves each server's name, its region, and the highest current player count observed in that region?

[Assistant]
SELECT s.server_name, s.region, m.max_current_players
FROM gaming_technology.servers s
JOIN (
  SELECT region, MAX(current_players) AS max_current_players
  FROM gaming_technology.servers
  GROUP BY region
) m ON s.region = m.region;

[User] Actually, only include regions where that maximum current player count exceeds 50.

[Assistant]
SELECT s.server_name, s.region, m.max_current_players
FROM gaming_technology.servers s
JOIN (
  SELECT region, MAX(current_players) AS max_current_players
  FROM gaming_technology.servers
  GROUP BY region
  HAVING MAX(current_players) > 50
) m ON s.region = m.region;

[User] Also, exclude any servers that are already full (where current_players equals max_players).

[Assistant]
SELECT s.server_name, s.region, m.max_current_players
FROM gaming_technology.servers s
JOIN (
  SELECT region, MAX(current_players) AS max_current_players
  FROM gaming_technology.servers
  GROUP BY region
  HAVING MAX(current_players) > 50
) m ON s.region = m.region
WHERE s.current_players < s.max_players;

[User] Finally, sort the results by region ascending and then by the maximum current players in descending order.

[Assistant]
SELECT s.server_name, s.region, m.max_current_players
FROM gaming_technology.servers s
JOIN (
  SELECT region, MAX(current_players) AS max_current_players
  FROM gaming_technology.servers
  GROUP BY region
  HAVING MAX(current_players) > 50
) m ON s.region = m.region
WHERE s.current_players < s.max_players
ORDER BY s.region ASC, m.max_current_players 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 insurance.premium_payments ( payment_id.text, policy_id.text, customer_id.text, payment_date.timestamp, amount_paid.numeric, payment_method.text, transaction_reference.text, due_date.date, payment_period_start.date, payment_period_end.date, status.text )

[User] Show me all premium payments made via credit card in the last 30 days, along with their payment amounts and transaction references.

[Assistant] SELECT payment_id, amount_paid, transaction_reference FROM insurance.premium_payments WHERE payment_method = 'credit card' AND payment_date >= CURRENT_DATE - INTERVAL '30 days';

[User] Now filter these payments to only show those with amounts greater than $500 and include the payment dates.

[Assistant] SELECT payment_id, amount_paid, transaction_reference, payment_date FROM insurance.premium_payments WHERE payment_method = 'credit card' AND payment_date >= CURRENT_DATE - INTERVAL '30 days' AND amount_paid > 500;

[User] I also want to see the count of such payments per customer_id.

[Assistant] SELECT customer_id, COUNT(*) as payment_count FROM insurance.premium_payments WHERE payment_method = 'credit card' AND payment_date >= CURRENT_DATE - INTERVAL '30 days' AND amount_paid > 500 GROUP BY customer_id;

[User] Finally, show me the average payment amount for these filtered payments.

[Assistant] SELECT AVG(amount_paid) as average_payment FROM insurance.premium_payments WHERE payment_method = 'credit card' AND payment_date >= CURRENT_DATE - INTERVAL '30 days' AND amount_paid > 500;


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

[User] Which Avalanche token has the largest total supply currently held by wallets, and who is its creator?

[Assistant]
SELECT tb.tick, SUM(tb.amount) AS total_amount, ti.creator
FROM token_balances_avalanche tb
JOIN token_info_avalanche ti ON tb.tick = ti.tick
GROUP BY tb.tick, ti.creator
ORDER BY total_amount DESC
LIMIT 1;

[User] Can you also provide the max_supply and updated_timestamp for that token?

[Assistant]
SELECT tb.tick, SUM(tb.amount) AS total_amount, ti.creator, ti.max_supply, ti.updated_timestamp
FROM token_balances_avalanche tb
JOIN token_info_avalanche ti ON tb.tick = ti.tick
GROUP BY tb.tick, ti.creator, ti.max_supply, ti.updated_timestamp
ORDER BY total_amount DESC
LIMIT 1;

[User] Instead, I want to see the top 3 tokens by total supply, including their tick, creator, max_supply, and updated_timestamp.

[Assistant]
SELECT tb.tick, SUM(tb.amount) AS total_amount, ti.creator, ti.max_supply, ti.updated_timestamp
FROM token_balances_avalanche tb
JOIN token_info_avalanche ti ON tb.tick = ti.tick
GROUP BY tb.tick, ti.creator, ti.max_supply, ti.updated_timestamp
ORDER BY total_amount DESC
LIMIT 3;

[User] Now, can you also add the number of unique wallets currently holding each token in the results?

[Assistant]
SELECT tb.tick, SUM(tb.amount) AS total_amount, ti.creator, ti.max_supply, ti.updated_timestamp, COUNT(DISTINCT tb.wallet_address) AS holder_count
FROM token_balances_avalanche tb
JOIN token_info_avalanche ti ON tb.tick = ti.tick
GROUP BY tb.tick, ti.creator, ti.max_supply, ti.updated_timestamp
ORDER BY total_amount DESC
LIMIT 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )

[User] Give me a breakdown of available services by unit, with the count of services and the average price, grouped by property.

[Assistant] SELECT property_id, unit, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit;

[User] I only want results where the average price is above 50.

[Assistant] SELECT property_id, unit, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit HAVING AVG(price) > 50;

[User] Actually, also include the department for each unit in the result.

[Assistant] SELECT property_id, unit, department, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit, department HAVING AVG(price) > 50;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )

[User] Can you show me the email addresses of all drivers whose status is 'Inactive'?

[Assistant] SELECT driver_id, first_name, last_name, email FROM transportation.drivers WHERE status = 'Inactive';

[User] I see there are some missing emails. Only include drivers who actually have an email address.

[Assistant] SELECT driver_id, first_name, last_name, email FROM transportation.drivers WHERE status = 'Inactive' AND email IS NOT NULL AND email <> '';

[User] Also add their hire date to the results and order by hire date ascending.

[Assistant] SELECT driver_id, first_name, last_name, email, hire_date FROM transportation.drivers WHERE status = 'Inactive' AND email IS NOT NULL AND email <> '' ORDER BY hire_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 financial_services.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address.text, city.text, state.text, zip_code.text, country.text, email.text, phone_number.text, created_at.timestamp, status.text, risk_profile.text )

[User] Show me all customers who were created in the current year.

[Assistant] SELECT customer_id, first_name, last_name, created_at FROM financial_services.customers WHERE EXTRACT(YEAR FROM created_at) = EXTRACT(YEAR FROM CURRENT_DATE);

[User] Add their city and risk profile to the output, and sort by created_at ascending.

[Assistant] SELECT customer_id, first_name, last_name, city, risk_profile, created_at FROM financial_services.customers WHERE EXTRACT(YEAR FROM created_at) = EXTRACT(YEAR FROM CURRENT_DATE) ORDER BY created_at ASC;

[User] Only include customers whose email is not null.

[Assistant] SELECT customer_id, first_name, last_name, city, risk_profile, created_at FROM financial_services.customers WHERE EXTRACT(YEAR FROM created_at) = EXTRACT(YEAR FROM CURRENT_DATE) AND email IS NOT NULL ORDER BY created_at ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- 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.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)

[User] Can you show me all invoices with their invoice number, total amount, due date, and the full name of the client associated with the invoice?

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

[User] I only want invoices where the due date is in the next 14 days. Could you update the query?

[Assistant]
SELECT i.invoice_number, i.total_amount, i.due_date, c.first_name || ' ' || c.last_name AS client_full_name
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id
WHERE i.due_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '14 days';

[User] Also, add the status column from invoices and order the results by due_date ascending.

[Assistant]
SELECT i.invoice_number, i.total_amount, i.due_date, i.status, c.first_name || ' ' || c.last_name AS client_full_name
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id
WHERE i.due_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '14 days'
ORDER BY i.due_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.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id.text, patient_id.text, appointment_id.text, doctor_id.text, record_date.timestamp, chief_complaint.text, present_illness_history.text, past_medical_history.text, physical_examination_notes.text, assessment.text, treatment_plan.text, vitals.json, created_at.timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )

[User] Could you provide a list of each diagnosis, the full name of the doctor who made it, and the name of the insurance plan whose contact phone number matches the doctor's phone number? Please include diagnosis_id, description, doctor full name, and insurance plan name.

[Assistant]
SELECT d.diagnosis_id, d.description, doc.first_name || ' ' || doc.last_name AS doctor_full_name, ip.plan_name
FROM healthcare.diagnoses d
JOIN healthcare.doctors doc ON d.doctor_id = doc.doctor_id
JOIN healthcare.insurance_plans ip ON doc.phone_number = ip.contact_phone;

[User] I only want diagnoses that are marked as 'Active'. Could you adjust the previous query?

[Assistant]
SELECT d.diagnosis_id, d.description, doc.first_name || ' ' || doc.last_name AS doctor_full_name, ip.plan_name
FROM healthcare.diagnoses d
JOIN healthcare.doctors doc ON d.doctor_id = doc.doctor_id
JOIN healthcare.insurance_plans ip ON doc.phone_number = ip.contact_phone
WHERE d.status = 'Active';

[User] Also, could you add the diagnosis date and make sure results are sorted by diagnosis_date in descending order?

[Assistant]
SELECT d.diagnosis_id, d.description, d.diagnosis_date, doc.first_name || ' ' || doc.last_name AS doctor_full_name, ip.plan_name
FROM healthcare.diagnoses d
JOIN healthcare.doctors doc ON d.doctor_id = doc.doctor_id
JOIN healthcare.insurance_plans ip ON doc.phone_number = ip.contact_phone
WHERE d.status = 'Active'
ORDER BY d.diagnosis_date 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 text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )

[User] List smart money addresses on the 'Arbitrum' chain with a realized ratio between 0.5 and 0.8 and positive profit. Show address, profit, and realized_ratio.

[Assistant] SELECT address, profit, realized_ratio FROM smart_money_profit WHERE chain = 'Arbitrum' AND realized_ratio BETWEEN 0.5 AND 0.8 AND profit > 0

[User] Add the 'most_profit_token' and 'last_trade_time' to the result. Also, order by profit descending.

[Assistant] SELECT address, profit, realized_ratio, most_profit_token, last_trade_time FROM smart_money_profit WHERE chain = 'Arbitrum' AND realized_ratio BETWEEN 0.5 AND 0.8 AND profit > 0 ORDER BY profit 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 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.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_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.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 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;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )

[User] How many tokens are there for each number of decimals?

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

[User] Now, only show the decimal counts where there are more than 10 tokens.

[Assistant] SELECT decimals, COUNT(*) FROM web3.tokens GROUP BY decimals HAVING COUNT(*) > 10;


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

[User] For each chain, find the token with the highest 24h trading volume and the token with the lowest 24h trading volume. Show chain, high_volume_token, high_volume_24h, low_volume_token, and low_volume_24h.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       n.low_volume_token,
       n.low_volume_24h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain;

[User] Exclude chains where the highest volume is below 100,000.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       n.low_volume_token,
       n.low_volume_24h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain
WHERE m.high_volume_24h >= 100000;

[User] Also include the 6h price change percentage for those high and low volume tokens in the output.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h,
         price_change_percentage_6h AS high_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h,
         price_change_percentage_6h AS low_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       m.high_change_6h,
       n.low_volume_token,
       n.low_volume_24h,
       n.low_change_6h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain;

[User] Finally, order the result by chain in ascending order.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h,
         price_change_percentage_6h AS high_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h,
         price_change_percentage_6h AS low_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       m.high_change_6h,
       n.low_volume_token,
       n.low_volume_24h,
       n.low_change_6h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain
ORDER BY m.chain 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 smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )

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

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

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

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


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.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, 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, 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.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] Show each user's username along with their KYC status and the date of their latest KYC review.

[Assistant]
SELECT u.username, ka.status, ka.reviewed_at AS latest_review
FROM trading_platform.users u
JOIN trading_platform.kyc_audit ka ON u.user_id = ka.user_id
WHERE ka.reviewed_at = (
  SELECT MAX(reviewed_at)
  FROM trading_platform.kyc_audit
  WHERE user_id = u.user_id
);

[User] Also filter to only include those whose latest status is 'approved'.

[Assistant]
SELECT u.username, ka.status, ka.reviewed_at AS latest_review
FROM trading_platform.users u
JOIN trading_platform.kyc_audit ka ON u.user_id = ka.user_id
WHERE ka.reviewed_at = (
  SELECT MAX(reviewed_at)
  FROM trading_platform.kyc_audit
  WHERE user_id = u.user_id
)
  AND ka.status = 'approved';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )

[User] List all players who have unlocked achievements in the last 7 days, showing their username and the number of achievements unlocked.

[Assistant]
SELECT p.username, COUNT(pa.achievement_id) AS unlocked_count
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE pa.unlocked_at >= NOW() - INTERVAL '7 days'
GROUP BY p.username;

[User] Also include the date of their most recent unlock as last_unlocked.

[Assistant]
SELECT p.username, COUNT(pa.achievement_id) AS unlocked_count, MAX(pa.unlocked_at) AS last_unlocked
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa ON p.player_id = pa.player_id
WHERE pa.unlocked_at >= NOW() - INTERVAL '7 days'
GROUP BY p.username;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)

[User] Which invoices have a status of 'Partially Paid' and have not reached their due date yet? Show the invoice number, client ID, due date, and amount paid.

[Assistant]
SELECT invoice_number, client_id, due_date, amount_paid
FROM legal_services.invoices
WHERE status = 'Partially Paid' AND due_date > CURRENT_DATE;


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 text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] List the first_name, last_name, and registration_date of citizens who registered in 2023 but are still not verified.

[Assistant]
SELECT first_name,
       last_name,
       registration_date
FROM government_services.citizens
WHERE registration_date >= '2023-01-01'
  AND registration_date <  '2024-01-01'
  AND is_verified = FALSE;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)

[User] Find all policies that were cancelled due to 'Non-payment'. Show the policy number, cancellation date, and premium amount for these policies.

[Assistant] SELECT policy_number ,  cancellation_date ,  premium_amount FROM insurance.policies WHERE status = 'Cancelled' AND cancellation_reason = 'Non-payment'