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,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
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 character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
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 character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, 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 int, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] List all vehicles with their assigned driver full names, license plates, and scheduled departure times for upcoming trips, ordered by departure time.

[Assistant]
SELECT v.vehicle_id,
       v.license_plate,
       d.first_name || ' ' || d.last_name AS driver_name,
       t.scheduled_departure
FROM transportation.vehicles v
JOIN transportation.trips t ON v.vehicle_id = t.vehicle_id
JOIN transportation.drivers d ON t.driver_id = d.driver_id
WHERE t.scheduled_departure > NOW()
ORDER BY t.scheduled_departure;


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 narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )

[User] List all narratives that have a market cap between 500,000,000 and 5,000,000,000 USD and a positive price change over the last 7 days. Show the narrative name, market cap, and price change percentage for the last 7 days.

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d FROM narrative_info WHERE market_cap BETWEEN 500000000 AND 5000000000 AND price_change_percentage_7d > 0

[User] Thanks, can you also include the number of tokens for each of these narratives and filter to only include those with a trend rank better than 25?

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d, token_num FROM narrative_info WHERE market_cap BETWEEN 500000000 AND 5000000000 AND price_change_percentage_7d > 0 AND trend_rank < 25

[User] Okay, please order the results by market cap in descending order.

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d, token_num FROM narrative_info WHERE market_cap BETWEEN 500000000 AND 5000000000 AND price_change_percentage_7d > 0 AND trend_rank < 25 ORDER BY market_cap DESC

[User] Finally, limit the results to the top 10.

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d, token_num FROM narrative_info WHERE market_cap BETWEEN 500000000 AND 5000000000 AND price_change_percentage_7d > 0 AND trend_rank < 25 ORDER BY market_cap DESC LIMIT 10


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
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) )

[User] List `user_id` and `conversation_id` for participants who are in conversations where there is at least one message sent by *another* user that they have not read.

[Assistant] SELECT DISTINCT T1.user_id, T1.conversation_id FROM social_media.conversation_participants AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T2.sender_user_id != T1.user_id AND (T1.last_read_at IS NULL OR T2.sent_at > T1.last_read_at);


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.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Show me all claims with police reports that were handled by agents hired in the last 2 years, along with the agent's full name and agency.

[Assistant] SELECT c.claim_id, c.policy_id, c.incident_date, c.police_report_number, CONCAT(a.first_name, ' ', a.last_name) AS agent_name, a.agency_name FROM insurance.claims c JOIN insurance.agents a ON c.claim_handler_id = a.agent_id WHERE c.police_report_number IS NOT NULL AND a.hire_date >= CURRENT_DATE - INTERVAL '2 years'

[User] Now filter these results to only show claims where the estimated loss is above $10,000 and include the settlement amount if available.

[Assistant] SELECT c.claim_id, c.policy_id, c.incident_date, c.police_report_number, c.estimated_loss, c.settlement_amount, CONCAT(a.first_name, ' ', a.last_name) AS agent_name, a.agency_name FROM insurance.claims c JOIN insurance.agents a ON c.claim_handler_id = a.agent_id WHERE c.police_report_number IS NOT NULL AND a.hire_date >= CURRENT_DATE - INTERVAL '2 years' AND c.estimated_loss > 10000

[User] I also want to see how many documents were submitted for each of these claims.

[Assistant] SELECT c.claim_id, c.policy_id, c.incident_date, c.police_report_number, c.estimated_loss, c.settlement_amount, CONCAT(a.first_name, ' ', a.last_name) AS agent_name, a.agency_name, COUNT(d.document_id) AS document_count FROM insurance.claims c JOIN insurance.agents a ON c.claim_handler_id = a.agent_id LEFT JOIN insurance.claim_documents d ON c.claim_id = d.claim_id WHERE c.police_report_number IS NOT NULL AND a.hire_date >= CURRENT_DATE - INTERVAL '2 years' AND c.estimated_loss > 10000 GROUP BY c.claim_id, c.policy_id, c.incident_date, c.police_report_number, c.estimated_loss, c.settlement_amount, a.first_name, a.last_name, a.agency_name

[User] Finally, order the results by the highest estimated loss first and include only claims with at least 3 documents.

[Assistant] SELECT c.claim_id, c.policy_id, c.incident_date, c.police_report_number, c.estimated_loss, c.settlement_amount, CONCAT(a.first_name, ' ', a.last_name) AS agent_name, a.agency_name, COUNT(d.document_id) AS document_count FROM insurance.claims c JOIN insurance.agents a ON c.claim_handler_id = a.agent_id LEFT JOIN insurance.claim_documents d ON c.claim_id = d.claim_id WHERE c.police_report_number IS NOT NULL AND a.hire_date >= CURRENT_DATE - INTERVAL '2 years' AND c.estimated_loss > 10000 GROUP BY c.claim_id, c.policy_id, c.incident_date, c.police_report_number, c.estimated_loss, c.settlement_amount, a.first_name, a.last_name, a.agency_name HAVING COUNT(d.document_id) >= 3 ORDER BY c.estimated_loss DESC


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )

[User] List all law firms that do not have a managing partner listed.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.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.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] Get the total fuel cost per route, showing route_number and the sum of total_cost for all fuel logs associated with trips on that route.

[Assistant]
SELECT r.route_number,
       SUM(fl.total_cost) AS total_fuel_cost
FROM transportation.routes r
JOIN transportation.trips t ON r.route_id = t.route_id
JOIN transportation.fuel_logs fl ON t.trip_id = fl.trip_id
GROUP BY r.route_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 legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] For each document (identified by case_id and document_name), find the latest version number and the ID of the lawyer who uploaded that version.

[Assistant] WITH RankedDocuments AS ( SELECT document_id, case_id, document_name, uploaded_by_lawyer_id, version, ROW_NUMBER() OVER(PARTITION BY case_id, document_name ORDER BY version DESC) as rn FROM legal_services.documents ) SELECT case_id, document_name, version AS latest_version, uploaded_by_lawyer_id AS latest_version_lawyer_id FROM RankedDocuments WHERE rn = 1;

[User] Now, filter these results to only show documents where the very first version (version 1) was uploaded by a different lawyer than the latest version you just listed.

[Assistant] SELECT vi_first.case_id, vi_first.document_name, vi_first.uploaded_by_lawyer_id AS first_version_lawyer_id, vi_latest.uploaded_by_lawyer_id AS latest_version_lawyer_id FROM legal_services.documents vi_first JOIN legal_services.documents vi_latest ON vi_first.case_id = vi_latest.case_id AND vi_first.document_name = vi_latest.document_name JOIN ( SELECT case_id, document_name, MIN(version) AS min_v, MAX(version) AS max_v FROM legal_services.documents GROUP BY case_id, document_name ) AS versions ON vi_first.case_id = versions.case_id AND vi_first.document_name = versions.document_name AND vi_first.version = versions.min_v AND vi_latest.version = versions.max_v WHERE vi_first.uploaded_by_lawyer_id <> vi_latest.uploaded_by_lawyer_id;

[User] Could you also include the upload timestamps for both the first version and the latest version for these documents?

[Assistant] SELECT vi_first.case_id, vi_first.document_name, vi_first.uploaded_by_lawyer_id AS first_version_lawyer_id, vi_first.upload_timestamp AS first_version_timestamp, vi_latest.uploaded_by_lawyer_id AS latest_version_lawyer_id, vi_latest.upload_timestamp AS latest_version_timestamp FROM legal_services.documents vi_first JOIN legal_services.documents vi_latest ON vi_first.case_id = vi_latest.case_id AND vi_first.document_name = vi_latest.document_name JOIN ( SELECT case_id, document_name, MIN(version) AS min_v, MAX(version) AS max_v FROM legal_services.documents GROUP BY case_id, document_name ) AS versions ON vi_first.case_id = versions.case_id AND vi_first.document_name = versions.document_name AND vi_first.version = versions.min_v AND vi_latest.version = versions.max_v WHERE vi_first.uploaded_by_lawyer_id <> vi_latest.uploaded_by_lawyer_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 social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )

[User] Count the number of unread notifications for each notification_type across all users.

[Assistant]
SELECT
  notification_type,
  COUNT(*) AS unread_count
FROM social_media.notifications
WHERE read_at IS NULL
GROUP BY notification_type;


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

[User] List all servers that are currently marked with a 'offline' status.

[Assistant] SELECT server_id, server_name, region FROM gaming_technology.servers WHERE status = 'offline';

[User] For those offline servers, please include the server name, region, and calculate how many minutes have passed since their last reported heartbeat.

[Assistant] SELECT server_name, region, EXTRACT(EPOCH FROM (NOW() - last_heartbeat))/60 AS minutes_since_heartbeat FROM gaming_technology.servers WHERE status = 'offline';

[User] Refine the list further to only show offline servers where the last heartbeat was received more than 90 minutes ago.

[Assistant] SELECT server_name, region, EXTRACT(EPOCH FROM (NOW() - last_heartbeat))/60 AS minutes_since_heartbeat FROM gaming_technology.servers WHERE status = 'offline' AND last_heartbeat < NOW() - INTERVAL '90 minutes';

[User] Finally, order these results by how long ago the heartbeat was received, from the oldest heartbeat to the most recent among this filtered group.

[Assistant] SELECT server_name, region, EXTRACT(EPOCH FROM (NOW() - last_heartbeat))/60 AS minutes_since_heartbeat FROM gaming_technology.servers WHERE status = 'offline' AND last_heartbeat < NOW() - INTERVAL '90 minutes' ORDER BY last_heartbeat 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_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )

[User] Which are the top 5 smart money addresses with the highest ROI on the BSC chain, and what are their profit, realized ratio, and most profitable token?

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

[User] Can you also include their rank and last trade time in the output?

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' ORDER BY roi DESC LIMIT 5;

[User] I only want to see addresses with a profit above $10,000 and a realized ratio higher than 0.8.

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' AND profit > 10000 AND realized_ratio > 0.8 ORDER BY roi DESC LIMIT 5;

[User] Now, show the top one among these by profit instead of ROI.

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' AND profit > 10000 AND realized_ratio > 0.8 ORDER BY profit DESC LIMIT 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 legal_services.cases ( case_id text PRIMARY KEY, case_number text UNIQUE, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.documents ( document_id text 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.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )

[User] Retrieve all billable but not yet billed time entries, showing entry_id, lawyer_id, case_id, hours_spent, and billing_rate.

[Assistant]
SELECT entry_id, lawyer_id, case_id, hours_spent, billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE;

[User] Filter those entries for case_id 'case_123'.

[Assistant]
SELECT entry_id, lawyer_id, case_id, hours_spent, billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND case_id = 'case_123';

[User] Additionally, include the case_name from the cases table.

[Assistant]
SELECT t.entry_id,
       t.lawyer_id,
       t.case_id,
       c.case_name,
       t.hours_spent,
       t.billing_rate
FROM legal_services.time_entries t
JOIN legal_services.cases c ON t.case_id = c.case_id
WHERE t.is_billable = TRUE
  AND t.is_billed = FALSE
  AND t.case_id = 'case_123';


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id.text, asset_id.text, asset_type.text, maintenance_type.text, staff_id.text, start_datetime.timestamp, end_datetime.timestamp, description.text, cost.numeric, status.text )

[User] What is the detailed repair history of the equipment used by the staff with staff_id 'STAFF123' during maintenance tasks?

[Assistant] I'm sorry, but I can't provide information on the detailed repair history of equipment used by staff members. The data in the maintenance_records table only includes information about maintenance tasks, such as record_id, asset_id, maintenance type, and staff_id, but does not cover equipment repair histories.


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

[User] Could you provide a report showing each in-game item's name and the total quantity currently held in player inventories?

[Assistant] SELECT ii.item_name, SUM(pi.quantity) AS total_held FROM gaming_technology.player_inventory pi JOIN gaming_technology.in_game_items ii ON pi.item_id = ii.item_id GROUP BY ii.item_name;

[User] Filter this list to only show items where the total quantity held is greater than 1000.

[Assistant] SELECT ii.item_name, SUM(pi.quantity) AS total_held FROM gaming_technology.player_inventory pi JOIN gaming_technology.in_game_items ii ON pi.item_id = ii.item_id GROUP BY ii.item_name HAVING SUM(pi.quantity) > 1000;


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

[User] Show me all active drivers whose license will expire in the next 60 days, including their full name and contact information.

[Assistant] SELECT driver_id, first_name, last_name, contact_number, email, license_expiry_date FROM transportation.drivers WHERE status = 'active' AND license_expiry_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '60 days')

[User] Can you also include their hire date and order the results by license expiry date with the soonest expiring first?

[Assistant] SELECT driver_id, first_name, last_name, contact_number, email, hire_date, license_expiry_date FROM transportation.drivers WHERE status = 'active' AND license_expiry_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '60 days') ORDER BY license_expiry_date ASC

[User] Now filter this to only show drivers who were hired more than 3 years ago.

[Assistant] SELECT driver_id, first_name, last_name, contact_number, email, hire_date, license_expiry_date FROM transportation.drivers WHERE status = 'active' AND license_expiry_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '60 days') AND hire_date < (CURRENT_DATE - INTERVAL '3 years') ORDER BY license_expiry_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 government_services.service_locations ( location_id.text, 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 )

[User] How many service locations are accessible in each state? Provide the state and the count of accessible locations.

[Assistant] SELECT state, COUNT(*) FROM government_services.service_locations WHERE is_accessible = TRUE GROUP BY state;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] Can you provide a list of all players who have acquired at least one item, along with the item name, its type, and the title of the game that item belongs to?

[Assistant]
SELECT pi.player_id, items.item_name, items.item_type, g.title AS game_title
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
JOIN gaming_technology.games g ON items.game_id = g.game_id
GROUP BY pi.player_id, items.item_name, items.item_type, g.title;

[User] Actually, I'd like to only see cases where a player has acquired more than 2 different types of items. Can you adjust the query?

[Assistant]
SELECT pi.player_id, items.item_name, items.item_type, g.title AS game_title
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
JOIN gaming_technology.games g ON items.game_id = g.game_id
WHERE pi.player_id IN (
    SELECT pi2.player_id
    FROM gaming_technology.player_inventory pi2
    JOIN gaming_technology.in_game_items items2 ON pi2.item_id = items2.item_id
    GROUP BY pi2.player_id
    HAVING COUNT(DISTINCT items2.item_type) > 2
)
GROUP BY pi.player_id, items.item_name, items.item_type, g.title;

