System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )
##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 )
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.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
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 )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.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 timestamp with time zone )
##Table Structure
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, 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 )

[User] Which chain has the highest total USD inflow from buy transactions (type=1), and how many distinct tokens were involved in that inflow?

[Assistant]
SELECT chain, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY chain
ORDER BY total_inflow DESC
LIMIT 1;

[User] I also want to see the average price at which those tokens were bought for that chain.

[Assistant]
WITH inflow AS (
  SELECT chain, SUM(usd_value) AS total_inflow
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY chain
), top_chain AS (
  SELECT chain FROM inflow ORDER BY total_inflow DESC LIMIT 1
)
SELECT i.chain, AVG(i.avg_price) AS avg_buy_price
FROM smart_money_token_inflow i
JOIN top_chain t ON i.chain = t.chain
WHERE i.type = 1;

[User] Actually, filter to narratives where the total USD inflow is above 50000.

[Assistant]
SELECT narrative, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY narrative
HAVING SUM(usd_value) > 50000;

[User] Please order the results by average price descending and show the top 2 chains.

[Assistant]
SELECT chain, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens, AVG(avg_price) AS avg_buy_price
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY chain
ORDER BY avg_buy_price DESC
LIMIT 2;

[User] How many insurance policies does each patient have? Return patient_id and policy_count.

[Assistant]
SELECT patient_id,
       COUNT(*) AS policy_count
FROM healthcare.patient_insurance
GROUP BY patient_id;

[User] Only show patients with more than 2 policies and order by policy_count descending.

[Assistant]
SELECT patient_id,
       COUNT(*) AS policy_count
FROM healthcare.patient_insurance
GROUP BY patient_id
HAVING COUNT(*) > 2
ORDER BY policy_count DESC;

[User] List the names and URLs of all available decentralized applications (DApps).

[Assistant] SELECT name, url FROM dapps;

[User] Can you provide a query that lists each game title, its platform, and the name of its developer by joining the games and developers tables?

[Assistant]
SELECT g.title,
       g.platform,
       d.name AS developer_name
FROM gaming_technology.games g
JOIN gaming_technology.developers d
  ON g.developer_id = d.developer_id;

[User] Actually, I need only games released in 2023 and sorted by release_date ascending.

[Assistant]
SELECT g.title,
       g.platform,
       d.name AS developer_name,
       g.release_date
FROM gaming_technology.games g
JOIN gaming_technology.developers d
  ON g.developer_id = d.developer_id
WHERE g.release_date BETWEEN '2023-01-01' AND '2023-12-31'
ORDER BY g.release_date ASC;

[User] Can you list the number of items for each rarity in the system?

[Assistant]
SELECT rarity, COUNT(*) AS item_count
FROM gaming_technology.in_game_items
GROUP BY rarity;

[User] Please only show rarities with at least 3 items.

[Assistant]
SELECT rarity, COUNT(*) AS item_count
FROM gaming_technology.in_game_items
GROUP BY rarity
HAVING COUNT(*) >= 3;

[User] Can you also display the minimum, maximum, and average cost amount for each rarity?

[Assistant]
SELECT rarity, COUNT(*) AS item_count, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost, AVG(cost_amount) AS avg_cost
FROM gaming_technology.in_game_items
GROUP BY rarity
HAVING COUNT(*) >= 3;

[User] Show me all invoices where the notes field is not null. Display invoice number, client ID, and notes.

[Assistant] SELECT invoice_number, client_id, notes FROM legal_services.invoices WHERE notes IS NOT 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 legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
##Table Structure
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) )
##Table Structure
CREATE TABLE transportation.bookings (
    booking_id character varying(64) NOT NULL,  -- unique identifier for the booking
    passenger_id character varying(64) NOT NULL, -- identifier of the passenger making the booking
    trip_id character varying(64) NOT NULL, -- identifier of the trip being booked
    seat_number character varying(16), -- assigned seat number (if applicable)
    booking_time timestamp with time zone NOT NULL, -- time when the booking was made
    status character varying(32) NOT NULL, -- e.g., Confirmed, Cancelled, Pending Payment
    fare numeric(10, 2) NOT NULL, -- price paid for the booking
    payment_transaction_id character varying(128), -- reference to the payment transaction
    special_requests text, -- any special requests from the passenger
    PRIMARY KEY (booking_id)
)
##Table Structure
CREATE TABLE financial_services.accounts ( account_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, account_number character varying(128) NOT NULL UNIQUE, account_type character varying(50) NOT NULL, balance numeric(19, 4) NOT NULL DEFAULT 0.00, currency character varying(3) NOT NULL, opened_date date NOT NULL, status character varying(32) NOT NULL, interest_rate numeric(5, 4), last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) )
##Table Structure
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
##Table Structure
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, 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 PRIMARY KEY, 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.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
##Table Structure
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 )

