System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// PUT /schedules
{
  "mappings": {
    "properties": {
      "schedule_id": { "type": "keyword" },
      "train_id": { "type": "keyword" }, // References trains index
      "route_id": { "type": "keyword" }, // References routes index
      "departure_datetime": { "type": "date" }, // ISO 8601 format recommended
      "arrival_datetime": { "type": "date" },
      "status": { "type": "keyword" },
      "notes": { "type": "text" }
    }
  }
}
// PUT /passengers
{
  "mappings": {
    "properties": {
      "passenger_id": { "type": "keyword" },
      "first_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 100 } }
      },
      "last_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 100 } }
       },
      "email": { "type": "keyword" }, // Often used for exact matches
      "phone_number": { "type": "keyword" },
      "date_of_birth": { "type": "date", "format": "yyyy-MM-dd" },
      "loyalty_program_id": { "type": "keyword" },
      "created_at": { "type": "date" }
    }
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE cex_token_balance ( snapshot_time text, chain text, address text, exchange text, token_address text, token_symbol text, balance numeric, usd_value numeric, price numeric )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
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 )

[User] Which exchange holds the largest total USD value of the token with the highest 24h price increase in the 'AI' narrative, and what is that value?

[Assistant]
SELECT ctb.exchange, SUM(ctb.usd_value) AS total_usd_value
FROM token_basic_info tbi
JOIN cex_token_balance ctb ON tbi.token_address = ctb.token_address AND tbi.chain = ctb.chain
WHERE tbi.narrative = 'AI' AND tbi.token_symbol = (
    SELECT token_symbol
    FROM token_basic_info
    WHERE narrative = 'AI'
    ORDER BY price_change_percentage_24h DESC
    LIMIT 1
)
GROUP BY ctb.exchange
ORDER BY total_usd_value DESC
LIMIT 1;

[User] Actually, can you show the top 2 exchanges by total USD value instead of just the top one?

[Assistant]
SELECT ctb.exchange, SUM(ctb.usd_value) AS total_usd_value
FROM token_basic_info tbi
JOIN cex_token_balance ctb ON tbi.token_address = ctb.token_address AND tbi.chain = ctb.chain
WHERE tbi.narrative = 'AI' AND tbi.token_symbol = (
    SELECT token_symbol
    FROM token_basic_info
    WHERE narrative = 'AI'
    ORDER BY price_change_percentage_24h DESC
    LIMIT 1
)
GROUP BY ctb.exchange
ORDER BY total_usd_value DESC
LIMIT 2;

[User] Great, now also include the chain and current price of this token in the results.

[Assistant]
SELECT ctb.exchange, ctb.chain, SUM(ctb.usd_value) AS total_usd_value, tbi.price
FROM token_basic_info tbi
JOIN cex_token_balance ctb ON tbi.token_address = ctb.token_address AND tbi.chain = ctb.chain
WHERE tbi.narrative = 'AI' AND tbi.token_symbol = (
    SELECT token_symbol
    FROM token_basic_info
    WHERE narrative = 'AI'
    ORDER BY price_change_percentage_24h DESC
    LIMIT 1
)
GROUP BY ctb.exchange, ctb.chain, tbi.price
ORDER BY total_usd_value DESC
LIMIT 2;

[User] Which are the top 3 tokens on BSC by total USD value held by all CEXs, and what is their narrative and current price?

[Assistant]
SELECT ctb.token_symbol, tbi.narrative, tbi.price, SUM(ctb.usd_value) AS total_usd_value
FROM cex_token_balance ctb
JOIN token_basic_info tbi ON ctb.token_symbol = tbi.token_symbol AND ctb.chain = tbi.chain
WHERE ctb.chain = 'BSC'
GROUP BY ctb.token_symbol, tbi.narrative, tbi.price
ORDER BY total_usd_value DESC
LIMIT 3;

[User] Can you also show, for each token, the number of CEX addresses holding it?

[Assistant]
SELECT ctb.token_symbol, tbi.narrative, tbi.price, COUNT(DISTINCT ctb.address) AS cex_address_count, SUM(ctb.usd_value) AS total_usd_value
FROM cex_token_balance ctb
JOIN token_basic_info tbi ON ctb.token_symbol = tbi.token_symbol AND ctb.chain = tbi.chain
WHERE ctb.chain = 'BSC'
GROUP BY ctb.token_symbol, tbi.narrative, tbi.price
ORDER BY total_usd_value DESC
LIMIT 3;

[User] Only include tokens with total USD value above 1,000,000.

[Assistant]
SELECT ctb.token_symbol, tbi.narrative, tbi.price, COUNT(DISTINCT ctb.address) AS cex_address_count, SUM(ctb.usd_value) AS total_usd_value
FROM cex_token_balance ctb
JOIN token_basic_info tbi ON ctb.token_symbol = tbi.token_symbol AND ctb.chain = tbi.chain
WHERE ctb.chain = 'BSC'
GROUP BY ctb.token_symbol, tbi.narrative, tbi.price
HAVING SUM(ctb.usd_value) > 1000000
ORDER BY total_usd_value DESC
LIMIT 3;

[User] For the 'DeFi' narrative, what is the average ROI and the total net inflow (usd_value where type=1) from smart money token inflow?

[Assistant]
SELECT AVG(sm.roi) AS avg_roi, SUM(smt.usd_value) AS total_net_inflow
FROM smart_money_token_inflow smt
JOIN smart_money_profit sm ON smt.chain = sm.chain
WHERE smt.narrative = 'DeFi' AND smt.type = 1;

[User] What is the average ROI for smart money addresses on the Binance chain?

[Assistant] SELECT AVG(roi) FROM smart_money_profit WHERE chain = 'Binance';

[User] Show me tokens with a 24-hour trading volume over $1,000,000 from DEX pools that also have a positive net flow from smart money addresses. Display the token symbol, chain, 24h volume, and net flow.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0;

[User] Okay, now refine the results to only include tokens where the smart money ROI is greater than 5 (500%) and the realized ratio is above 0.5.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5;

[User] Add the token's current price from the basic info table and its narrative category to the results.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow, tbi.price AS current_price, tbi.narrative FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain JOIN token_basic_info AS tbi ON tdi.token_symbol = tbi.token_symbol AND tdi.chain = tbi.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5;

[User] Order the final list by 24-hour trading volume descending and show the top 10.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow, tbi.price AS current_price, tbi.narrative FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain JOIN token_basic_info AS tbi ON tdi.token_symbol = tbi.token_symbol AND tdi.chain = tbi.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5 ORDER BY tdi.volume_24h DESC LIMIT 10;

[User] List tokens that have a price increase of more than 10% in the last 24 hours and belong to a narrative with a trend rank of 10 or better. For these tokens, show their symbol, chain, 24h price change, the narrative, and the narrative's trend rank.

[Assistant] SELECT T1.token_symbol, T1.chain, T1.price_change_percentage_24h, T1.narrative, T2.trend_rank FROM token_basic_info AS T1 INNER JOIN narrative_info AS T2 ON T1.narrative = T2.narrative WHERE T1.price_change_percentage_24h > 10 AND T2.trend_rank <= 10;

[User] Now, for these same tokens, include their smart money Net Flow and ROI.

