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.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.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )

[User] Find all document types uploaded by citizens whose documents have an expiry date in 2024 and were uploaded at locations located in the state of 'Nevada'. List the document_id, document_type, and location_name.

[Assistant]
SELECT d.document_id, d.document_type, sl.location_name
FROM government_services.documents d
JOIN government_services.service_locations sl
  ON d.application_id = sl.location_id
WHERE d.expiry_date BETWEEN '2024-01-01' AND '2024-12-31'
  AND sl.state = 'Nevada';


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.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    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, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)

[User] List the first name, last name, and job title of each employee, along with the job title of their manager.

[Assistant] SELECT e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.job_title AS employee_job_title, m.job_title AS manager_job_title FROM government_services.employees AS e LEFT JOIN government_services.employees AS m ON e.manager_employee_id = m.employee_id;


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

[User] Find pairs of active services within the same category provided by the same agency, where one service has an average processing time more than double the other's. Display the agency ID, category, the first service name and its processing time, and the second service name and its processing time.

[Assistant] SELECT s1.agency_id, s1.category, s1.service_name AS service1_name, s1.average_processing_time_days AS service1_processing_time_days, s2.service_name AS service2_name, s2.average_processing_time_days AS service2_processing_time_days FROM government_services.services AS s1 JOIN government_services.services AS s2 ON s1.agency_id = s2.agency_id AND s1.category = s2.category AND s1.service_id < s2.service_id WHERE s1.is_active = TRUE AND s2.is_active = TRUE AND s1.average_processing_time_days IS NOT NULL AND s2.average_processing_time_days IS NOT NULL AND (s1.average_processing_time_days > 2 * s2.average_processing_time_days OR s2.average_processing_time_days > 2 * s1.average_processing_time_days);


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, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)

[User] List the service name, category, and standard fee for all services offered by agencies that have at least one accessible service location in the state of 'California'.

[Assistant] SELECT DISTINCT T1.service_name, T1.category, T1.standard_fee FROM government_services.services AS T1 JOIN government_services.service_locations AS T2 ON T1.agency_id = T2.agency_id WHERE T2.is_accessible = TRUE AND T2.state = 'California';


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.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    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, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    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] Show me all upcoming appointments in July 2024, the citizen's full name, the name of the service, and the agency responsible for the service.

[Assistant]
SELECT a.appointment_id, a.scheduled_start_time, c.first_name || ' ' || c.last_name AS citizen_full_name, s.service_name, ag.agency_name
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.services s ON a.service_id = s.service_id
JOIN government_services.agencies ag ON s.agency_id = ag.agency_id
WHERE a.scheduled_start_time >= '2024-07-01' AND a.scheduled_start_time < '2024-08-01'
ORDER BY a.scheduled_start_time ASC;

[User] Could you also include the status of each appointment and only show those which are still 'Scheduled'?

[Assistant]
SELECT a.appointment_id, a.scheduled_start_time, c.first_name || ' ' || c.last_name AS citizen_full_name, s.service_name, ag.agency_name, a.status
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.services s ON a.service_id = s.service_id
JOIN government_services.agencies ag ON s.agency_id = ag.agency_id
WHERE a.scheduled_start_time >= '2024-07-01' AND a.scheduled_start_time < '2024-08-01'
  AND a.status = 'Scheduled'
ORDER BY a.scheduled_start_time ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )

[User] List agency_id, agency_name, and main_phone_number for agencies that do not have a main phone number specified.

[Assistant]
SELECT agency_id, agency_name, main_phone_number
FROM government_services.agencies
WHERE main_phone_number IS NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.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.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )

[User] Give me a list of all passengers with an email address on file, showing their first name, last name, and the date their record was created.

[Assistant]
SELECT first_name, last_name, created_at
FROM transportation.passengers
WHERE email IS NOT NULL;

[User] Narrow the results to only include passengers who joined in 2022.

[Assistant]
SELECT first_name, last_name, created_at
FROM transportation.passengers
WHERE email IS NOT NULL AND EXTRACT(YEAR FROM created_at) = 2022;


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.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] What are the average and maximum fare amounts for each booking status?

[Assistant]
SELECT status, AVG(fare) AS avg_fare, MAX(fare) AS max_fare
FROM transportation.bookings
GROUP BY status;

[User] Only include statuses where the average fare is greater than 50.