[User] Can you show me the number of lawyers grouped by specialization?

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count FROM lawyers GROUP BY specialization;

[User] Include only specializations that have more than two lawyers.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2;

[User] Also show the average tenure in years for each of those specializations.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count, AVG(EXTRACT(EPOCH FROM (NOW() - hire_date)) / 31536000) AS avg_tenure_years FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2;

[User] Order the result by average tenure in descending order.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count, AVG(EXTRACT(EPOCH FROM (NOW() - hire_date)) / 31536000) AS avg_tenure_years FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2 ORDER BY avg_tenure_years DESC;

[User] For each patient, find their latest medical record and show patient_id, latest_record_id, and record_date.

[Assistant]
SELECT a.patient_id,
       a.record_id AS latest_record_id,
       a.record_date
FROM healthcare.medical_records a
LEFT JOIN healthcare.medical_records b
  ON a.patient_id = b.patient_id
 AND a.record_date < b.record_date
WHERE b.record_id IS NULL;

[User] Actually, only include records created after January 1st, 2024.

[Assistant]
SELECT a.patient_id,
       a.record_id AS latest_record_id,
       a.record_date
FROM healthcare.medical_records a
LEFT JOIN healthcare.medical_records b
  ON a.patient_id = b.patient_id
 AND a.record_date < b.record_date
WHERE b.record_id IS NULL
  AND a.record_date > '2024-01-01';

[User] Show me the total number of bookings and total fare collected per trip. Only include trips that have collected more than 500 in total fare.

[Assistant]
SELECT trip_id, COUNT(*) AS booking_count, SUM(fare) AS total_fare
FROM transportation.bookings
GROUP BY trip_id
HAVING SUM(fare) > 500;

[User] Which customers have more than one account? Please include customer_id and the number of accounts they hold.

[Assistant] SELECT customer_id, COUNT(account_id) AS account_count FROM financial_services.accounts GROUP BY customer_id HAVING COUNT(account_id) > 1;

[User] Can you also show the account_types for each customer in the result?

[Assistant] SELECT customer_id, COUNT(account_id) AS account_count, STRING_AGG(DISTINCT account_type, ', ') AS account_types FROM financial_services.accounts GROUP BY customer_id HAVING COUNT(account_id) > 1;

[User] List the number of bookings made by each loyalty program member. Show the loyalty_program_id and the booking count.

[Assistant]
SELECT p.loyalty_program_id, COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE p.loyalty_program_id IS NOT NULL
GROUP BY p.loyalty_program_id;

[User] What is the total estimated loss for all claims reported in the year 2024?

[Assistant] SELECT SUM(estimated_loss) FROM insurance.claims WHERE EXTRACT(YEAR FROM reported_date) = 2024;

[User] List all guests who have provided a phone number, showing their guest ID and phone number.

[Assistant] SELECT guest_id, phone_number FROM hospitality_technology.guests WHERE phone_number IS NOT NULL AND phone_number <> '';

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

[Assistant] SELECT guest_id, phone_number, email FROM hospitality_technology.guests WHERE phone_number IS NOT NULL AND phone_number <> '';

[User] How many posts are currently marked as 'private' visibility?

[Assistant] SELECT COUNT(*) FROM social_media.posts WHERE visibility = 'private'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
##Table Structure
CREATE TABLE gaming_technology.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
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, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
##Table Structure
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
##Table Structure
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
##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 )
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )
##Table Structure
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)

[User] Calculate the total price for all service orders, grouped by their status.

[Assistant] SELECT status, SUM(total_price) AS total_revenue FROM hospitality_technology.service_orders GROUP BY status;

[User] Now, only include the statuses 'Delivered' and 'Completed'.

[Assistant] SELECT status, SUM(total_price) AS total_revenue FROM hospitality_technology.service_orders WHERE status IN ('Delivered', 'Completed') GROUP BY status;

[User] For each achievement, show its name, the game_id it belongs to, and the number of distinct players who have played a session for that game.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id;

[User] Now, filter to only include achievements for games that have at least 50 players who have played a session.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id
HAVING COUNT(DISTINCT gs.player_id) >= 50;