[Assistant] SELECT T1.token_symbol, T1.chain, T1.price_change_percentage_24h, T1.narrative, T2.trend_rank, T3.net_flow, T3.roi FROM token_basic_info AS T1 INNER JOIN narrative_info AS T2 ON T1.narrative = T2.narrative INNER JOIN smart_money_token_performance AS T3 ON T1.token_symbol = T3.token_symbol AND T1.chain = T3.chain WHERE T1.price_change_percentage_24h > 10 AND T2.trend_rank <= 10;

[User] Filter the results to only include tokens where the Smart Money Net Flow is greater than 10000 and the ROI is greater than 2.

[Assistant] SELECT T1.token_symbol, T1.chain, T1.price_change_percentage_24h, T1.narrative, T2.trend_rank, T3.net_flow, T3.roi FROM token_basic_info AS T1 INNER JOIN narrative_info AS T2 ON T1.narrative = T2.narrative INNER JOIN smart_money_token_performance AS T3 ON T1.token_symbol = T3.token_symbol AND T1.chain = T3.chain WHERE T1.price_change_percentage_24h > 10 AND T2.trend_rank <= 10 AND T3.net_flow > 10000 AND T3.roi > 2;

[User] Order the results by Smart Money Net Flow in descending order and show the top 5.

[Assistant] SELECT T1.token_symbol, T1.chain, T1.price_change_percentage_24h, T1.narrative, T2.trend_rank, T3.net_flow, T3.roi FROM token_basic_info AS T1 INNER JOIN narrative_info AS T2 ON T1.narrative = T2.narrative INNER JOIN smart_money_token_performance AS T3 ON T1.token_symbol = T3.token_symbol AND T1.chain = T3.chain WHERE T1.price_change_percentage_24h > 10 AND T2.trend_rank <= 10 AND T3.net_flow > 10000 AND T3.roi > 2 ORDER BY T3.net_flow DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )

[User] Show me pairs of trip IDs that used the same vehicle.

[Assistant]
SELECT
  t1.trip_id AS trip1_id,
  t2.trip_id AS trip2_id
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.vehicle_id = t2.vehicle_id
  AND t1.trip_id < t2.trip_id;

[User] Now, filter this list to only include pairs where both trips have a 'Completed' status.

[Assistant]
SELECT
  t1.trip_id AS trip1_id,
  t2.trip_id AS trip2_id
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.vehicle_id = t2.vehicle_id
  AND t1.trip_id < t2.trip_id
WHERE
  t1.status = 'Completed' AND t2.status = 'Completed';

[User] Show me the total number of passengers transported by each vehicle in the last week, along with the vehicle ID.

[Assistant] SELECT vehicle_id, SUM(passenger_count) AS total_passengers FROM transportation.trips WHERE status = 'completed' AND actual_departure >= CURRENT_DATE - INTERVAL '7 days' GROUP BY vehicle_id;

[User] Can you include the average passenger count per trip for each vehicle as well?

[Assistant] SELECT vehicle_id, SUM(passenger_count) AS total_passengers, AVG(passenger_count) AS avg_passengers_per_trip FROM transportation.trips WHERE status = 'completed' AND actual_departure >= CURRENT_DATE - INTERVAL '7 days' GROUP BY vehicle_id;

[User] Now filter to only show vehicles that transported more than 100 passengers total.

[Assistant] SELECT vehicle_id, SUM(passenger_count) AS total_passengers, AVG(passenger_count) AS avg_passengers_per_trip FROM transportation.trips WHERE status = 'completed' AND actual_departure >= CURRENT_DATE - INTERVAL '7 days' GROUP BY vehicle_id HAVING SUM(passenger_count) > 100;

[User] What is the count of trips for each status?

[Assistant]
SELECT
  status,
  COUNT(*) AS trip_count
FROM transportation.trips
GROUP BY
  status;

[User] Only include statuses with more than 5 trips.

[Assistant]
SELECT
  status,
  COUNT(*) AS trip_count
FROM transportation.trips
GROUP BY
  status
HAVING
  COUNT(*) > 5;

[User] Find consecutive pairs of trips for each vehicle based on the scheduled departure time.

[Assistant]
WITH RankedTrips AS (
  SELECT
    trip_id,
    vehicle_id,
    scheduled_departure,
    origin_location_id,
    destination_location_id,
    ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY scheduled_departure) as rn
  FROM transportation.trips
)
SELECT
  t1.trip_id AS first_trip_id,
  t2.trip_id AS second_trip_id,
  t1.vehicle_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.scheduled_departure AS second_scheduled_departure,
  t1.destination_location_id AS first_destination_location_id,
  t2.origin_location_id AS second_origin_location_id
FROM RankedTrips AS t1
JOIN RankedTrips AS t2
  ON t1.vehicle_id = t2.vehicle_id AND t1.rn + 1 = t2.rn;

[User] From these consecutive pairs, only show those where the destination of the first trip matches the origin of the second trip.

[Assistant]
WITH RankedTrips AS (
  SELECT
    trip_id,
    vehicle_id,
    scheduled_departure,
    origin_location_id,
    destination_location_id,
    ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY scheduled_departure) as rn
  FROM transportation.trips
)
SELECT
  t1.trip_id AS first_trip_id,
  t2.trip_id AS second_trip_id,
  t1.vehicle_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.scheduled_departure AS second_scheduled_departure,
  t1.destination_location_id AS first_destination_location_id,
  t2.origin_location_id AS second_origin_location_id
FROM RankedTrips AS t1
JOIN RankedTrips AS t2
  ON t1.vehicle_id = t2.vehicle_id AND t1.rn + 1 = t2.rn
WHERE
  t1.destination_location_id = t2.origin_location_id;

[User] Also, only include pairs where the time difference between the scheduled departures is less than 24 hours.

[Assistant]
WITH RankedTrips AS (
  SELECT
    trip_id,
    vehicle_id,
    scheduled_departure,
    origin_location_id,
    destination_location_id,
    ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY scheduled_departure) as rn
  FROM transportation.trips
)
SELECT
  t1.trip_id AS first_trip_id,
  t2.trip_id AS second_trip_id,
  t1.vehicle_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.scheduled_departure AS second_scheduled_departure,
  t1.destination_location_id AS first_destination_location_id,
  t2.origin_location_id AS second_origin_location_id
FROM RankedTrips AS t1
JOIN RankedTrips AS t2
  ON t1.vehicle_id = t2.vehicle_id AND t1.rn + 1 = t2.rn
WHERE
  t1.destination_location_id = t2.origin_location_id
  AND t2.scheduled_departure < t1.scheduled_departure + INTERVAL '24 hour';

[User] For each vehicle, list the vehicle_id and the total number of trips it has performed.

[Assistant] SELECT vehicle_id, COUNT(*) AS trip_count FROM transportation.trips GROUP BY vehicle_id;

[User] Can you limit this to only vehicles that have more than 10 trips?

[Assistant] SELECT vehicle_id, COUNT(*) AS trip_count FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 10;

[User] In addition, for these vehicles, can you show the driver_id who has driven the highest number of trips for each vehicle?

[Assistant] SELECT vehicle_id, driver_id, trip_driver_count FROM (SELECT vehicle_id, driver_id, COUNT(*) AS trip_driver_count, ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY COUNT(*) DESC) as rn FROM transportation.trips GROUP BY vehicle_id, driver_id) t WHERE rn = 1 AND vehicle_id IN (SELECT vehicle_id FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 10);

[User] List the booking ID, trip ID, and the booking status for all bookings.