[Assistant]
SELECT status, AVG(fare) AS avg_fare, MAX(fare) AS max_fare
FROM transportation.bookings
GROUP BY status
HAVING AVG(fare) > 50;


[User] Can you show the fuel_log_id, vehicle make, and quantity for all fuel logs where the quantity is greater than 100?

[Assistant]
SELECT f.fuel_log_id, v.make, f.quantity
FROM transportation.fuel_logs f
JOIN transportation.vehicles v ON f.vehicle_id = v.vehicle_id
WHERE f.quantity > 100;

[User] Also display the fuel type and order the results by quantity in descending order.

[Assistant]
SELECT f.fuel_log_id, v.make, f.quantity, f.fuel_type
FROM transportation.fuel_logs f
JOIN transportation.vehicles v ON f.vehicle_id = v.vehicle_id
WHERE f.quantity > 100
ORDER BY f.quantity DESC;

[User] Only include records from fuel logs that happened in 2023.

[Assistant]
SELECT f.fuel_log_id, v.make, f.quantity, f.fuel_type
FROM transportation.fuel_logs f
JOIN transportation.vehicles v ON f.vehicle_id = v.vehicle_id
WHERE f.quantity > 100
  AND EXTRACT(YEAR FROM f.log_timestamp) = 2023
ORDER BY f.quantity 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 transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] Show me the log timestamp, fuel type, quantity, and the name of the location for all fuel logs recorded at locations with type 'Warehouse'.

[Assistant] SELECT f.log_timestamp, f.fuel_type, f.quantity, l.name FROM transportation.fuel_logs f JOIN transportation.locations l ON f.location_id = l.location_id WHERE l.type = 'Warehouse';

[User] Filter these fuel logs to only include entries from the year 2024 and also include the total cost for each entry.

[Assistant] SELECT f.log_timestamp, f.fuel_type, f.quantity, f.total_cost, l.name FROM transportation.fuel_logs f JOIN transportation.locations l ON f.location_id = l.location_id WHERE l.type = 'Warehouse' AND EXTRACT(YEAR FROM f.log_timestamp) = 2024;

[User] For these 'Warehouse' fuel logs from 2024, calculate the average quantity and average cost_per_unit for each fuel type.

[Assistant] SELECT f.fuel_type, AVG(f.quantity) AS average_quantity, AVG(f.cost_per_unit) AS average_cost_per_unit FROM transportation.fuel_logs f JOIN transportation.locations l ON f.location_id = l.location_id WHERE l.type = 'Warehouse' AND EXTRACT(YEAR FROM f.log_timestamp) = 2024 GROUP BY f.fuel_type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )

[User] For each vehicle, find the vehicle acquired immediately before it in the same depot. Show current vehicle_id, acquisition_date, previous_vehicle_id, and previous_acquisition_date.

[Assistant]
SELECT v.vehicle_id,
       v.acquisition_date,
       prev.vehicle_id AS previous_vehicle_id,
       prev.acquisition_date AS previous_acquisition_date
FROM transportation.vehicles v
LEFT JOIN transportation.vehicles prev
  ON v.depot_id = prev.depot_id
  AND prev.acquisition_date = (
    SELECT MAX(acquisition_date)
    FROM transportation.vehicles
    WHERE depot_id = v.depot_id
      AND acquisition_date < v.acquisition_date
  );


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.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] Show the booking ID and seat number for all bookings that have a fare equal to 50.

[Assistant]
SELECT booking_id, seat_number
FROM transportation.bookings
WHERE fare = 50;

[User] Also include the booking status and order the results by booking time ascending.

[Assistant]
SELECT booking_id, seat_number, status
FROM transportation.bookings
WHERE fare = 50
ORDER BY booking_time 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 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.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] Retrieve the daily total fare collected for bookings with status 'Completed' in March 2024. Display the booking_date and total_fare.

[Assistant]
SELECT
  DATE(booking_time) AS booking_date,
  SUM(fare) AS total_fare
FROM transportation.bookings
WHERE status = 'Completed'
  AND booking_time >= '2024-03-01'
  AND booking_time <  '2024-04-01'
GROUP BY DATE(booking_time);

[User] Now include only days where the total_fare exceeds 1000.

[Assistant]
SELECT
  DATE(booking_time) AS booking_date,
  SUM(fare) AS total_fare
FROM transportation.bookings
WHERE status = 'Completed'
  AND booking_time >= '2024-03-01'
  AND booking_time <  '2024-04-01'