[User] Please also include the number of times each achievement has been unlocked by unique players, labeled as unique_unlocks.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions,
       (SELECT COUNT(DISTINCT gs2.player_id)
        FROM gaming_technology.game_sessions gs2
        WHERE gs2.game_id = a.game_id) AS unique_unlocks
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id
HAVING COUNT(DISTINCT gs.player_id) >= 50;

[User] I think unique_unlocks should be the count of distinct players who have unlocked each specific achievement, not just played a session. Can you correct that?

[Assistant] -- With the provided tables, there is no direct record of players unlocking a specific achievement, unless unlocking is inferred elsewhere. If you have an achievement unlocks table, you could join it here. Otherwise, only possible to count sessions per game.

[User] Show all cities in the USA that have more than one distinct location type represented. List the city, country, and number of distinct location types.

[Assistant]
SELECT city, country, COUNT(DISTINCT type) AS distinct_location_types
FROM transportation.locations
WHERE country = 'USA'
GROUP BY city, country
HAVING COUNT(DISTINCT type) > 1;

[User] Show all peers whose last_seen timestamp is before '2023-01-01' and whose port number is less than 1000, listing their peer_id and ip_address.

[Assistant] SELECT peer_id, ip_address FROM trading_platform.peers WHERE last_seen < '2023-01-01' AND port < 1000;

[User] I need the average capacity of vehicles for each fuel_type.

[Assistant]
SELECT fuel_type,
       AVG(capacity) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type;

[User] Only include fuel types where the vehicle count is at least 10.

[Assistant]
SELECT fuel_type,
       AVG(capacity) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 10;

[User] Also show the number of vehicles for each of these fuel types.

[Assistant]
SELECT fuel_type,
       COUNT(*) AS vehicle_count,
       AVG(capacity) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 10;

[User] Please round avg_capacity to one decimal place.

[Assistant]
SELECT fuel_type,
       COUNT(*) AS vehicle_count,
       ROUND(AVG(capacity)::numeric, 1) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 10;

[User] List all appointments that have a location specified and their status is not 'Cancelled'. Show the appointment ID, subject, and location.

[Assistant] SELECT appointment_id, subject, location FROM legal_services.appointments WHERE location IS NOT NULL AND status <> 'Cancelled';

[User] Also, include appointments that have a case ID assigned. Order the final list by start time ascending.

[Assistant] SELECT appointment_id, subject, location FROM legal_services.appointments WHERE (location IS NOT NULL AND status <> 'Cancelled') OR case_id IS NOT NULL ORDER BY start_time ASC;

[User] Show me the email and full name of passengers who are enrolled in a loyalty program, along with the date they joined, ordered by most recent sign-up.

[Assistant] SELECT email, CONCAT(first_name, ' ', last_name) AS full_name, created_at FROM transportation.passengers WHERE loyalty_program_id IS NOT NULL ORDER BY created_at DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text, transaction_id text, output_index integer, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text, asset_id text, key text, value text )
CREATE TABLE trading_platform.logs ( log_id text, user_id text, action text, details text, logged_at timestamp )
##Table Structure
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 character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
##Table Structure
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 )

[User] Show the average gas_price for each transaction status.

[Assistant]
SELECT status, AVG(gas_price) AS avg_gas_price
FROM web3.transactions
GROUP BY status;

[User] Actually, can you also include the total number of transactions for each status in the result?

[Assistant]
SELECT status, AVG(gas_price) AS avg_gas_price, COUNT(*) AS transaction_count
FROM web3.transactions
GROUP BY status;

[User] Provide each trip's ID, vehicle license plate, driver's full name, origin city, and destination city.

[Assistant]
SELECT t.trip_id,
       v.license_plate,
       CONCAT(d.first_name, ' ', d.last_name) AS driver_name,
       lo.city AS origin_city,
       ld.city AS destination_city
FROM transportation.trips t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
JOIN transportation.drivers d ON t.driver_id = d.driver_id
JOIN transportation.locations lo ON t.origin_location_id = lo.location_id
JOIN transportation.locations ld ON t.destination_location_id = ld.location_id;

[User] For each user, show the total amount of unspent UTXOs across all their wallets.

[Assistant] SELECT w.user_id, SUM(u.amount) AS total_unspent_amount FROM trading_platform.wallets w JOIN trading_platform.utxos u ON w.address = u.address WHERE u.spent = FALSE GROUP BY w.user_id;

[User] Now, filter this list to only include users where the total unspent amount is greater than 500.