[Assistant] SELECT booking_id, trip_id, status FROM transportation.bookings;

[User] For these bookings, please also include the scheduled departure time of the corresponding trip.

[Assistant] SELECT B.booking_id, B.trip_id, B.status, T.scheduled_departure FROM transportation.bookings AS B JOIN transportation.trips AS T ON B.trip_id = T.trip_id;

[User] Only show bookings for trips with more than 50 passengers.

[Assistant] SELECT B.booking_id, B.trip_id, B.status, T.scheduled_departure FROM transportation.bookings AS B JOIN transportation.trips AS T ON B.trip_id = T.trip_id WHERE T.passenger_count > 50;

[User] Order the results by scheduled departure time in descending order.

[Assistant] SELECT B.booking_id, B.trip_id, B.status, T.scheduled_departure FROM transportation.bookings AS B JOIN transportation.trips AS T ON B.trip_id = T.trip_id WHERE T.passenger_count > 50 ORDER BY T.scheduled_departure 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 hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] List all service orders with quantity greater than 3, showing the order ID, total price, and the staff member who placed the order.

[Assistant]
SELECT order_id, total_price, staff_id_ordered
FROM hospitality_technology.service_orders
WHERE quantity > 3;

[User] Please add the delivery timestamp, and only show orders that were actually delivered (delivery_timestamp is not null).

[Assistant]
SELECT order_id, total_price, staff_id_ordered, delivery_timestamp
FROM hospitality_technology.service_orders
WHERE quantity > 3
  AND delivery_timestamp IS NOT NULL;

[User] Now, show only those orders where the delivered staff is different from the ordered staff, and sort by delivery timestamp ascending.

[Assistant]
SELECT order_id, total_price, staff_id_ordered, staff_id_delivered, delivery_timestamp
FROM hospitality_technology.service_orders
WHERE quantity > 3
  AND delivery_timestamp IS NOT NULL
  AND staff_id_ordered <> staff_id_delivered
ORDER BY delivery_timestamp ASC;

[User] List each staff member who delivered orders, along with the number of orders they delivered.

[Assistant] SELECT staff_id_delivered, COUNT(order_id) AS delivered_orders FROM hospitality_technology.service_orders WHERE staff_id_delivered IS NOT NULL GROUP BY staff_id_delivered;

[User] Only show staff who delivered more than 10 orders.

[Assistant] SELECT staff_id_delivered, COUNT(order_id) AS delivered_orders FROM hospitality_technology.service_orders WHERE staff_id_delivered IS NOT NULL GROUP BY staff_id_delivered HAVING COUNT(order_id) > 10;

[User] Get the total_quantity and total_revenue (sum of total_price) for each staff member who placed orders (staff_id_ordered).

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

[User] Filter to staff who have delivered at least one order (staff_id_delivered is not null).

[Assistant]
SELECT staff_id_ordered,
       SUM(quantity) AS total_quantity,
       SUM(total_price) AS total_revenue
FROM hospitality_technology.service_orders
WHERE staff_id_delivered IS NOT NULL
GROUP BY staff_id_ordered;

[User] For these staff members, list each order along with the previous order they placed, including first_order_timestamp and second_order_timestamp, and the time difference in hours.

[Assistant]
SELECT t1.staff_id_ordered,
       t1.order_id AS first_order_id,
       t2.order_id AS second_order_id,
       t1.order_timestamp AS first_order_timestamp,
       t2.order_timestamp AS second_order_timestamp,
       EXTRACT(EPOCH FROM (t2.order_timestamp - t1.order_timestamp)) / 3600 AS hours_diff
FROM hospitality_technology.service_orders t1
JOIN hospitality_technology.service_orders t2
  ON t1.staff_id_ordered = t2.staff_id_ordered
 AND t2.order_timestamp > t1.order_timestamp
 AND NOT EXISTS (
       SELECT 1 FROM hospitality_technology.service_orders t3
       WHERE t3.staff_id_ordered = t1.staff_id_ordered
         AND t3.order_timestamp > t1.order_timestamp
         AND t3.order_timestamp < t2.order_timestamp
   )
WHERE t1.staff_id_delivered IS NOT NULL
  AND t2.staff_id_delivered IS NOT NULL
ORDER BY t1.staff_id_ordered, t1.order_timestamp;

[User] Show me the total quantity and total price for each service ordered by each guest.

[Assistant] SELECT guest_id, service_id, SUM(quantity) AS total_quantity, SUM(total_price) AS total_price FROM hospitality_technology.service_orders GROUP BY guest_id, service_id;

[User] Show the total revenue and the average order value for each order status.

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

[User] Please only include statuses where the total revenue is above 1000.

[Assistant] SELECT status, SUM(total_price) AS total_revenue, AVG(total_price) AS avg_order_value FROM hospitality_technology.service_orders GROUP BY status HAVING SUM(total_price) > 1000;

[User] Also order the results by total revenue descending.

[Assistant] SELECT status, SUM(total_price) AS total_revenue, AVG(total_price) AS avg_order_value FROM hospitality_technology.service_orders GROUP BY status HAVING SUM(total_price) > 1000 ORDER BY total_revenue DESC;

[User] List the total number of service orders placed by each staff member who delivered the service.

[Assistant] SELECT staff_id_delivered, COUNT(*) AS order_count FROM hospitality_technology.service_orders GROUP BY staff_id_delivered;

[User] Show only those staff members who have delivered at least 20 service orders and order the results by order_count descending.

[Assistant] SELECT staff_id_delivered, COUNT(*) AS order_count FROM hospitality_technology.service_orders GROUP BY staff_id_delivered HAVING COUNT(*) >= 20 ORDER BY order_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text PRIMARY KEY, case_number text UNIQUE, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )

[User] I need the case_number and case_name along with the total billing amount (hours_spent * billing_rate) for cases that are currently open.

[Assistant]
SELECT c.case_number, c.case_name, SUM(te.hours_spent * te.billing_rate) AS total_billing
FROM legal_services.cases c
JOIN legal_services.time_entries te ON c.case_id = te.case_id
WHERE c.status = 'Open'
GROUP BY c.case_number, c.case_name;

[User] Now order the results by total_billing in descending order and limit to the top 5.

[Assistant]
SELECT c.case_number, c.case_name, SUM(te.hours_spent * te.billing_rate) AS total_billing
FROM legal_services.cases c
JOIN legal_services.time_entries te ON c.case_id = te.case_id
WHERE c.status = 'Open'
GROUP BY c.case_number, c.case_name
ORDER BY total_billing DESC
LIMIT 5;

[User] Show me each lawyer’s full name and the count of distinct cases they have logged time against.

[Assistant]
SELECT l.first_name || ' ' || l.last_name AS lawyer_name, COUNT(DISTINCT te.case_id) AS case_count
FROM legal_services.lawyers l
LEFT JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id
GROUP BY l.first_name, l.last_name;

[User] Only include lawyers who have worked on more than 3 distinct cases.

[Assistant]
SELECT l.first_name || ' ' || l.last_name AS lawyer_name, COUNT(DISTINCT te.case_id) AS case_count
FROM legal_services.lawyers l
LEFT JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id
GROUP BY l.first_name, l.last_name
HAVING COUNT(DISTINCT te.case_id) > 3;

[User] Restrict the entries to those dated in 2024.