GROUP BY DATE(booking_time)
HAVING SUM(fare) > 1000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers (
    driver_id character varying(64) NOT NULL,  -- unique identifier for the driver
    employee_id character varying(64) NOT NULL UNIQUE, -- employee reference number
    first_name character varying(128) NOT NULL, -- driver's first name
    last_name character varying(128) NOT NULL, -- driver's last name
    license_number character varying(64) NOT NULL UNIQUE, -- driving license number
    license_expiry_date date NOT NULL, -- expiry date of the license
    contact_number character varying(32), -- phone number
    email character varying(128) UNIQUE, -- email address
    hire_date date NOT NULL, -- date the driver was hired
    status character varying(32) NOT NULL, -- e.g., Active, On Leave, Terminated
    PRIMARY KEY (driver_id)
)
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.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )

[User] Show me all maintenance logs for vehicles of make 'Toyota' performed after January 1, 2024. Include the log ID, vehicle ID, service date, and service type.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE v.make = 'Toyota' AND ml.service_date > '2024-01-01';

[User] Can you add the maintenance cost and mechanic name to each entry and sort the results by service date descending?

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, ml.cost, ml.mechanic_name
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE v.make = 'Toyota' AND ml.service_date > '2024-01-01'
ORDER BY ml.service_date DESC;

[User] Actually, only show logs where the maintenance cost is greater than 1000.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, ml.cost, ml.mechanic_name
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE v.make = 'Toyota' AND ml.service_date > '2024-01-01' AND ml.cost > 1000
ORDER BY ml.service_date DESC;


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

[User] Could you provide the number of vehicles for each fuel_type?

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

[User] Filter out fuel types having fewer than 10 vehicles.

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

[User] Now order the result by vehicle_count descending and limit to the top 5 entries.

[Assistant]
SELECT fuel_type, COUNT(*) AS vehicle_count
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 10
ORDER BY vehicle_count DESC
LIMIT 5;

[User] Also add the average capacity for each fuel_type.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

[User] List the number of bookings made by each passenger, including passenger_id, first_name, last_name, and booking_count.

[Assistant]
SELECT p.passenger_id,
       p.first_name,
       p.last_name,
       COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id,
         p.first_name,
         p.last_name;

[User] Actually, only include passengers who have made at least 2 bookings.

[Assistant]
SELECT p.passenger_id,
       p.first_name,
       p.last_name,
       COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id,
         p.first_name,
         p.last_name
HAVING COUNT(b.booking_id) >= 2;

[User] Also include the average fare per passenger.

[Assistant]
SELECT p.passenger_id,
       p.first_name,
       p.last_name,
       COUNT(b.booking_id)     AS booking_count,
       AVG(b.fare)             AS average_fare
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id,
         p.first_name,
         p.last_name
HAVING COUNT(b.booking_id) >= 2;

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

[Assistant]
SELECT p.passenger_id,
       p.first_name,
       p.last_name,
       COUNT(b.booking_id)     AS booking_count,
       AVG(b.fare)             AS average_fare
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id,
         p.first_name,
         p.last_name
HAVING COUNT(b.booking_id) >= 2
ORDER BY average_fare 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.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 )

[User] Find pairs of distinct routes that share the same destination location but start from different origins. Include the route ID and route number for both routes and the shared destination location ID.

[Assistant]
SELECT
  r1.route_id AS route1_id,
  r1.route_number AS route1_number,
  r2.route_id AS route2_id,
  r2.route_number AS route2_number,
  r1.destination_location_id AS shared_destination_location_id
FROM transportation.routes AS r1
JOIN transportation.routes AS r2
  ON r1.destination_location_id = r2.destination_location_id
  AND r1.route_id < r2.route_id
WHERE
  r1.origin_location_id != r2.origin_location_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )

[User] List each booking with its previous booking time for the same passenger.

[Assistant]
SELECT b.booking_id,
       b.passenger_id,
       b.booking_time,
       LAG(b.booking_time) OVER (PARTITION BY b.passenger_id ORDER BY b.booking_time) AS previous_booking_time
FROM transportation.bookings b;

[User] I only want records where the gap between bookings is more than 7 days.

[Assistant]
SELECT booking_id,
       passenger_id,
       booking_time,
       previous_booking_time