[Assistant] SELECT w.user_id, SUM(u.amount) AS total_unspent_amount FROM trading_platform.wallets w JOIN trading_platform.utxos u ON w.address = u.address WHERE u.spent = FALSE GROUP BY w.user_id HAVING SUM(u.amount) > 500;

[User] For each service category, count the number of appointments scheduled in the next 7 days. Return the category and appointment count.

[Assistant]
SELECT s.category, COUNT(a.appointment_id) AS upcoming_appointments
FROM government_services.appointments a
JOIN government_services.services s ON a.service_id = s.service_id
WHERE a.scheduled_start_time BETWEEN now() AND now() + interval '7 days'
GROUP BY s.category;

[User] For each client, show the earliest and latest invoice issue_date, along with the total amount invoiced. Include client_id, earliest_issue_date, latest_issue_date, and total_amount.

[Assistant]
SELECT client_id, MIN(issue_date) AS earliest_issue_date, MAX(issue_date) AS latest_issue_date, SUM(total_amount) AS total_amount
FROM legal_services.invoices
GROUP BY client_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. You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.platforms ( platform_id text PRIMARY KEY, station_id text, platform_number text, track_number text, status text, length_meters numeric, accessible boolean )
##Table Structure
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 )
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes 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 )
##Table Structure
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 ) 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.staff ( staff_id text PRIMARY KEY, first_name text, last_name text, role text, primary_station_id text, employee_number text UNIQUE, hire_date date, contact_email text UNIQUE, contact_phone text, is_active boolean ) 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.stations ( station_id character varying(64) NOT NULL, station_name character varying(128) NOT NULL, city character varying(100) NOT NULL, state_province character varying(100), country_code character varying(3) NOT NULL, address text, timezone character varying(64) NOT NULL, number_of_platforms integer NOT NULL DEFAULT 0, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (station_id) ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.platforms ( platform_id.text, station_id.text, platform_number.text, track_number.text, status.text, length_meters.numeric, accessible.boolean )
##Table Structure
CREATE TABLE web3.contracts ( contract_id text, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text ) You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.platforms ( platform_id character varying(64) NOT NULL, station_id character varying(64) NOT NULL, platform_number character varying(10) NOT NULL, track_number character varying(10), status character varying(32) NOT NULL DEFAULT 'Operational', length_meters numeric(8,2), accessible boolean NOT NULL DEFAULT false, PRIMARY KEY (platform_id), FOREIGN KEY (station_id) REFERENCES train_station_management.stations(station_id) )
##Table Structure
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp ) 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.trains ( train_id text, train_number text, model text, manufacturer text, year_manufactured integer, capacity integer, status text, last_maintenance_date date, next_maintenance_date date )
##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 )
##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 )
##Table Structure
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )

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

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

[User] How many messages in total have been sent that do not contain any media attachment?

[Assistant]
SELECT COUNT(*) AS non_media_message_count
FROM social_media.messages
WHERE media_url IS NULL OR media_url = '';

[User] For each user, show their user ID and the count of unique wallet addresses they own.

[Assistant] SELECT user_id, COUNT(DISTINCT address) FROM wallets GROUP BY user_id;

[User] How many appointments are scheduled at each location?

[Assistant] SELECT location_id, COUNT(*) AS scheduled_count FROM healthcare.appointments WHERE status = 'scheduled' GROUP BY location_id;

[User] Which route numbers connect locations with a distance less than 80 km and more than 5 words in their description? Include the route type in the results.

[Assistant] SELECT route_number, type FROM transportation.routes WHERE distance_km < 80 AND array_length(regexp_split_to_array(description, '\s+'), 1) > 5;

[User] What are the training programs or certifications completed by a staff member with the role of Platform Supervisor?

[Assistant] I'm sorry, but I don't have access to information about the training programs or certifications completed by staff members. The data available to me only includes basic staff details such as name, role, and contact information. For details on training or certifications, please refer to the HR department or relevant training records.

[User] What are the ticket prices for trains departing from the station with ID 'ST456'?

[Assistant] I'm sorry, but I can't provide information on ticket prices as this data is not included in the station management database. For ticket pricing, please refer to the ticketing system or contact customer service.

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

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

[User] For each network, list the deployer address and the number of contracts they have deployed, ordered from most to least.

[Assistant] SELECT network_id, deployer_address, COUNT(*) AS deployed_contracts FROM web3.contracts GROUP BY network_id, deployer_address ORDER BY network_id, deployed_contracts DESC;

[User] What is the current number of passengers waiting at platform 2B at station ABC?