[Assistant]
SELECT l.first_name || ' ' || l.last_name AS lawyer_name, COUNT(DISTINCT te.case_id) AS case_count
FROM legal_services.lawyers l
LEFT JOIN legal_services.time_entries te
  ON l.lawyer_id = te.lawyer_id
  AND te.date_worked BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY l.first_name, l.last_name
HAVING COUNT(DISTINCT te.case_id) > 3;

[User] Also include their specialization in the result set.

[Assistant]
SELECT l.first_name || ' ' || l.last_name AS lawyer_name, l.specialization, COUNT(DISTINCT te.case_id) AS case_count
FROM legal_services.lawyers l
LEFT JOIN legal_services.time_entries te
  ON l.lawyer_id = te.lawyer_id
  AND te.date_worked BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY l.first_name, l.last_name, l.specialization
HAVING COUNT(DISTINCT te.case_id) > 3;

[User] List the full name (first and last) and specialization of all lawyers who work for law firms founded before the year 2000.

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T2.founded_date < '2000-01-01'

[User] From that list, could you only show those lawyers whose specialization is 'Environmental Law'?

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T2.founded_date < '2000-01-01' AND T1.specialization = 'Environmental Law'

[User] Also include their hire date and order the results by specialization then hire date.

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization, T1.hire_date FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T2.founded_date < '2000-01-01' AND T1.specialization = 'Environmental Law' ORDER BY T1.specialization, T1.hire_date

[User] Show me case number, case name, and the lead lawyer's full name for all cases in the 'State Court' jurisdiction.

[Assistant] SELECT T1.case_number, T1.case_name, T2.first_name, T2.last_name FROM cases AS T1 JOIN lawyers AS T2 ON T1.lead_lawyer_id = T2.lawyer_id WHERE T1.court_jurisdiction = 'State Court'

[User] From those cases, only list the ones whose status is 'Open'.

[Assistant] SELECT T1.case_number, T1.case_name, T2.first_name, T2.last_name FROM cases AS T1 JOIN lawyers AS T2 ON T1.lead_lawyer_id = T2.lawyer_id WHERE T1.court_jurisdiction = 'State Court' AND T1.status = 'Open'

[User] Additionally, restrict the list to cases where the lead lawyer specializes in 'Criminal Defense'.

[Assistant] SELECT T1.case_number, T1.case_name, T2.first_name, T2.last_name FROM cases AS T1 JOIN lawyers AS T2 ON T1.lead_lawyer_id = T2.lawyer_id WHERE T1.court_jurisdiction = 'State Court' AND T1.status = 'Open' AND T2.specialization = 'Criminal Defense'

[User] Just show the case number and case name, ordered by case number.

[Assistant] SELECT T1.case_number, T1.case_name FROM cases AS T1 JOIN lawyers AS T2 ON T1.lead_lawyer_id = T2.lawyer_id WHERE T1.court_jurisdiction = 'State Court' AND T1.status = 'Open' AND T2.specialization = 'Criminal Defense' ORDER BY T1.case_number

[User] Show me the names of all law firms and the total number of lawyers associated with each firm.

[Assistant] SELECT T1.firm_name, count(T2.lawyer_id) FROM legal_services.law_firms AS T1 JOIN legal_services.lawyers AS T2 ON T1.firm_id = T2.firm_id GROUP BY T1.firm_id, T1.firm_name

[User] Show me the total billable hours and total billed amount for each lawyer who worked on 'Civil Litigation' cases in 2023, sorted by billed amount descending.

[Assistant]
SELECT te.lawyer_id,
       SUM(te.hours_spent) AS total_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS total_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id
ORDER BY total_billed_amount DESC;

[User] Actually, I'd like to include only those lawyers who have at least 10 billable entries in that period.

[Assistant]
SELECT te.lawyer_id,
       SUM(te.hours_spent) AS total_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS total_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id
HAVING COUNT(*) >= 10
ORDER BY total_billed_amount DESC;

[User] Also break down the report by case, listing each lawyer and case_number along with their billable hours and billed amount per case, sorted by billed amount descending.

[Assistant]
SELECT te.lawyer_id,
       c.case_number,
       SUM(te.hours_spent) AS case_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS case_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id, c.case_number
ORDER BY case_billed_amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )

[User] Find users who have both commented on a post and liked that same post. Return the user_id and the count of such posts as post_count.

[Assistant]
SELECT c.user_id, COUNT(DISTINCT c.post_id) AS post_count
FROM social_media.comments c
JOIN social_media.likes l ON c.user_id = l.user_id
  AND c.post_id = l.post_id
WHERE l.post_id IS NOT NULL
GROUP BY c.user_id;

[User] Additionally, include only those cases where they also liked their own comment on that post. Return user_id, post_id, and comment_id.

[Assistant]
SELECT c.user_id, c.post_id, c.comment_id
FROM social_media.comments c
JOIN social_media.likes l ON c.comment_id = l.comment_id
  AND l.user_id = c.user_id
WHERE l.comment_id IS NOT NULL;

[User] List all group conversations that have at least one unread notification, include the conversation ID, group name, and the count of unread notifications as unread_count.

[Assistant]
SELECT c.conversation_id, c.group_name, COUNT(n.notification_id) AS unread_count
FROM social_media.conversations c
JOIN social_media.notifications n ON c.conversation_id = n.target_entity_id
  AND n.target_entity_type = 'conversation'
WHERE c.is_group_chat = true
  AND n.read_at IS NULL
GROUP BY c.conversation_id, c.group_name;

[User] Actually, only include unread notifications of type 'mention'.

[Assistant]
SELECT c.conversation_id, c.group_name, COUNT(n.notification_id) AS unread_count
FROM social_media.conversations c
JOIN social_media.notifications n ON c.conversation_id = n.target_entity_id
  AND n.target_entity_type = 'conversation'
WHERE c.is_group_chat = true
  AND n.read_at IS NULL
  AND n.notification_type = 'mention'
GROUP BY c.conversation_id, c.group_name;

[User] Also, show the most recent unread notification timestamp for each conversation as last_unread_at.

[Assistant]
SELECT c.conversation_id, c.group_name, COUNT(n.notification_id) AS unread_count, MAX(n.created_at) AS last_unread_at
FROM social_media.conversations c
JOIN social_media.notifications n ON c.conversation_id = n.target_entity_id
  AND n.target_entity_type = 'conversation'
WHERE c.is_group_chat = true
  AND n.read_at IS NULL
  AND n.notification_type = 'mention'
GROUP BY c.conversation_id, c.group_name;

[User] Finally, order the results by unread_count descending.

[Assistant]
SELECT c.conversation_id, c.group_name, COUNT(n.notification_id) AS unread_count, MAX(n.created_at) AS last_unread_at
FROM social_media.conversations c
JOIN social_media.notifications n ON c.conversation_id = n.target_entity_id
  AND n.target_entity_type = 'conversation'
WHERE c.is_group_chat = true
  AND n.read_at IS NULL
  AND n.notification_type = 'mention'
GROUP BY c.conversation_id, c.group_name
ORDER BY unread_count DESC;

[User] List user IDs and the creation timestamp of likes made by users who have email notifications enabled.

[Assistant] SELECT T1.user_id, T1.created_at FROM social_media.likes AS T1 JOIN social_media.user_settings AS T2 ON T1.user_id = T2.user_id WHERE T2.email_notifications_enabled = true;

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