[User] I'd also like to know the total quantity of items each qualifying player has acquired. Can you add that to the results?

[Assistant]
SELECT pi.player_id, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
WHERE pi.player_id IN (
    SELECT pi2.player_id
    FROM gaming_technology.player_inventory pi2
    JOIN gaming_technology.in_game_items items2 ON pi2.item_id = items2.item_id
    GROUP BY pi2.player_id
    HAVING COUNT(DISTINCT items2.item_type) > 2
)
GROUP BY pi.player_id;

[User] Can you also display the country of each player if I had such a 'country_code' column in a 'players' table? Show it in the result along with the player_id and total_quantity.

[Assistant]
SELECT pi.player_id, p.country_code, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
JOIN gaming_technology.players p ON pi.player_id = p.player_id
WHERE pi.player_id IN (
    SELECT pi2.player_id
    FROM gaming_technology.player_inventory pi2
    JOIN gaming_technology.in_game_items items2 ON pi2.item_id = items2.item_id
    GROUP BY pi2.player_id
    HAVING COUNT(DISTINCT items2.item_type) > 2
)
GROUP BY pi.player_id, p.country_code;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
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.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, 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.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, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    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, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
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] Which employees have been assigned to applications for services with a standard fee greater than 200? Show the employee's full name, job title, application ID, and the service name.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS employee_full_name, e.job_title, a.application_id, s.service_name
FROM government_services.applications a
JOIN government_services.employees e ON a.assigned_employee_id = e.employee_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE s.standard_fee > 200;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.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] Find all pairs of payments for the same policy where the payment_periods overlap. Show payment_id1, payment_id2, policy_id, overlap_start, and overlap_end.

[Assistant]
SELECT p1.payment_id AS payment_id1,
       p2.payment_id AS payment_id2,
       p1.policy_id,
       GREATEST(p1.payment_period_start, p2.payment_period_start) AS overlap_start,
       LEAST(p1.payment_period_end, p2.payment_period_end) AS overlap_end
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.policy_id = p2.policy_id
 AND p1.payment_id < p2.payment_id
WHERE p1.payment_period_start <= p2.payment_period_end
  AND p2.payment_period_start <= p1.payment_period_end;

[User] Only include pairs where both payment statuses are 'completed'.

[Assistant]
SELECT p1.payment_id AS payment_id1,
       p2.payment_id AS payment_id2,
       p1.policy_id,
       GREATEST(p1.payment_period_start, p2.payment_period_start) AS overlap_start,
       LEAST(p1.payment_period_end, p2.payment_period_end) AS overlap_end
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.policy_id = p2.policy_id
 AND p1.payment_id < p2.payment_id
WHERE p1.payment_period_start <= p2.payment_period_end
  AND p2.payment_period_start <= p1.payment_period_end
  AND p1.status = 'completed'
  AND p2.status = 'completed';

[User] Also include the customer_id for each payment in the output.

[Assistant]
SELECT p1.payment_id AS payment_id1,
       p2.payment_id AS payment_id2,
       p1.customer_id AS customer_id1,
       p2.customer_id AS customer_id2,
       p1.policy_id,
       GREATEST(p1.payment_period_start, p2.payment_period_start) AS overlap_start,
       LEAST(p1.payment_period_end, p2.payment_period_end) AS overlap_end
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.policy_id = p2.policy_id
 AND p1.payment_id < p2.payment_id
WHERE p1.payment_period_start <= p2.payment_period_end
  AND p2.payment_period_start <= p1.payment_period_end
  AND p1.status = 'completed'
  AND p2.status = 'completed';


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

[User] Count the total number of group chats.

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE is_group_chat = true;


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 )

[User] Show me all pairs of usernames for users located in the same city along with their shared location.

[Assistant]
SELECT u1.username AS user1, u2.username AS user2, u1.location
FROM social_media.users u1
JOIN social_media.users u2
  ON u1.location = u2.location
  AND u1.user_id < u2.user_id;

[User] I only want pairs where both users have verified profiles.

[Assistant]
SELECT u1.username AS user1, u2.username AS user2, u1.location
FROM social_media.users u1
JOIN social_media.users u2
  ON u1.location = u2.location
  AND u1.user_id < u2.user_id
WHERE u1.is_verified = TRUE
  AND u2.is_verified = TRUE;

[User] Also, order the results by the first username, then the second.

[Assistant]
SELECT u1.username AS user1, u2.username AS user2, u1.location
FROM social_media.users u1
JOIN social_media.users u2
  ON u1.location = u2.location
  AND u1.user_id < u2.user_id
WHERE u1.is_verified = TRUE
  AND u2.is_verified = TRUE
ORDER BY u1.username, u2.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 financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text )