FROM (
  SELECT booking_id,
         passenger_id,
         booking_time,
         LAG(booking_time) OVER (PARTITION BY passenger_id ORDER BY booking_time) AS previous_booking_time
  FROM transportation.bookings
) t
WHERE previous_booking_time IS NOT NULL
  AND booking_time - previous_booking_time > INTERVAL '7 days';

[User] Also include the total number of bookings for each passenger.

[Assistant]
SELECT booking_id,
       passenger_id,
       booking_time,
       previous_booking_time,
       COUNT(*) OVER (PARTITION BY passenger_id) AS total_bookings
FROM (
  SELECT booking_id,
         passenger_id,
         booking_time,
         LAG(booking_time) OVER (PARTITION BY passenger_id ORDER BY booking_time) AS previous_booking_time
  FROM transportation.bookings
) t
WHERE previous_booking_time IS NOT NULL
  AND booking_time - previous_booking_time > INTERVAL '7 days';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )

[User] For each user, what is the average time difference in days between their wallet creations? Return user_id and avg_diff_days.

[Assistant]
WITH diffs AS (
  SELECT
    user_id,
    EXTRACT(EPOCH FROM (created_at - LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at))) / 86400 AS diff_days
  FROM web3.wallets
)
SELECT
  user_id,
  AVG(diff_days) AS avg_diff_days
FROM diffs
WHERE diff_days IS NOT NULL
GROUP BY user_id;

[User] Actually, only include users who have created more than 2 wallets.

[Assistant]
WITH diffs AS (
  SELECT
    user_id,
    EXTRACT(EPOCH FROM (created_at - LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at))) / 86400 AS diff_days
  FROM web3.wallets
)
SELECT
  user_id,
  AVG(diff_days) AS avg_diff_days
FROM diffs
WHERE diff_days IS NOT NULL
GROUP BY user_id
HAVING COUNT(diff_days) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id text PRIMARY KEY, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )

[User] List all failed transactions along with the from and to addresses, and the gas used.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used FROM web3.transactions WHERE status = 'failed';

[User] Actually, I also need to see the block number and timestamp for these failed transactions.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used, block_number, timestamp FROM web3.transactions WHERE status = 'failed';

[User] There's a typo in your SQL, it should be 'timestamp' not 'timestamp'. Also, sort the results by block number in descending order.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used, block_number, timestamp FROM web3.transactions WHERE status = 'failed' ORDER BY block_number DESC;

[User] Now filter to only show transactions with gas used greater than 100,000.

[Assistant] SELECT transaction_id, from_address, to_address, gas_used, block_number, timestamp FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000 ORDER BY block_number DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )

[User] Find pairs of wallets that were created at the exact same timestamp but are owned by different users. List the IDs of both wallets and the shared creation timestamp.

[Assistant]
SELECT
    w1.wallet_id AS wallet1_id,
    w2.wallet_id AS wallet2_id,
    w1.created_at
FROM
    web3.wallets w1
JOIN
    web3.wallets w2 ON w1.created_at = w2.created_at
WHERE
    w1.wallet_id < w2.wallet_id
    AND w1.user_id != w2.user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )

[User] Find pairs of users who registered on the same weekday but in different years. List the user ID and registration date for both users, and the weekday name.

[Assistant] SELECT u1.user_id, u1.created_at AS user1_created_at, u2.user_id, u2.created_at AS user2_created_at, TO_CHAR(u1.created_at, 'Day') AS registration_weekday FROM web3.users u1 JOIN web3.users u2 ON TO_CHAR(u1.created_at, 'Day') = TO_CHAR(u2.created_at, 'Day') AND EXTRACT(YEAR FROM u1.created_at) <> EXTRACT(YEAR FROM u2.created_at) AND u1.user_id < u2.user_id ORDER BY TO_CHAR(u1.created_at, 'D'), u1.created_at;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )

[User] For each user, find the previous user by registration time. List current user_id and username, previous user_id and username, and the time difference in minutes between their registrations.

[Assistant]
SELECT u.user_id AS current_user_id,
       u.username AS current_username,
       p.user_id AS previous_user_id,
       p.username AS previous_username,
       EXTRACT(EPOCH FROM (u.created_at - p.created_at)) / 60 AS diff_minutes
FROM web3.users u
JOIN web3.users p
  ON p.created_at = (
    SELECT MAX(created_at)
    FROM web3.users
    WHERE created_at < u.created_at
  )