[Assistant] SELECT T1.user_id, T1.created_at FROM social_media.likes AS T1 JOIN social_media.user_settings AS T2 ON T1.user_id = T2.user_id WHERE T2.email_notifications_enabled = true AND T1.created_at >= '2024-01-01' AND T1.created_at < '2025-01-01';

[User] Filter to only include users whose profile is not private.

[Assistant] SELECT T1.user_id, T1.created_at FROM social_media.likes AS T1 JOIN social_media.user_settings AS T2 ON T1.user_id = T2.user_id WHERE T2.email_notifications_enabled = true AND T1.created_at >= '2024-01-01' AND T1.created_at < '2025-01-01' AND T2.private_profile = false;

[User] Count the total number of group chats.

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

[User] Show me the usernames and group names for all users who received a 'mention' notification related to group conversations, and when those notifications were created.

[Assistant]
SELECT us.user_id, us.theme AS username, c.group_name, n.created_at
FROM social_media.notifications n
JOIN social_media.conversations c
  ON n.target_entity_id = c.conversation_id AND n.target_entity_type = 'conversation' AND c.is_group_chat = true
JOIN social_media.user_settings us
  ON n.recipient_user_id = us.user_id
WHERE n.notification_type = 'mention';

[User] Actually, only include notifications sent after June 1, 2024.

[Assistant]
SELECT us.user_id, us.theme AS username, c.group_name, n.created_at
FROM social_media.notifications n
JOIN social_media.conversations c
  ON n.target_entity_id = c.conversation_id AND n.target_entity_type = 'conversation' AND c.is_group_chat = true
JOIN social_media.user_settings us
  ON n.recipient_user_id = us.user_id
WHERE n.notification_type = 'mention'
  AND n.created_at > '2024-06-01';

[User] Show only users whose theme is set to 'light' and the group name contains the word 'Team'.

[Assistant]
SELECT us.user_id, us.theme AS username, c.group_name, n.created_at
FROM social_media.notifications n
JOIN social_media.conversations c
  ON n.target_entity_id = c.conversation_id AND n.target_entity_type = 'conversation' AND c.is_group_chat = true
JOIN social_media.user_settings us
  ON n.recipient_user_id = us.user_id
WHERE n.notification_type = 'mention'
  AND n.created_at > '2024-06-01'
  AND us.theme = 'light'
  AND c.group_name ILIKE '%Team%';

[User] How many likes were given to comments in June 2024?

[Assistant]
SELECT COUNT(*) AS comment_likes_count
FROM social_media.likes
WHERE comment_id IS NOT NULL
  AND DATE_TRUNC('month', created_at) = '2024-06-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 legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )

[User] Show me the names, founding dates, and websites of all law firms whose name contains the word 'Legal' and were founded after the year 2005. Sort the results by their founding date.

[Assistant] SELECT firm_name, founded_date, website FROM legal_services.law_firms WHERE firm_name LIKE '%Legal%' AND founded_date > '2005-12-31' ORDER BY founded_date ASC;

[User] List pairs of law firms that are located at the same address. Display the names of both firms and the shared address, ensuring the address is not null.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.address
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.address = t2.address
WHERE
  t1.firm_id < t2.firm_id AND t1.address IS NOT NULL;

[User] Only show pairs where both firms were founded before 2020.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.address
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.address = t2.address
WHERE
  t1.firm_id < t2.firm_id AND t1.address IS NOT NULL AND EXTRACT(YEAR FROM t1.founded_date) < 2020 AND EXTRACT(YEAR FROM t2.founded_date) < 2020;

[User] Show me the count of law firms grouped by the year they were founded. Include the founding year and the number of firms.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL
GROUP BY
  founding_year;

[User] Only include years where the firm count is greater than 3.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL
GROUP BY
  founding_year
HAVING
  COUNT(firm_id) > 3;

[User] Also, restrict this count to only include firms that have a website listed.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL AND website IS NOT NULL
GROUP BY
  founding_year
HAVING
  COUNT(firm_id) > 3;

[User] Order the results by the founding year in ascending order.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL AND website IS NOT NULL
GROUP BY
  founding_year
HAVING
  COUNT(firm_id) > 3
ORDER BY
  founding_year ASC;

[User] Find all law firms that share the same address, listing each address and the two firm names.

[Assistant] SELECT f1.address, f1.firm_name AS firm1, f2.firm_name AS firm2 FROM law_firms f1 JOIN law_firms f2 ON f1.address = f2.address AND f1.firm_id < f2.firm_id;

[User] Actually, only show addresses containing the word 'Street'.

[Assistant] SELECT f1.address, f1.firm_name AS firm1, f2.firm_name AS firm2 FROM law_firms f1 JOIN law_firms f2 ON f1.address = f2.address AND f1.firm_id < f2.firm_id WHERE f1.address LIKE '%Street%';

[User] List all pairs of law firms founded in the same year, showing the two firm names and the shared year.

[Assistant] SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS year FROM law_firms f1 JOIN law_firms f2 ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date) AND f1.firm_id <> f2.firm_id;

[User] Actually, only include years after 2000.

[Assistant] SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS year FROM law_firms f1 JOIN law_firms f2 ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date) AND f1.firm_id <> f2.firm_id WHERE EXTRACT(YEAR FROM f1.founded_date) > 2000;

[User] And ensure each pair only appears once.

[Assistant] SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS year FROM law_firms f1 JOIN law_firms f2 ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date) AND f1.firm_id < f2.firm_id WHERE EXTRACT(YEAR FROM f1.founded_date) > 2000;

[User] Find pairs of law firms that share the same managing partner. List the names of both firms and the managing partner ID, but only show pairs where the managing partner ID is not null.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.managing_partner_id
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.managing_partner_id = t2.managing_partner_id
WHERE
  t1.firm_id < t2.firm_id AND t1.managing_partner_id IS NOT NULL;

[User] Refine this to only include pairs where the managing partner ID starts with 'MPG_'.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.managing_partner_id
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.managing_partner_id = t2.managing_partner_id
WHERE
  t1.firm_id < t2.firm_id AND t1.managing_partner_id LIKE 'MPG_%';

[User] Further filter to only show pairs where both firms were founded after 2015.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.managing_partner_id
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.managing_partner_id = t2.managing_partner_id
WHERE
  t1.firm_id < t2.firm_id AND t1.managing_partner_id LIKE 'MPG_%' AND EXTRACT(YEAR FROM t1.founded_date) > 2015 AND EXTRACT(YEAR FROM t2.founded_date) > 2015;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id uuid PRIMARY KEY, game_id uuid, server_name text, region text, ip_address text, port int, current_players int, max_players int, status text, last_heartbeat timestamptz )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid PRIMARY KEY, player_id uuid, achievement_id uuid, unlocked_at timestamptz )
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 )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )

[User] Show me the title of each game and the total number of game sessions played on servers hosting that game.

[Assistant] SELECT t1.title, count(t3.session_id) FROM gaming_technology.games AS t1 JOIN gaming_technology.servers AS t2 ON t1.game_id = t2.game_id JOIN gaming_technology.game_sessions AS t3 ON t2.server_id = t3.server_id GROUP BY 1

[User] Now, filter this list to only include games with more than 1000 total sessions, and order the results by session count descending.

[Assistant] SELECT t1.title, count(t3.session_id) FROM gaming_technology.games AS t1 JOIN gaming_technology.servers AS t2 ON t1.game_id = t2.game_id JOIN gaming_technology.game_sessions AS t3 ON t2.server_id = t3.server_id GROUP BY 1 HAVING count(t3.session_id) > 1000 ORDER BY count(t3.session_id) DESC