[Assistant] I'm sorry, but I can't provide information on the current number of passengers at a specific platform. The data in the platforms table only includes details like platform number, track number, status, length, and accessibility. For real-time passenger counts, you may need to refer to station monitoring systems or staff reports.

[User] How many participants are there in each conversation? Return conversation_id and participant_count.

[Assistant]
SELECT conversation_id,
       COUNT(*) AS participant_count
FROM social_media.conversation_participants
GROUP BY conversation_id;

[User] What is the detailed repair history for train number T5678?

[Assistant] I'm sorry, but I can't provide the detailed repair history for train number T5678 as this information is not available in the current database table. The table only includes basic information such as train ID, model, manufacturer, capacity, status, and maintenance dates. For repair history, you may need to consult a different database or department.

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

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

[User] For each city and state, show the number of service locations available along with their accessibility status.

[Assistant] SELECT city, state, is_accessible, COUNT(*) AS location_count FROM government_services.service_locations GROUP BY city, state, is_accessible;

[User] List all asset symbols where the asset type is 'token'.

[Assistant] SELECT symbol FROM trading_platform.assets WHERE 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 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 )
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.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.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 )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE social_media.messages ( message_id.text, conversation_id.text, sender_user_id.text, content.text, media_url.text, media_type.text, sent_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)
CREATE TABLE transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] Count how many doctors have an email address ending with '.com'.

[Assistant] SELECT count(*) FROM healthcare.doctors WHERE email LIKE '%.com';

[User] I want to find all notifications for messages containing the word 'holiday' in their content; include notification_id, message content, and notification created_at.

[Assistant]
SELECT n.notification_id, m.content, n.created_at
FROM social_media.notifications AS n
JOIN social_media.messages AS m
  ON n.target_entity_type = 'message'
  AND n.target_entity_id = m.message_id
WHERE m.content LIKE '%holiday%';

[User] Could you filter this to only include notifications sent after '2024-05-01' and order by created_at descending?

[Assistant]
SELECT n.notification_id, m.content, n.created_at
FROM social_media.notifications AS n
JOIN social_media.messages AS m
  ON n.target_entity_type = 'message'
  AND n.target_entity_id = m.message_id
WHERE m.content LIKE '%holiday%'
  AND n.created_at > '2024-05-01'
ORDER BY n.created_at DESC;

[User] List all fuel refueling events with the refueled vehicle's make and model, the fuel type used, and the fueling location ID.

[Assistant]
SELECT fl.fuel_log_id, fl.log_timestamp, v.make, v.model, fl.fuel_type, fl.quantity, fl.unit, fl.total_cost, fl.location_id
FROM transportation.fuel_logs fl
JOIN transportation.vehicles v ON fl.vehicle_id = v.vehicle_id;

[User] Find claims where documents were uploaded by more than one distinct user. Show the claim_id.

[Assistant] SELECT claim_id FROM insurance.claim_documents GROUP BY claim_id HAVING COUNT(DISTINCT uploaded_by) > 1;

[User] Can you also include the total number of distinct uploaders and the total number of documents for each of those claims? Label them as distinct_uploaders and total_documents.

[Assistant] SELECT claim_id, COUNT(DISTINCT uploaded_by) AS distinct_uploaders, COUNT(*) AS total_documents FROM insurance.claim_documents GROUP BY claim_id HAVING COUNT(DISTINCT uploaded_by) > 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 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.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 )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.service_locations ( location_id.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 )
CREATE TABLE government_services.appointments ( appointment_id.text, 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.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.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.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )

[User] For each employee who acts as a manager, please show the number of employees directly reporting to them.

[Assistant] SELECT m.first_name || ' ' || m.last_name AS manager_name, COUNT(e.employee_id) AS direct_report_count FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id GROUP BY m.employee_id, manager_name;

[User] Include the department of the manager in the output as well.

[Assistant] SELECT m.first_name || ' ' || m.last_name AS manager_name, m.department, COUNT(e.employee_id) AS direct_report_count FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id GROUP BY m.employee_id, manager_name, m.department;

[User] Only list managers who have fewer than 10 direct reports.

[Assistant] SELECT m.first_name || ' ' || m.last_name AS manager_name, m.department, COUNT(e.employee_id) AS direct_report_count FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id GROUP BY m.employee_id, manager_name, m.department HAVING COUNT(e.employee_id) < 10;

[User] Get appointment_id, scheduled_start_time, service_name, location_name, and city for all appointments booked via 'Phone' at accessible locations.