[User] Retrieve each employee with their manager's first_name and last_name.

[Assistant] SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id;

[User] Filter to only include employees in the 'Finance' department whose managers belong to a different department.

[Assistant] SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.department AS manager_department FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.department = 'Finance' AND m.department IS NOT NULL AND m.department <> e.department;

[User] Also show the branch_id for both the employee and their manager.

[Assistant] SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, e.branch_id AS employee_branch_id, m.employee_id AS manager_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.department AS manager_department, m.branch_id AS manager_branch_id FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.department = 'Finance' AND m.department IS NOT NULL AND m.department <> e.department;

[User] Finally, sort the results by the employee's last_name ascending, then by their manager's last_name descending.

[Assistant] SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, e.branch_id AS employee_branch_id, m.employee_id AS manager_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.department AS manager_department, m.branch_id AS manager_branch_id FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.department = 'Finance' AND m.department IS NOT NULL AND m.department <> e.department ORDER BY e.last_name ASC, m.last_name DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.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 )

[User] Which active services have a standard fee less than 100, and what are the agency IDs and categories for these services?

[Assistant] SELECT service_name, agency_id, category FROM government_services.services WHERE is_active = TRUE AND standard_fee < 100;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_id)
)

[User] Find all clients who do not have a company name listed and show their full name and email.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE company_name IS NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )

[User] Show the full name of each manager and the average commission rate of the agents who report directly to them. Only include managers who have at least one reporting agent.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, AVG(T1.commission_rate) AS average_agent_commission_rate FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id GROUP BY T2.agent_id, T2.first_name, T2.last_name

[User] Filter the results to only show managers whose average agent commission rate is above 0.12.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, AVG(T1.commission_rate) AS average_agent_commission_rate FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id GROUP BY T2.agent_id, T2.first_name, T2.last_name HAVING AVG(T1.commission_rate) > 0.12


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.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] List the full names of patients who have had at least one appointment scheduled with a doctor, along with the medication names they have been prescribed. Please include only patients who have both an appointment and at least one corresponding medication.

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, m.medication_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.medications m ON m.medication_id IN (
    SELECT medication_id FROM healthcare.medications
) -- Placeholder, since no direct prescription table or mapping is given
WHERE a.status = 'scheduled';

[User] Actually, could you also include the appointment time in the results?

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, a.appointment_time, m.medication_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.medications m ON m.medication_id IN (
    SELECT medication_id FROM healthcare.medications
)
WHERE a.status = 'scheduled';

[User] The medication names are not matching with the appointments, I think there is no direct link. Can you just give me, for each patient who has at least one scheduled appointment, all their appointment times and their last names, without including medication info?

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, a.appointment_time
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
WHERE a.status = 'scheduled';


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.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.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 character varying(64) NOT NULL, user_id character varying(64) NOT NULL, status character varying(32) NOT NULL, reviewed_at timestamp NOT NULL, PRIMARY KEY (kyc_audit_id) )

[User] Show assets of type 'token', including their name, symbol, and any associated metadata key and value.

[Assistant] SELECT t1.name, t1.symbol, t2.key, t2.value FROM trading_platform.assets AS t1 LEFT JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token';

[User] For the results from the previous query, only include metadata entries where the key is 'website'.

[Assistant] SELECT t1.name, t1.symbol, t2.key, t2.value FROM trading_platform.assets AS t1 LEFT JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token' AND t2.key = 'website';

[User] Instead of listing metadata, count how many assets of type 'token' have a metadata entry with key 'website'.

[Assistant] SELECT COUNT(DISTINCT t1.asset_id) FROM trading_platform.assets AS t1 INNER JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token' AND t2.key = 'website';

[User] Also, provide the total count of assets with type 'token'.

[Assistant] SELECT COUNT(DISTINCT t1.asset_id) FILTER (WHERE t2.key = 'website') AS token_with_website_metadata_count, COUNT(DISTINCT t1.asset_id) AS total_token_count FROM trading_platform.assets AS t1 LEFT JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token';


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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.documents ( document_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, document_name character varying(255) NOT NULL, document_type character varying(100), storage_path text NOT NULL, uploaded_by_lawyer_id character varying(64), upload_timestamp timestamp NOT NULL, version integer DEFAULT 1, description text, PRIMARY KEY (document_id) )
CREATE TABLE legal_services.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )
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] Which cases have at least one document uploaded, and what are the names and case numbers of those cases along with the most recent document name for each?

[Assistant]
SELECT c.case_id, c.case_name, c.case_number, d.document_name AS latest_document_name
FROM legal_services.cases c
JOIN (
    SELECT case_id, MAX(upload_timestamp) AS latest_upload
    FROM legal_services.documents
    GROUP BY case_id
) last_doc ON c.case_id = last_doc.case_id
JOIN legal_services.documents d ON d.case_id = last_doc.case_id AND d.upload_timestamp = last_doc.latest_upload;


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.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )

[User] Compute the co-occurrence count for each hashtag pair across all posts.

[Assistant]
SELECT ph1.hashtag_id AS tag_a, ph2.hashtag_id AS tag_b, COUNT(DISTINCT ph1.post_id) AS co_occurrence_count
FROM social_media.post_hashtags ph1
JOIN social_media.post_hashtags ph2
  ON ph1.post_id = ph2.post_id
  AND ph1.hashtag_id < ph2.hashtag_id
GROUP BY ph1.hashtag_id, ph2.hashtag_id;

[User] Only include pairs with co_occurrence_count >= 3.

[Assistant]
SELECT ph1.hashtag_id AS tag_a, ph2.hashtag_id AS tag_b, COUNT(DISTINCT ph1.post_id) AS co_occurrence_count
FROM social_media.post_hashtags ph1
JOIN social_media.post_hashtags ph2
  ON ph1.post_id = ph2.post_id
  AND ph1.hashtag_id < ph2.hashtag_id
GROUP BY ph1.hashtag_id, ph2.hashtag_id
HAVING COUNT(DISTINCT ph1.post_id) >= 3;

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

[Assistant]
SELECT ph1.hashtag_id AS tag_a, ph2.hashtag_id AS tag_b, COUNT(DISTINCT ph1.post_id) AS co_occurrence_count
FROM social_media.post_hashtags ph1
JOIN social_media.post_hashtags ph2
  ON ph1.post_id = ph2.post_id
  AND ph1.hashtag_id < ph2.hashtag_id
GROUP BY ph1.hashtag_id, ph2.hashtag_id
HAVING COUNT(DISTINCT ph1.post_id) >= 3
ORDER BY co_occurrence_count DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.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.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 each user along with how many image-type posts they've made, showing user_id and image_post_count, sorted by the count descending.

[Assistant]
SELECT user_id, COUNT(*) AS image_post_count
FROM social_media.posts
WHERE media_type = 'image'
GROUP BY user_id
ORDER BY image_post_count 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 social_media.users ( user_id text PRIMARY KEY, 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 bool )
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, 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.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, 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 PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] List all posts that contain a non-empty media_url and show the usernames of their authors.

[Assistant]
SELECT p.post_id, p.media_url, u.username
FROM social_media.posts p
JOIN social_media.users u ON p.user_id = u.user_id
WHERE p.media_url IS NOT NULL AND p.media_url <> '';


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 PRIMARY KEY, 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 text, created_at timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] I want to see a list of insurance plans along with the full names of all doctors whose hospital affiliation ID matches the plan ID. For each entry, include the plan name, insurance provider, doctor ID, and the doctor's first and last name.

[Assistant]
SELECT ip.plan_name, ip.insurance_provider, d.doctor_id, d.first_name, d.last_name
FROM healthcare.insurance_plans ip
JOIN healthcare.doctors d ON ip.plan_id = d.hospital_affiliation_id

[User] Additionally, show only doctors who have an email address on file.

[Assistant]
SELECT ip.plan_name, ip.insurance_provider, d.doctor_id, d.first_name, d.last_name
FROM healthcare.insurance_plans ip
JOIN healthcare.doctors d ON ip.plan_id = d.hospital_affiliation_id
WHERE d.email IS NOT NULL AND d.email <> ''

[User] Sort the results by insurance provider in ascending order, then by the doctor's last name in descending order.

[Assistant]
SELECT ip.plan_name, ip.insurance_provider, d.doctor_id, d.first_name, d.last_name
FROM healthcare.insurance_plans ip
JOIN healthcare.doctors d ON ip.plan_id = d.hospital_affiliation_id
WHERE d.email IS NOT NULL AND d.email <> ''
ORDER BY ip.insurance_provider ASC, d.last_name DESC


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
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] Show the total hours spent by each lawyer across all their time entries. Display the lawyer's first name, last name, and the total hours.

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

[User] Modify the previous query to only include time entries that are marked as billable.

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

[User] Now, filter the results to only show lawyers who are partners and have logged more than 100 billable hours in total.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_billable_hours FROM legal_services.time_entries te JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id WHERE te.is_billable = true AND l.is_partner = true GROUP BY l.lawyer_id, l.first_name, l.last_name HAVING SUM(te.hours_spent) > 100 ORDER BY total_billable_hours DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )

[User] Find all pairs of insurance products that belong to the same product_type and are both active, listing the two product IDs and their names.

[Assistant]
SELECT p1.product_id AS product1_id, p1.product_name AS product1_name, p2.product_id AS product2_id, p2.product_name AS product2_name
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p1.product_id < p2.product_id
WHERE p1.is_active = true
  AND p2.is_active = true;

[User] Only include pairs where the absolute difference in base_premium is greater than 500.