[User] Find all in-game items that have a 'mana_cost' attribute in their attributes JSON. Show the item ID, item name, and the value of the 'mana_cost'.

[Assistant] SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost'

[User] Now, only include items where the 'mana_cost' is greater than 50.

[Assistant] SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost' AND (attributes ->> 'mana_cost')::int > 50

[User] Add the item's rarity and the title of the game it belongs to in the output.

[Assistant] SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50

[User] Filter the results to only include items from games in the 'Fantasy' genre.

[Assistant] SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50 AND t2.genre = 'Fantasy'

[User] Show me the top 5 games by number of online servers in European regions. I want the game title and the server count.

[Assistant]
SELECT g.title, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.servers s ON g.game_id = s.game_id
WHERE s.region ILIKE 'eu%' AND s.status = 'online'
GROUP BY g.title
ORDER BY server_count DESC
LIMIT 5;

[User] Now include only those games whose average current_players per online server exceeds 100.

[Assistant]
SELECT g.title,
       COUNT(s.server_id) AS server_count,
       AVG(s.current_players)::numeric(10,2) AS avg_players
FROM gaming_technology.games g
JOIN gaming_technology.servers s ON g.game_id = s.game_id
WHERE s.region ILIKE 'eu%' AND s.status = 'online'
GROUP BY g.title
HAVING AVG(s.current_players) > 100
ORDER BY server_count DESC
LIMIT 5;

[User] How many players are there for each status in the players table?

[Assistant]
SELECT status, COUNT(*) AS player_count
FROM gaming_technology.players
GROUP BY status;

[User] Exclude any rows where status is NULL.

[Assistant]
SELECT status, COUNT(*) AS player_count
FROM gaming_technology.players
WHERE status IS NOT NULL
GROUP BY status;

[User] Also sort the result by player_count in descending order.

[Assistant]
SELECT status, COUNT(*) AS player_count
FROM gaming_technology.players
WHERE status IS NOT NULL
GROUP BY status
ORDER BY player_count DESC;

[User] Finally, only show statuses with more than 100 players.

[Assistant]
SELECT status, COUNT(*) AS player_count
FROM gaming_technology.players
WHERE status IS NOT NULL
GROUP BY status
HAVING COUNT(*) > 100
ORDER BY player_count DESC;

[User] List game titles and their developer names for games released in 2023 or later.

[Assistant] SELECT T1.title, T2.name FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id WHERE T1.release_date >= '2023-01-01';

[User] Also include the genre and order the results by release date descending.

[Assistant] SELECT T1.title, T2.name, T1.genre FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id WHERE T1.release_date >= '2023-01-01' ORDER BY T1.release_date DESC;

[User] List all in-game items that are either 'Rare' or 'Epic' rarity.

[Assistant] SELECT item_id, item_name, rarity FROM in_game_items WHERE rarity IN ('Rare', 'Epic');

[User] Include the item type and cost amount in the output.

[Assistant] SELECT item_id, item_name, rarity, item_type, cost_amount FROM in_game_items WHERE rarity IN ('Rare', 'Epic');

[User] Now, only show items where the cost amount is less than 500.

[Assistant] SELECT item_id, item_name, rarity, item_type, cost_amount FROM in_game_items WHERE rarity IN ('Rare', 'Epic') AND cost_amount < 500;

[User] Order the results by cost amount ascending.

[Assistant] SELECT item_id, item_name, rarity, item_type, cost_amount FROM in_game_items WHERE rarity IN ('Rare', 'Epic') AND cost_amount < 500 ORDER BY cost_amount ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id 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.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

[User] I need a list of all routes and the number of trips made on each route.

[Assistant]
SELECT route_id, COUNT(*) AS trip_count
FROM transportation.trips
GROUP BY route_id;

[User] Actually, show the route_number and description instead of route_id.

[Assistant]
SELECT r.route_number,
       r.description,
       COUNT(t.trip_id) AS trip_count
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
GROUP BY r.route_number, r.description;

[User] Also, only include routes with more than 20 trips and sort by trip_count descending.

[Assistant]
SELECT r.route_number,
       r.description,
       COUNT(t.trip_id) AS trip_count
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
GROUP BY r.route_number, r.description
HAVING COUNT(t.trip_id) > 20
ORDER BY trip_count DESC;

[User] Finally, display the average passenger count per trip for each of these routes.

[Assistant]
SELECT r.route_number,
       r.description,
       COUNT(t.trip_id) AS trip_count,
       AVG(t.passenger_count) AS avg_passengers
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
GROUP BY r.route_number, r.description
HAVING COUNT(t.trip_id) > 20
ORDER BY trip_count DESC;

[User] Provide a list of all drivers and for each, show their driver_id, full name, the total number of completed trips they've driven, and the sum of all fares from bookings on those completed trips. Include drivers even if they have no completed trips. Order by total_fares descending.

[Assistant]
SELECT d.driver_id,
       d.first_name || ' ' || d.last_name AS full_name,
       COUNT(t.trip_id) FILTER (WHERE t.status = 'Completed') AS completed_trips,
       COALESCE(SUM(b.fare) FILTER (WHERE t.status = 'Completed'), 0) AS total_fares
FROM transportation.drivers d
LEFT JOIN transportation.trips t ON d.driver_id = t.driver_id
LEFT JOIN transportation.bookings b ON t.trip_id = b.trip_id
GROUP BY d.driver_id, d.first_name, d.last_name
ORDER BY total_fares DESC;

[User] Show me the top 3 vehicles with the highest average passenger count on completed trips, and include each vehicle's license plate, make, and the average passenger count.

[Assistant]
SELECT v.vehicle_id,
       v.license_plate,
       v.make,
       AVG(t.passenger_count) AS avg_passengers
FROM transportation.vehicles v
JOIN transportation.trips t
  ON v.vehicle_id = t.vehicle_id
WHERE t.status = 'Completed'
GROUP BY v.vehicle_id, v.license_plate, v.make
ORDER BY avg_passengers DESC
LIMIT 3;

[User] For each route, show the route_number, origin and destination location names with their cities, and the average departure delay (in minutes) for trips where actual_departure was later than scheduled_departure.

[Assistant]
SELECT r.route_number,
       lo.name       AS origin_name,
       lo.city       AS origin_city,
       ld.name       AS destination_name,
       ld.city       AS destination_city,
       AVG(EXTRACT(EPOCH FROM (t.actual_departure - t.scheduled_departure)) / 60) AS avg_delay_minutes
FROM transportation.routes r
JOIN transportation.trips t
  ON r.route_id = t.route_id
JOIN transportation.locations lo
  ON r.origin_location_id = lo.location_id
JOIN transportation.locations ld
  ON r.destination_location_id = ld.location_id
WHERE t.actual_departure > t.scheduled_departure
GROUP BY r.route_number, origin_name, origin_city, destination_name, destination_city;

[User] Show the top 10 most expensive fuel log entries including fuel_log_id, vehicle make and model, location name and city, and total_cost.

[Assistant]
SELECT f.fuel_log_id,
       v.make,
       v.model,
       loc.name AS location_name,
       loc.city,
       f.total_cost