[Assistant] SELECT ap.appointment_id, ap.scheduled_start_time, s.service_name, sl.location_name, sl.city FROM government_services.appointments ap JOIN government_services.services s ON s.service_id = ap.service_id JOIN government_services.service_locations sl ON sl.location_id = ap.location_id WHERE ap.booking_method = 'Phone' AND sl.is_accessible = TRUE;

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

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

[User] List all replacement policies where a customer received a new policy starting the day after their previous policy was cancelled. Return customer_id, original_policy_id, original_cancellation_date, new_policy_id, new_start_date.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day';

[User] Now include the premium_amount difference as premium_diff and only show cases where the new policy's premium is higher.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date,
       (nw.premium_amount - orig.premium_amount) AS premium_diff
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day'
WHERE nw.premium_amount > orig.premium_amount;

[User] Show me a list of all customers from California along with their full names and phone numbers.

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number FROM insurance.customers WHERE state = 'CA';

[User] Can you also include their email addresses in the results?

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number, email FROM insurance.customers WHERE state = 'CA';

[User] Actually, show me only those customers whose status is 'active'.

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number, email FROM insurance.customers WHERE state = 'CA' AND status = 'active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id text, first_name text, last_name text, bar_number text, firm_id text, email text, phone text, specialization text, hire_date timestamp, is_partner boolean )
##Table Structure
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, 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 )
##Table Structure
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.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 )
##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) )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
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 text, case_number text, 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, 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.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
##Table Structure
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )

[User] Retrieve the driver_id, first_name, and last_name for all drivers whose license_expiry_date falls within the next 6 months from today.

[Assistant]
SELECT driver_id, first_name, last_name
FROM transportation.drivers
WHERE license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '6 months';

[User] Now, also include those drivers' email addresses and sort the results by license_expiry_date ascending.

[Assistant]
SELECT driver_id, first_name, last_name, email
FROM transportation.drivers
WHERE license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '6 months'
ORDER BY license_expiry_date ASC;

[User] List each partner’s full name along with the full name of a non-partner lawyer in the same firm.

[Assistant]
SELECT p.lawyer_id,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_full_name,
       CONCAT(n.first_name, ' ', n.last_name) AS non_partner_full_name
FROM legal_services.lawyers p
JOIN legal_services.lawyers n
  ON p.firm_id = n.firm_id
  AND p.lawyer_id <> n.lawyer_id
WHERE p.is_partner = TRUE
  AND n.is_partner = FALSE;

[User] Only include non-partner lawyers hired after 2023-01-01.

[Assistant]
SELECT p.lawyer_id,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_full_name,
       CONCAT(n.first_name, ' ', n.last_name) AS non_partner_full_name
FROM legal_services.lawyers p
JOIN legal_services.lawyers n
  ON p.firm_id = n.firm_id
  AND p.lawyer_id <> n.lawyer_id
WHERE p.is_partner = TRUE
  AND n.is_partner = FALSE
  AND n.hire_date > '2023-01-01';

[User] Show the service names that had documents uploaded for their applications in the calendar year 2023.

[Assistant] SELECT DISTINCT T1.service_name FROM government_services.services AS T1 JOIN applications AS T2 ON T1.service_id = T2.service_id JOIN government_services.documents AS T3 ON T2.application_id = T3.application_id WHERE EXTRACT(YEAR FROM T3.upload_timestamp) = 2023

[User] Only include services belonging to the 'Healthcare' category.

[Assistant] SELECT DISTINCT T1.service_name FROM government_services.services AS T1 JOIN applications AS T2 ON T1.service_id = T2.service_id JOIN government_services.documents AS T3 ON T2.application_id = T3.application_id WHERE EXTRACT(YEAR FROM T3.upload_timestamp) = 2023 AND T1.category = 'Healthcare'

[User] Find all documents that are larger than 5MB. Show the document ID, claim ID, file name, and file size in bytes.

[Assistant]
SELECT document_id, claim_id, file_name, file_size_bytes
FROM insurance.claim_documents
WHERE file_size_bytes > 5242880;

[User] What is the total number of messages sent with a media URL?

[Assistant] SELECT COUNT(*) FROM social_media.messages WHERE media_url IS NOT NULL;

[User] Which clients have at least one open case, and what are the names and numbers of those cases?

[Assistant]
SELECT c.first_name, c.last_name, cs.case_name, cs.case_number
FROM legal_services.clients c
JOIN legal_services.cases cs ON c.client_id = cs.client_id
WHERE cs.status = 'Open';

[User] Show the count of vehicles for each type.

[Assistant] SELECT type, COUNT(*) AS vehicle_count FROM transportation.vehicles GROUP BY type;