ORDER BY u.created_at;


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

[User] Calculate the total transfer volume and number of transfers for each Avalanche token tick over the past 7 days.

[Assistant]
SELECT ta.tick,
       SUM(ta.amt) AS total_volume,
       COUNT(*)   AS transfer_count
FROM token_activities_avalanche ta
WHERE ta.block_timestamp >= NOW() - INTERVAL '7 days'
GROUP BY ta.tick;

[User] Now include the creator from token_info and filter to tokens with total_volume > 500.

[Assistant]
SELECT sub.tick,
       sub.total_volume,
       sub.transfer_count,
       ti.creator
FROM (
  SELECT ta.tick,
         SUM(ta.amt) AS total_volume,
         COUNT(*)   AS transfer_count
  FROM token_activities_avalanche ta
  WHERE ta.block_timestamp >= NOW() - INTERVAL '7 days'
  GROUP BY ta.tick
) sub
JOIN token_info ti ON sub.tick = ti.tick
WHERE sub.total_volume > 500;

[User] Also add the current total_supply from token_balances_avalanche for each tick.

[Assistant]
SELECT sub.tick,
       sub.total_volume,
       sub.transfer_count,
       ti.creator,
       tb.total_supply
FROM (
  SELECT ta.tick,
         SUM(ta.amt) AS total_volume,
         COUNT(*)   AS transfer_count
  FROM token_activities_avalanche ta
  WHERE ta.block_timestamp >= NOW() - INTERVAL '7 days'
  GROUP BY ta.tick
) sub
JOIN token_info ti ON sub.tick = ti.tick
JOIN token_balances_avalanche tb ON sub.tick = tb.tick
WHERE sub.total_volume > 500;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )

[User] For Avalanche tokens, show me the token `tick`, `creator`, and `max_supply` from the `token_info_avalanche` table.

[Assistant] SELECT tick, creator, max_supply FROM token_info_avalanche

[User] Now, for each of these ticks, calculate the total transfer volume (`amt`) from the `token_activities_avalanche` table over the last 30 days.

[Assistant] SELECT T1.tick, T2.creator, T2.max_supply, SUM(T1.amt) AS total_volume FROM token_activities_avalanche AS T1 JOIN token_info_avalanche AS T2 ON T1.tick = T2.tick WHERE T1.block_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30' DAY GROUP BY T1.tick, T2.creator, T2.max_supply

[User] Filter the results to only include ticks where the `total_volume` is greater than 10000.

[Assistant] SELECT T1.tick, T2.creator, T2.max_supply, SUM(T1.amt) AS total_volume FROM token_activities_avalanche AS T1 JOIN token_info_avalanche AS T2 ON T1.tick = T2.tick WHERE T1.block_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30' DAY GROUP BY T1.tick, T2.creator, T2.max_supply HAVING SUM(T1.amt) > 10000


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.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.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_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.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)

[User] List all group chats and the total count of messages sent in each one.

[Assistant] SELECT T1.group_name, count(T2.message_id) AS message_count FROM social_media.conversations AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T1.is_group_chat = TRUE GROUP BY T1.group_name;

[User] Can you refine that to only show group chats that have more than 100 messages?

[Assistant] SELECT T1.group_name, count(T2.message_id) AS message_count FROM social_media.conversations AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T1.is_group_chat = TRUE GROUP BY T1.group_name HAVING count(T2.message_id) > 100;

[User] Great, now please also include the creation time of these group chats and order the results by the message count in descending order.

[Assistant] SELECT T1.group_name, T1.created_at, count(T2.message_id) AS message_count FROM social_media.conversations AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T1.is_group_chat = TRUE GROUP BY T1.group_name, T1.created_at HAVING count(T2.message_id) > 100 ORDER BY message_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id character varying(64) NOT NULL, follower_user_id character varying(64) NOT NULL, following_user_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (follow_id), CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
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.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )

[User] For each user, show their username and how many unique conversations they have sent at least one message in where the conversation is a group chat.

[Assistant]
SELECT u.username, COUNT(DISTINCT m.conversation_id) AS group_chats_messaged_in
FROM social_media.users u
JOIN social_media.messages m ON u.user_id = m.sender_user_id
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY u.username;

[User] Instead, show only users who have sent messages in more than one group chat, and include their email addresses.