FROM transportation.fuel_logs f
JOIN transportation.vehicles v ON f.vehicle_id = v.vehicle_id
JOIN transportation.locations loc ON f.location_id = loc.location_id
ORDER BY f.total_cost DESC
LIMIT 10;

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )

[User] Which customers have made more than three premium payments in 2024? Show the customer_id and the number of payments.

[Assistant] SELECT customer_id, COUNT(*) AS payment_count FROM insurance.premium_payments WHERE payment_date >= '2024-01-01' AND payment_date < '2025-01-01' GROUP BY customer_id HAVING COUNT(*) > 3;

[User] Include only those payments where the status is 'completed'.

[Assistant] SELECT customer_id, COUNT(*) AS payment_count FROM insurance.premium_payments WHERE payment_date >= '2024-01-01' AND payment_date < '2025-01-01' AND status = 'completed' GROUP BY customer_id HAVING COUNT(*) > 3;

[User] List all premium payments with a due date in March 2024.

[Assistant] SELECT * FROM insurance.premium_payments WHERE due_date >= '2024-03-01' AND due_date <= '2024-03-31';

[User] Show me the total paid amount and the number of premium payments per customer for policies that have at least one payment over $5000.

[Assistant] SELECT customer_id, SUM(amount_paid) AS total_paid, COUNT(*) AS payment_count FROM insurance.premium_payments WHERE policy_id IN (SELECT policy_id FROM insurance.premium_payments WHERE amount_paid > 5000) GROUP BY customer_id;

[User] Can you also include the earliest payment date for each customer in the result?

[Assistant] SELECT customer_id, SUM(amount_paid) AS total_paid, COUNT(*) AS payment_count, MIN(payment_date) AS earliest_payment_date FROM insurance.premium_payments WHERE policy_id IN (SELECT policy_id FROM insurance.premium_payments WHERE amount_paid > 5000) GROUP BY customer_id;

[User] Now restrict this to only show customers who have made payments using the 'bank transfer' method.

[Assistant] SELECT customer_id, SUM(amount_paid) AS total_paid, COUNT(*) AS payment_count, MIN(payment_date) AS earliest_payment_date FROM insurance.premium_payments WHERE policy_id IN (SELECT policy_id FROM insurance.premium_payments WHERE amount_paid > 5000) AND payment_method = 'bank transfer' GROUP BY customer_id;

[User] For each policy, find the latest payment date. Show the policy_id and the maximum payment_date.

[Assistant] SELECT policy_id, MAX(payment_date) AS latest_payment_date FROM insurance.premium_payments GROUP BY policy_id;

[User] Restrict the results to only show policies where the latest payment date was before '2024-01-01'.

[Assistant] SELECT policy_id, MAX(payment_date) AS latest_payment_date FROM insurance.premium_payments GROUP BY policy_id HAVING MAX(payment_date) < '2024-01-01';

[User] List all premium payments that have a status of 'pending'. Show the payment_id, policy_id, customer_id, and amount_paid.

[Assistant] SELECT payment_id, policy_id, customer_id, amount_paid FROM insurance.premium_payments WHERE status = 'pending';

[User] Count the number of completed premium payments grouped by payment_method.

[Assistant]
SELECT payment_method,
       COUNT(*) AS payment_count
FROM insurance.premium_payments
WHERE status = 'Completed'
GROUP BY payment_method;


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

[User] Provide the count of applications grouped by their status.

[Assistant]
SELECT status, COUNT(*) AS application_count
FROM government_services.applications
GROUP BY status;

[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] Which employees have verified more than 5 documents in the last 30 days? Return the employee's full name, department, and the number of verifications.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS full_name, e.department, COUNT(d.document_id) AS verification_count
FROM government_services.documents d
JOIN government_services.employees e ON d.verified_by_employee_id = e.employee_id
WHERE d.verification_status = 'Verified'
  AND d.verification_timestamp >= now() - interval '30 days'
GROUP BY e.first_name, e.last_name, e.department
HAVING COUNT(d.document_id) > 5;

[User] Provide a count of documents grouped by their current verification status.

[Assistant] SELECT verification_status, COUNT(*) FROM government_services.documents GROUP BY verification_status

[User] Find the full names of employees who have verified documents that have an expiry date in the past and are marked as 'Verified'.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name FROM government_services.employees AS T1 JOIN government_services.documents AS T2 ON T1.employee_id = T2.verified_by_employee_id WHERE T2.expiry_date < CURRENT_DATE AND T2.verification_status = 'Verified'

[User] List the application IDs and their submitted dates for applications that have been assigned to an employee in the 'Housing' department.

[Assistant] SELECT T1.application_id, T1.submitted_at FROM government_services.applications AS T1 JOIN government_services.employees AS T2 ON T1.assigned_employee_id = T2.employee_id WHERE T2.department = 'Housing'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[User] Add the last_trade_time to your output.

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

[User] Calculate the average realized_ratio across all addresses.

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
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 )

[User] List all premium payments along with the customer's first and last name for payments made after July 1, 2023.

[Assistant]
SELECT pp.payment_id, pp.payment_date, pp.amount_paid, cu.first_name, cu.last_name
FROM insurance.premium_payments pp
JOIN insurance.customers cu ON pp.customer_id = cu.customer_id
WHERE pp.payment_date > '2023-07-01';

[User] Add the payment_method and payment_period_start and payment_period_end columns to the output.

[Assistant]
SELECT pp.payment_id, pp.payment_date, pp.amount_paid, cu.first_name, cu.last_name, pp.payment_method, pp.payment_period_start, pp.payment_period_end
FROM insurance.premium_payments pp
JOIN insurance.customers cu ON pp.customer_id = cu.customer_id
WHERE pp.payment_date > '2023-07-01';

[User] Show me all claims along with the related customer's full name and the policy number for incidents that occurred in 2024.

[Assistant]
SELECT c.claim_id, c.incident_date, c.description, cu.first_name || ' ' || cu.last_name AS customer_full_name, p.policy_number
FROM insurance.claims c
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
JOIN insurance.policies p ON c.policy_id = p.policy_id
WHERE EXTRACT(YEAR FROM c.incident_date) = 2024;

[User] Include the settlement amount and status of each claim in the results.

[Assistant]
SELECT c.claim_id, c.incident_date, c.description, cu.first_name || ' ' || cu.last_name AS customer_full_name, p.policy_number, c.settlement_amount, c.status
FROM insurance.claims c
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
JOIN insurance.policies p ON c.policy_id = p.policy_id
WHERE EXTRACT(YEAR FROM c.incident_date) = 2024;

[User] Actually, please filter only those claims with a settlement_amount that is not null.

[Assistant]
SELECT c.claim_id, c.incident_date, c.description, cu.first_name || ' ' || cu.last_name AS customer_full_name, p.policy_number, c.settlement_amount, c.status
FROM insurance.claims c
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
JOIN insurance.policies p ON c.policy_id = p.policy_id
WHERE EXTRACT(YEAR FROM c.incident_date) = 2024
  AND c.settlement_amount IS NOT NULL;

[User] Give a list of all policies where the deductible is less than 1000. Show policy_id, policy_number, start_date, and deductible.

[Assistant]
SELECT policy_id, policy_number, start_date, deductible
FROM insurance.policies
WHERE deductible < 1000;

[User] List all agents who have a commission rate above 0.1, showing their full names and agency names.

[Assistant] SELECT agent_id, first_name || ' ' || last_name AS full_name, agency_name, commission_rate FROM insurance.agents WHERE commission_rate > 0.1 AND status = 'Active';