[User] Only include types where the vehicle count is greater than 2 and order the results by vehicle_count descending.

[Assistant] SELECT type, COUNT(*) AS vehicle_count FROM transportation.vehicles GROUP BY type HAVING COUNT(*) > 2 ORDER BY vehicle_count DESC;

[User] What is the average interest rate for auto loans (loan_type = 'Auto') with a principal amount between $20,000 and $50,000?

[Assistant] SELECT AVG(interest_rate) AS avg_interest_rate FROM financial_services.loans WHERE loan_type = 'Auto' AND principal_amount BETWEEN 20000 AND 50000;


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,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.notifications (
    notification_id character varying(64) NOT NULL,  -- unique identifier for the notification
    user_id character varying(64) NOT NULL, -- identifier of the user receiving the notification
    message text NOT NULL, -- message of the notification
    sent_at timestamp NOT NULL, -- time when the notification was sent
    read_at timestamp, -- time when the notification was read
    PRIMARY KEY (notification_id)
)
##Table Structure
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 )
##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 )
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, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )
##Table Structure
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )

[User] Show all wallet addresses that have ever received a UTXO.

[Assistant]
SELECT DISTINCT address
FROM trading_platform.utxos;

[User] Show me all invoice numbers and due dates where the amount paid is exactly zero.

[Assistant] SELECT invoice_number, due_date FROM legal_services.invoices WHERE amount_paid = 0;

[User] Find all patients who have more than two primary active insurance policies, showing their patient ID and the count of such policies. Also, list the plan names for these policies.

[Assistant]
SELECT pi.patient_id, COUNT(*) AS active_primary_policy_count, STRING_AGG(ip.plan_name, ', ') AS plan_names
FROM healthcare.patient_insurance pi
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE pi.is_primary = TRUE AND (pi.expiration_date IS NULL OR pi.expiration_date > CURRENT_DATE)
GROUP BY pi.patient_id
HAVING COUNT(*) > 2;

[User] Find all pairs of citizens who share the same last name but have different dates of birth. Display both full names, the shared last name, and each date of birth.

[Assistant]
SELECT
  c1.first_name || ' ' || c1.last_name AS citizen1_name,
  c2.first_name || ' ' || c2.last_name AS citizen2_name,
  c1.last_name AS shared_last_name,
  c1.date_of_birth AS dob1,
  c2.date_of_birth AS dob2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.last_name = c2.last_name
     AND c1.citizen_id < c2.citizen_id
     AND c1.date_of_birth <> c2.date_of_birth;

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

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

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

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

[User] Show me all participants who joined any conversation before January 1st, 2024. Return participant_id, user_id, conversation_id and the joined_at timestamp.

[Assistant] SELECT participant_id, user_id, conversation_id, joined_at FROM social_media.conversation_participants WHERE joined_at < '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.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 )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
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 text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )

[User] Show each vehicle's ID along with another vehicle's ID where they share the same make but have different models. Sort by the first vehicle_id.

[Assistant]
SELECT v1.vehicle_id AS vehicle_a, v2.vehicle_id AS vehicle_b
FROM transportation.vehicles v1
JOIN transportation.vehicles v2
  ON v1.make = v2.make
  AND v1.model <> v2.model
ORDER BY v1.vehicle_id;

[User] Oops, I only want pairs where both vehicles have status 'Active'.

[Assistant]
SELECT v1.vehicle_id AS vehicle_a, v2.vehicle_id AS vehicle_b
FROM transportation.vehicles v1
JOIN transportation.vehicles v2
  ON v1.make = v2.make
  AND v1.model <> v2.model
WHERE v1.status = 'Active'
  AND v2.status = 'Active'
ORDER BY v1.vehicle_id;

[User] Also include the year and capacity of both vehicles in the output.

[Assistant]
SELECT v1.vehicle_id AS vehicle_a,
       v1.year   AS year_a,
       v1.capacity AS capacity_a,
       v2.vehicle_id AS vehicle_b,
       v2.year   AS year_b,
       v2.capacity AS capacity_b
FROM transportation.vehicles v1
JOIN transportation.vehicles v2
  ON v1.make = v2.make
  AND v1.model <> v2.model
WHERE v1.status = 'Active'
  AND v2.status = 'Active'
ORDER BY v1.vehicle_id;

[User] List the first and last names of all drivers who share a last name with any passenger, along with the passenger's first name.

[Assistant]
SELECT d.first_name AS driver_first_name, d.last_name, p.first_name AS passenger_first_name
FROM transportation.drivers d
JOIN transportation.passengers p ON d.last_name = p.last_name;