[Assistant]
SELECT p1.product_id AS product1_id, p1.product_name AS product1_name, p2.product_id AS product2_id, p2.product_name AS product2_name
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p1.product_id < p2.product_id
WHERE p1.is_active = true
  AND p2.is_active = true
  AND ABS(p1.base_premium - p2.base_premium) > 500;

[User] And restrict this to product_type 'home'.

[Assistant]
SELECT p1.product_id AS product1_id, p1.product_name AS product1_name, p2.product_id AS product2_id, p2.product_name AS product2_name
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p1.product_id < p2.product_id
WHERE p1.is_active = true
  AND p2.is_active = true
  AND ABS(p1.base_premium - p2.base_premium) > 500
  AND p1.product_type = 'home';


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

[User] List consecutive fuel log entries for each vehicle based on log_timestamp. Show vehicle ID, current log ID, previous log ID, current timestamp, previous timestamp, and the quantity difference (current - previous).

[Assistant]
SELECT
    vehicle_id,
    fuel_log_id AS current_log_id,
    LAG(fuel_log_id) OVER (PARTITION BY vehicle_id ORDER BY log_timestamp) AS previous_log_id,
    log_timestamp AS current_timestamp,
    LAG(log_timestamp) OVER (PARTITION BY vehicle_id ORDER BY log_timestamp) AS previous_timestamp,
    quantity - LAG(quantity) OVER (PARTITION BY vehicle_id ORDER BY log_timestamp) AS quantity_difference
FROM transportation.fuel_logs
ORDER BY vehicle_id, log_timestamp;

[User] Filter this list to only include pairs where the quantity difference is positive and greater than 20 units.

[Assistant]
WITH ConsecutiveLogs AS (
    SELECT
        vehicle_id,
        fuel_log_id AS current_log_id,
        LAG(fuel_log_id) OVER (PARTITION BY vehicle_id ORDER BY log_timestamp) AS previous_log_id,
        log_timestamp AS current_timestamp,
        LAG(log_timestamp) OVER (PARTITION BY vehicle_id ORDER BY log_timestamp) AS previous_timestamp,
        quantity - LAG(quantity) OVER (PARTITION BY vehicle_id ORDER BY log_timestamp) AS quantity_difference
    FROM transportation.fuel_logs
)
SELECT
    vehicle_id,
    current_log_id,
    previous_log_id,
    current_timestamp,
    previous_timestamp,
    quantity_difference
FROM ConsecutiveLogs
WHERE quantity_difference > 20;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id.text, 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 )

[User] List all doctors whose last name begins with 'B', showing their doctor ID, full name, and their hospital affiliation ID.

[Assistant] SELECT doctor_id, first_name, last_name, hospital_affiliation_id FROM healthcare.doctors WHERE last_name LIKE 'B%';

[User] Could you refine the query to only include doctors whose phone_number ends with '99'?

[Assistant] SELECT doctor_id, first_name, last_name, hospital_affiliation_id FROM healthcare.doctors WHERE last_name LIKE 'B%' AND phone_number LIKE '%99';


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 manufacturing.components (
    component_id character varying(64) NOT NULL, -- unique identifier for the component
    part_number character varying(100) NOT NULL UNIQUE, -- manufacturer-specific part number
    component_name character varying(255) NOT NULL, -- descriptive name (e.g., Landing Gear Strut, Wing Spar)
    description text, -- detailed description
    material_id character varying(64), -- FK linking to the material used
    supplier_id character varying(64), -- FK linking to the supplier
    weight_kg numeric(10,3), -- weight of the component in kg
    cost_usd numeric(12,2), -- cost of the component in USD
    criticality_level character varying(20), -- e.g., 'High', 'Medium', 'Low'
    PRIMARY KEY (component_id)
)
CREATE TABLE manufacturing.materials (
    material_id character varying(64) NOT NULL,  -- unique identifier for the material
    material_name character varying(128) NOT NULL, -- common name (e.g., Titanium Alloy Grade 5, Carbon Fiber Prepreg)
    specification character varying(255), -- specification standard (e.g., AMS 4928)
    description text, -- detailed description of properties
    density_kg_m3 numeric(10, 4), -- density in kg per cubic meter
    tensile_strength_mpa integer, -- tensile strength in Megapascals
    PRIMARY KEY (material_id)
)
CREATE TABLE manufacturing.assembly_lines (
    line_id character varying(64) NOT NULL, -- unique identifier for the assembly line
    line_name character varying(128) NOT NULL, -- name of the line (e.g., Fuselage Assembly Line 1)
    location_building character varying(100), -- building where the line is located
    location_area character varying(100), -- specific area within the building
    aircraft_model_id character varying(64), -- FK to the primary aircraft model built on this line
    capacity_units_per_month integer, -- theoretical maximum output per month
    status character varying(50) NOT NULL, -- e.g., 'Active', 'Maintenance', 'Idle'
    PRIMARY KEY (line_id)
)
CREATE TABLE manufacturing.component_inventory (
    inventory_record_id character varying(64) NOT NULL, -- unique ID for this inventory record/batch
    component_id character varying(64) NOT NULL, -- FK to the component
    quantity integer NOT NULL, -- number of units of this component in stock for this batch
    location_warehouse character varying(100), -- warehouse identifier
    location_bin character varying(100), -- specific bin or shelf location
    received_date timestamp NOT NULL, -- when this batch was received
    expiry_date date, -- expiry date if applicable (e.g., for sealants, adhesives)
    batch_number character varying(100), -- supplier batch number
    last_updated timestamp NOT NULL, -- timestamp of the last update to this record
    PRIMARY KEY (inventory_record_id)
)