[User] Now include only agents who were hired in the last 5 years and sort them by hire date in descending order.

[Assistant] SELECT agent_id, first_name || ' ' || last_name AS full_name, agency_name, commission_rate, hire_date FROM insurance.agents WHERE commission_rate > 0.1 AND status = 'Active' AND hire_date >= CURRENT_DATE - INTERVAL '5 years' ORDER BY hire_date DESC;

[User] Show me all claims with police reports that were filed in the last 3 months, along with their policy details and estimated loss amounts.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.incident_date, cl.reported_date, cl.estimated_loss, cl.police_report_number, p.policy_number, p.start_date, p.end_date, p.coverage_limit FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Now include the customer's full name and the product type for these policies.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.incident_date, cl.reported_date, cl.estimated_loss, cl.police_report_number, p.policy_number, p.start_date, p.end_date, p.coverage_limit, c.first_name || ' ' || c.last_name AS customer_name, ip.product_type FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.insurance_products ip ON p.product_id = ip.product_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Filter these results to only show claims where the estimated loss is above $10,000 and include the agent who handled the claim.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.incident_date, cl.reported_date, cl.estimated_loss, cl.police_report_number, p.policy_number, p.start_date, p.end_date, p.coverage_limit, c.first_name || ' ' || c.last_name AS customer_name, ip.product_type, a.first_name || ' ' || a.last_name AS agent_name FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.insurance_products ip ON p.product_id = ip.product_id LEFT JOIN insurance.agents a ON cl.claim_handler_id = a.agent_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND cl.estimated_loss > 10000;

[User] Finally, order the results by the highest estimated loss first and include only claims that have been settled.

[Assistant] SELECT cl.claim_id, cl.policy_id, cl.incident_date, cl.reported_date, cl.estimated_loss, cl.police_report_number, p.policy_number, p.start_date, p.end_date, p.coverage_limit, c.first_name || ' ' || c.last_name AS customer_name, ip.product_type, a.first_name || ' ' || a.last_name AS agent_name FROM insurance.claims cl JOIN insurance.policies p ON cl.policy_id = p.policy_id JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.insurance_products ip ON p.product_id = ip.product_id LEFT JOIN insurance.agents a ON cl.claim_handler_id = a.agent_id WHERE cl.police_report_number IS NOT NULL AND cl.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND cl.estimated_loss > 10000 AND cl.status = 'Settled' ORDER BY cl.estimated_loss DESC;

[User] List all agents who have sold policies with a coverage limit above 500000. Show agent_id, first_name, last_name, and the count of such policies as policy_count.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, COUNT(p.policy_id) AS policy_count
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE p.coverage_limit > 500000
GROUP BY a.agent_id, a.first_name, a.last_name;

[User] Actually, include the sum of premium_amount for each of those agents as total_premium as well.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, COUNT(p.policy_id) AS policy_count, SUM(p.premium_amount) AS total_premium
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE p.coverage_limit > 500000
GROUP BY a.agent_id, a.first_name, a.last_name;

[User] And restrict to agents whose commission_rate is greater than 0.06.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, COUNT(p.policy_id) AS policy_count, SUM(p.premium_amount) AS total_premium
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE p.coverage_limit > 500000
  AND a.commission_rate > 0.06
GROUP BY a.agent_id, a.first_name, a.last_name;


[User] List all trips that are currently 'Scheduled'.

[Assistant] SELECT * FROM transportation.trips WHERE status = 'Scheduled'

[User] For these scheduled trips, can you also include the route number and estimated duration?

[Assistant] SELECT T1.trip_id, T2.route_number, T2.estimated_duration_minutes FROM transportation.trips AS T1 JOIN transportation.routes AS T2 ON T1.route_id = T2.route_id WHERE T1.status = 'Scheduled'

[User] Only show trips scheduled to depart after '2023-10-01'.

[Assistant] SELECT T1.trip_id, T2.route_number, T2.estimated_duration_minutes FROM transportation.trips AS T1 JOIN transportation.routes AS T2 ON T1.route_id = T2.route_id WHERE T1.status = 'Scheduled' AND T1.scheduled_departure > '2023-10-01'

[User] Order the results by scheduled departure time.

[Assistant] SELECT T1.trip_id, T2.route_number, T2.estimated_duration_minutes FROM transportation.trips AS T1 JOIN transportation.routes AS T2 ON T1.route_id = T2.route_id WHERE T1.status = 'Scheduled' AND T1.scheduled_departure > '2023-10-01' ORDER BY T1.scheduled_departure

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 )


[User] List the username and email of users who have disabled push notifications.

[Assistant]
SELECT u.username, u.email
FROM social_media.users u
JOIN social_media.user_settings s ON u.user_id = s.user_id
WHERE s.push_notifications_enabled = false;

[User] Also include only those whose profile is private.

[Assistant]
SELECT u.username, u.email
FROM social_media.users u
JOIN social_media.user_settings s ON u.user_id = s.user_id
WHERE s.push_notifications_enabled = false
  AND s.private_profile = true;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)


[User] List all prescriptions where the dosage text contains the word 'unit'. Show the prescription ID, medication ID, and dosage.

[Assistant] SELECT prescription_id, medication_id, dosage FROM healthcare.prescriptions WHERE dosage LIKE '%unit%';

[User] From that list, also filter to only show prescriptions where the number of refills allowed is greater than 0.

[Assistant] SELECT prescription_id, medication_id, dosage FROM healthcare.prescriptions WHERE dosage LIKE '%unit%' AND refills_allowed > 0;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, 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.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )


[User] I want to retrieve a list of all doctors along with every insurance plan name, showing doctor ID, first and last names, and insurance plan name.

[Assistant]
SELECT d.doctor_id, d.first_name, d.last_name, p.plan_name
FROM healthcare.doctors d
CROSS JOIN healthcare.insurance_plans p;

[User] Actually, limit this to only those combinations where the plan type is 'HMO'.

[Assistant]
SELECT d.doctor_id, d.first_name, d.last_name, p.plan_name
FROM healthcare.doctors d
CROSS JOIN healthcare.insurance_plans p
WHERE p.plan_type = 'HMO';

[User] Also, sort the results by the doctor's last name in descending order.

[Assistant]
SELECT d.doctor_id, d.first_name, d.last_name, p.plan_name
FROM healthcare.doctors d
CROSS JOIN healthcare.insurance_plans p
WHERE p.plan_type = 'HMO'
ORDER BY d.last_name DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)


[User] I need a list of active drivers with their names and contact details.

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

[User] Actually, include their hire_date and filter to drivers hired before '2022-01-01'.

[Assistant] SELECT driver_id, first_name, last_name, contact_number, email, hire_date FROM transportation.drivers WHERE status = 'Active' AND hire_date < '2022-01-01';

[User] Now sort by hire_date descending and limit to the first 10 records.

[Assistant] SELECT driver_id, first_name, last_name, contact_number, email, hire_date FROM transportation.drivers WHERE status = 'Active' AND hire_date < '2022-01-01' ORDER BY hire_date DESC LIMIT 10;

[User] Also add the license_expiry_date to each record.

[Assistant] SELECT driver_id, first_name, last_name, contact_number, email, hire_date, license_expiry_date FROM transportation.drivers WHERE status = 'Active' AND hire_date < '2022-01-01' ORDER BY hire_date DESC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 )