[Assistant]
SELECT u.username, u.email, COUNT(DISTINCT m.conversation_id) AS group_chats_messaged_in
FROM social_media.users u
JOIN social_media.messages m ON u.user_id = m.sender_user_id
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY u.username, u.email
HAVING COUNT(DISTINCT m.conversation_id) > 1;

[User] Also add the most recent message time sent by each user in these group chats.

[Assistant]
SELECT u.username, u.email, COUNT(DISTINCT m.conversation_id) AS group_chats_messaged_in, MAX(m.sent_at) AS last_message_time
FROM social_media.users u
JOIN social_media.messages m ON u.user_id = m.sender_user_id
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY u.username, u.email
HAVING COUNT(DISTINCT m.conversation_id) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )

[User] How many notifications have been sent by each sender? Show sender_user_id and notification count.

[Assistant]
SELECT sender_user_id, COUNT(*) AS notification_count
FROM social_media.notifications
WHERE sender_user_id IS NOT NULL
GROUP BY sender_user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.comments ( comment_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, parent_comment_id character varying(64), content text NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (comment_id) )
CREATE TABLE social_media.follows ( follow_id character varying(64) NOT NULL, follower_user_id character varying(64) NOT NULL, following_user_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (follow_id), CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )

[User] I need the count of messages each user has sent per conversation, along with the conversation's group_name when it's a group chat.

[Assistant]
SELECT m.sender_user_id,
       u.username,
       m.conversation_id,
       CASE WHEN c.is_group_chat THEN c.group_name ELSE 'Direct Chat' END AS chat_name,
       COUNT(*) AS total_messages
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
GROUP BY m.sender_user_id, u.username, m.conversation_id, c.is_group_chat, c.group_name;

[User] Only include conversations where the total messages exceed 5, and alias the count as message_count.

[Assistant]
SELECT m.sender_user_id,
       u.username,
       m.conversation_id,
       CASE WHEN c.is_group_chat THEN c.group_name ELSE 'Direct Chat' END AS chat_name,
       COUNT(*) AS message_count
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
GROUP BY m.sender_user_id, u.username, m.conversation_id, c.is_group_chat, c.group_name
HAVING COUNT(*) > 5;

[User] Exclude messages that have neither content nor media_url.

[Assistant]
SELECT m.sender_user_id,
       u.username,
       m.conversation_id,
       CASE WHEN c.is_group_chat THEN c.group_name ELSE 'Direct Chat' END AS chat_name,
       COUNT(*) AS message_count
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
WHERE NOT ((m.content IS NULL OR m.content = '') AND m.media_url IS NULL)
GROUP BY m.sender_user_id, u.username, m.conversation_id, c.is_group_chat, c.group_name
HAVING COUNT(*) > 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
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.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
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, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )

[User] Show me all conversations that have more than 10 messages, along with the group name and the usernames of their participants.

[Assistant]
SELECT c.conversation_id, c.group_name, u.username
FROM social_media.conversations c
JOIN social_media.messages m ON c.conversation_id = m.conversation_id
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
JOIN social_media.users u ON cp.user_id = u.user_id
GROUP BY c.conversation_id, c.group_name, u.username
HAVING COUNT(m.message_id) > 10;

[User] Instead, can you only show group chats where the group name contains 'Study' and list the time each participant joined?

[Assistant]
SELECT c.conversation_id, c.group_name, u.username, cp.joined_at
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
JOIN social_media.users u ON cp.user_id = u.user_id
WHERE c.is_group_chat = true AND c.group_name ILIKE '%Study%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id 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 text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] Show me the usernames and the group names for each user who has sent at least one message in a group chat.

[Assistant]
SELECT DISTINCT u.username, c.group_name
FROM social_media.users u
JOIN social_media.conversation_participants cp ON u.user_id = cp.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
JOIN social_media.messages m ON c.conversation_id = m.conversation_id AND u.user_id = m.sender_user_id
WHERE c.is_group_chat = true;

[User] Can you include the total number of messages each user has sent in each group chat as well?

[Assistant]
SELECT u.username, c.group_name, COUNT(m.message_id) AS message_count
FROM social_media.users u
JOIN social_media.conversation_participants cp ON u.user_id = cp.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
JOIN social_media.messages m ON c.conversation_id = m.conversation_id AND u.user_id = m.sender_user_id
WHERE c.is_group_chat = true
GROUP BY u.username, c.group_name;


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.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )

[User] What is the count of appointments for each lawyer? Display the lawyer ID and the total count.

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

[User] Only show lawyers who have more than 5 appointments.

[Assistant] SELECT lawyer_id, COUNT(*) AS appointment_count FROM legal_services.appointments GROUP BY lawyer_id HAVING COUNT(*) > 5;

[User] Consider only appointments that were created in the year 2023.

[Assistant] SELECT lawyer_id, COUNT(*) AS appointment_count FROM legal_services.appointments WHERE created_at BETWEEN '2023-01-01 00:00:00' AND '2023-12-31 23:59:59' GROUP BY lawyer_id HAVING COUNT(*) > 5;

[User] Order the results by the appointment count in descending order.

[Assistant] SELECT lawyer_id, COUNT(*) AS appointment_count FROM legal_services.appointments WHERE created_at BETWEEN '2023-01-01 00:00:00' AND '2023-12-31 23:59:59' GROUP BY lawyer_id HAVING COUNT(*) > 5 ORDER BY appointment_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.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )

[User] What is the total sum of amounts paid for all invoices?

[Assistant] SELECT SUM(amount_paid) FROM invoices;

[User] Group this total by the status of the invoice.

[Assistant] SELECT status, SUM(amount_paid) FROM invoices GROUP BY status;

[User] Only show statuses where the total amount paid is greater than 50000.

[Assistant] SELECT status, SUM(amount_paid) FROM invoices GROUP BY status HAVING SUM(amount_paid) > 50000;

[User] Order the results by the total paid amount in descending order.

[Assistant] SELECT status, SUM(amount_paid) FROM invoices GROUP BY status HAVING SUM(amount_paid) > 50000 ORDER BY SUM(amount_paid) DESC;


[User] Show me the subject and start times of all appointments along with the corresponding lawyer IDs for each client.

[Assistant] SELECT client_id, lawyer_id, subject, start_time FROM legal_services.appointments;


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

[User] Get a list of appointment_id, start_time, and invoice_number for appointments that have a related invoice.

[Assistant]
SELECT a.appointment_id,
       a.start_time,
       i.invoice_number
FROM legal_services.appointments a
JOIN legal_services.invoices i
  ON a.case_id = i.case_id;

[User] Also include only appointments that are completed and invoices that are fully paid (status 'Paid').

[Assistant]
SELECT a.appointment_id,
       a.start_time,
       i.invoice_number
FROM legal_services.appointments a
JOIN legal_services.invoices i
  ON a.case_id = i.case_id
WHERE a.status = 'Completed'
  AND i.status = 'Paid';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)

[User] Show me all time entries from the last 90 days, including the entry description, hours spent, the name of the case, and the name of the client.

[Assistant] SELECT T1.description, T1.hours_spent, T2.case_name, T3.first_name, T3.last_name FROM legal_services.time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id JOIN clients AS T3 ON T2.client_id = T3.client_id WHERE T1.date_worked >= CURRENT_DATE - INTERVAL '90 days';


[User] I want to see a list of invoice_number and appointment_id for each invoice that has a scheduled appointment.

[Assistant]
SELECT i.invoice_number,
       a.appointment_id
FROM legal_services.invoices i
JOIN legal_services.appointments a
  ON i.case_id = a.case_id
WHERE a.status = 'Scheduled';

[User] Only include those invoices whose due_date is still in the future.

[Assistant]
SELECT i.invoice_number,
       a.appointment_id
FROM legal_services.invoices i
JOIN legal_services.appointments a
  ON i.case_id = a.case_id
WHERE a.status = 'Scheduled'
  AND i.due_date > CURRENT_DATE;

[User] Finally, sort the results by the invoice issue_date in descending order.

[Assistant]
SELECT i.invoice_number,
       a.appointment_id
FROM legal_services.invoices i
JOIN legal_services.appointments a
  ON i.case_id = a.case_id
WHERE a.status = 'Scheduled'
  AND i.due_date > CURRENT_DATE
ORDER BY i.issue_date DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)

[User] List the document name, type, version, and description for all documents.

[Assistant] SELECT document_name, document_type, version, description FROM documents;

[User] Only include documents where the description is not null.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL;

[User] Also, filter to only show documents with a version greater than 2.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL AND version > 2;

[User] Order the results by upload timestamp descending.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL AND version > 2 ORDER BY upload_timestamp DESC;