[User] 我想查询所有使用特定材料ID的组件信息，包括组件名称、零件编号和供应商ID，同时还需要获取该材料的名称和规格。

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id';

[User] 如果我想只显示重量大于10公斤的组件，应该怎么修改查询语句？

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id' AND c.weight_kg > 10;

[User] 能不能再加上一个条件，只显示关键性等级为'High'的组件？

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id' AND c.weight_kg > 10 AND c.criticality_level = 'High';

[User] 最后，请按组件名称的字母顺序对结果进行排序。

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id' AND c.weight_kg > 10 AND c.criticality_level = 'High'
ORDER BY c.component_name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
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, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )

[User] List law firm names and the full name and specialization of all lawyers hired after 2020.

[Assistant] SELECT T1.firm_name, T2.first_name || ' ' || T2.last_name AS lawyer_full_name, T2.specialization FROM law_firms AS T1 JOIN lawyers AS T2 ON T1.firm_id = T2.firm_id WHERE T2.hire_date >= '2021-01-01'

[User] Only include firms founded before 2015.

[Assistant] SELECT T1.firm_name, T2.first_name || ' ' || T2.last_name AS lawyer_full_name, T2.specialization FROM law_firms AS T1 JOIN lawyers AS T2 ON T1.firm_id = T2.firm_id WHERE T2.hire_date >= '2021-01-01' AND T1.founded_date < '2015-01-01'

[User] Display only the firm name, lawyer full name, and hire date.

[Assistant] SELECT T1.firm_name, T2.first_name || ' ' || T2.last_name AS lawyer_full_name, T2.hire_date FROM law_firms AS T1 JOIN lawyers AS T2 ON T1.firm_id = T2.firm_id WHERE T2.hire_date >= '2021-01-01' AND T1.founded_date < '2015-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 token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token 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_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp chain character varying(128) NOT NULL, -- the chain that the token resides address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX exchange character varying(512) NOT NULL, -- a centralized exchange name token_address character varying(128) NOT NULL, -- token contract address token_symbol character varying(512), --token symbol balance numeric(38,10), -- token balance usd_value numeric(38,14), -- value of the token held in USD price double precision, --price of the token in USD ,PRIMARY KEY (snapshot_time, exchange, address, chain, token_address) )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol pnl numeric(38,2), -- the profit users made on this token net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token avg_cost numeric(38,16), -- the average cost price of user spent on this token price double precision, -- the current price of the token realized_ratio numeric(10,2), -- the ratio user sold of the token roi numeric(10,2), -- the roi users made of this token chain character varying(100), -- the chain that the token resides PRIMARY KEY (token_address, chain) )

[User] For each narrative, what is the average smart money ROI and the total 24-hour trading volume of the narrative?

[Assistant] SELECT T3.narrative, T4.avg_roi, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative

[User] Only include narratives that have more than 20 tokens and a total 24h trading volume above $1,000,000.

[Assistant] SELECT T3.narrative, T4.avg_roi, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000

[User] Also show the average net flow for smart money performance within each of these narratives.

[Assistant] SELECT T3.narrative, T4.avg_roi, T4.avg_net_flow, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi, AVG(T1.net_flow) as avg_net_flow FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000

[User] Order the results by average ROI descending and show the top 5.

[Assistant] SELECT T3.narrative, T4.avg_roi, T4.avg_net_flow, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi, AVG(T1.net_flow) as avg_net_flow FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000 ORDER BY T4.avg_roi DESC LIMIT 5


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

[User] Show me pairs of servers in the same region hosting different games where one has at least 100 more current players than the other.

[Assistant]
SELECT s1.server_id AS server1_id,
       s1.server_name AS server1_name,
       s1.region,
       s2.server_id AS server2_id,
       s2.server_name AS server2_name
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
WHERE s1.game_id <> s2.game_id
  AND s1.current_players >= s2.current_players + 100;

[User] Also include the difference in current players between the two servers as player_diff.

[Assistant]
SELECT s1.server_id AS server1_id,
       s1.server_name AS server1_name,
       s1.region,
       s2.server_id AS server2_id,
       s2.server_name AS server2_name,
       (s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
WHERE s1.game_id <> s2.game_id
  AND (s1.current_players - s2.current_players) >= 100;