[User] Now, only show those pairs where the passenger's loyalty_program_id is not null.

[Assistant]
SELECT d.first_name AS driver_first_name, d.last_name, p.first_name AS passenger_first_name
FROM transportation.drivers d
JOIN transportation.passengers p ON d.last_name = p.last_name
WHERE p.loyalty_program_id IS NOT NULL;

[User] What is the total payment amount for each currency recorded in the payments table?

[Assistant] SELECT currency ,  sum(amount) FROM government_services.payments GROUP BY currency

[User] Now, only show currencies where the total amount paid is greater than 10000.

[Assistant] SELECT currency ,  sum(amount) FROM government_services.payments GROUP BY currency HAVING sum(amount)  >  10000

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

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

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

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

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

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

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

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

[User] List all hashtags created in March 2024 along with their creation timestamps.

[Assistant]
SELECT hashtag_id, tag_name, created_at
FROM social_media.hashtags
WHERE created_at BETWEEN '2024-03-01 00:00:00' AND '2024-03-31 23:59:59';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.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 )
##Table Structure
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text PRIMARY KEY, from_address text, to_address text, value numeric, gas_used int, gas_price numeric, block_number int, timestamp timestamp, input_data text, status text, nonce int )
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
##Table Structure
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )

[User] For each route, show the route number and the total number of trips associated with it.

[Assistant] SELECT T2.route_number, count(T1.trip_id) FROM transportation.trips AS T1 JOIN transportation.routes AS T2 ON T1.route_id = T2.route_id GROUP BY T2.route_number

[User] I want to list all insurance plans along with the number of medical records that have a record_date in 2024. Display plan_id, plan_name, and the total medical records.

[Assistant]
SELECT ip.plan_id, ip.plan_name, COUNT(mr.record_id) AS total_medical_records
FROM healthcare.insurance_plans ip
LEFT JOIN healthcare.medical_records mr ON 1=0 -- there is no direct relationship in schema, so no records will be counted
WHERE mr.record_date >= '2024-01-01' AND mr.record_date < '2025-01-01'
GROUP BY ip.plan_id, ip.plan_name;

[User] Since there's no direct relationship, can you adjust it to just show all insurance plans of type 'EPO' with their plan_id and plan_name?

[Assistant]
SELECT plan_id, plan_name
FROM healthcare.insurance_plans
WHERE plan_type = 'EPO';

[User] List all pairs of active services in the same category where one service’s standard fee is higher than the other’s. Display the category, the higher-fee service name with its fee, and the lower-fee service name with its fee.

[Assistant]
SELECT
  s1.category,
  s1.service_name AS higher_service,
  s1.standard_fee AS higher_fee,
  s2.service_name AS lower_service,
  s2.standard_fee AS lower_fee
FROM government_services.services s1
JOIN government_services.services s2
  ON s1.category = s2.category
  AND s1.standard_fee > s2.standard_fee
WHERE s1.is_active = TRUE
  AND s2.is_active = TRUE;

[User] List all peer logs, showing the user_id and the action taken, ordered by the most recent log entry.

[Assistant]
SELECT user_id, action, logged_at
FROM trading_platform.logs
ORDER BY logged_at DESC;

[User] For each block, compute the total number of transactions and the average gas_price.

[Assistant] SELECT block_number, COUNT(*) AS total_txs, AVG(gas_price) AS avg_gas_price FROM web3.transactions GROUP BY block_number;

[User] Actually, only include blocks with more than 100 transactions.

[Assistant] SELECT block_number, COUNT(*) AS total_txs, AVG(gas_price) AS avg_gas_price FROM web3.transactions GROUP BY block_number HAVING COUNT(*) > 100;

[User] How many events were emitted on each date? List the date and the count of events.

[Assistant]
SELECT DATE(emitted_at) AS emit_date,
       COUNT(*) AS event_count
FROM web3.events
GROUP BY DATE(emitted_at);

[User] Actually, only include dates where more than 10 events were emitted.

[Assistant]
SELECT DATE(emitted_at) AS emit_date,
       COUNT(*) AS event_count
FROM web3.events
GROUP BY DATE(emitted_at)
HAVING COUNT(*) > 10;

[User] How many agents were hired in the current year and what is their average commission rate?

[Assistant] SELECT COUNT(*) AS hired_this_year, AVG(commission_rate) AS average_commission_rate FROM insurance.agents WHERE EXTRACT(YEAR FROM hire_date) = EXTRACT(YEAR FROM CURRENT_DATE);