System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )

[User] Please list the full name and status of clients who have not provided a company name.

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

[User] Can you show me the company name, email, and phone of all clients who share the same status?

[Assistant]
SELECT a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id;

[User] What if I only want to see those clients who registered before January 1st, 2023?

[Assistant]
SELECT a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id
WHERE a.date_registered < '2023-01-01';

[User] Please add each client's first and last name, and sort the results by company_name.

[Assistant]
SELECT a.first_name, a.last_name, a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id
WHERE a.date_registered < '2023-01-01'
ORDER BY a.company_name;

[User] I need a list of unique company names and the number of clients in each company.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name;

[User] Only include companies where there are at least 2 clients.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name
HAVING COUNT(*) >= 2;

[User] Also, show the email addresses of the clients in those companies.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;

[User] Only show companies whose name contains the word 'Group'.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL AND company_name ILIKE '%Group%'
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;

[User] List all pairs of clients who registered in the same year. Show each client's first_name, last_name, and the registration year.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id;

[User] Actually, only include clients with status = 'active'.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id WHERE c1.status = 'active' AND c2.status = 'active';

[User] Also, sort the results by registration_year descending and then by the first client's last_name ascending.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id WHERE c1.status = 'active' AND c2.status = 'active' ORDER BY registration_year DESC, last_name_1 ASC;

[User] List the first_name, last_name, and email of all clients whose email domain is 'gmail.com'.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE SUBSTRING(email FROM POSITION('@' IN email) + 1) = 'gmail.com';

[User] List all pairs of clients who registered on the same day, showing each client's first_name, last_name, and the registration date.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, DATE(c1.date_registered) AS registration_date FROM legal_services.clients c1 JOIN legal_services.clients c2 ON DATE(c1.date_registered) = DATE(c2.date_registered) AND c1.client_id < c2.client_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )

[User] Show me the incident date, estimated loss, and the associated product name for all claims with an estimated loss greater than 20000.

[Assistant]
SELECT c.incident_date, c.estimated_loss, p.product_name
FROM insurance.claims c
JOIN insurance.policies pol ON c.policy_id = pol.policy_id
JOIN insurance.insurance_products p ON pol.product_id = p.product_id
WHERE c.estimated_loss > 20000;

[User] List all insurance products along with their product type and creation date.

[Assistant]
SELECT product_name, product_type, created_at
FROM insurance.insurance_products;

[User] Show me claim IDs and the file names of any documents associated with claims filed before January 1, 2024.

[Assistant]
SELECT cd.claim_id, cd.file_name
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01';

[User] Only include documents where the file size is less than 1 MB.

[Assistant]
SELECT cd.claim_id, cd.file_name
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes < 1048576;

[User] Add the document type to the results and sort by file size ascending.

[Assistant]
SELECT cd.claim_id, cd.file_name, cd.document_type, cd.file_size_bytes
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes < 1048576
ORDER BY cd.file_size_bytes ASC;

[User] Sorry, I got an error about NULL file sizes. Please exclude records where the file size is NULL.

[Assistant]
SELECT cd.claim_id, cd.file_name, cd.document_type, cd.file_size_bytes
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes IS NOT NULL
  AND cd.file_size_bytes < 1048576
ORDER BY cd.file_size_bytes ASC;

[User] How many claims were reported in the last 90 days?

[Assistant] SELECT COUNT(*) FROM claims WHERE reported_date >= CURRENT_DATE - INTERVAL '90 days'

[User] List all policies that have at least one beneficiary with a 'Child' relationship, showing policy number, policy status, and the number of child beneficiaries for that policy.

[Assistant] SELECT T1.policy_number, T1.status, COUNT(T2.beneficiary_id) AS child_beneficiary_count FROM policies AS T1 JOIN policy_beneficiaries AS T2 ON T1.policy_id = T2.policy_id WHERE T2.relationship = 'Child' GROUP BY T1.policy_id, T1.policy_number, T1.status HAVING COUNT(T2.beneficiary_id) >= 1

[User] Can you also include the total premium amount for these policies?

[Assistant] SELECT T1.policy_number, T1.status, T1.premium_amount, COUNT(T2.beneficiary_id) AS child_beneficiary_count FROM policies AS T1 JOIN policy_beneficiaries AS T2 ON T1.policy_id = T2.policy_id WHERE T2.relationship = 'Child' GROUP BY T1.policy_id, T1.policy_number, T1.status, T1.premium_amount HAVING COUNT(T2.beneficiary_id) >= 1

[User] Show all policies that started before January 1, 2022, including policy_id, policy_number, start_date, and status.

[Assistant]
SELECT policy_id, policy_number, start_date, status
FROM insurance.policies
WHERE start_date < '2022-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)

[User] For each sector, retrieve the ticker symbol and last_updated timestamp of the earliest and latest updated securities, labeling them as earliest_ticker, earliest_updated, latest_ticker, and latest_updated.

[Assistant]
WITH sector_stats AS (
  SELECT
    sector,
    MIN(last_updated) AS earliest_updated,
    MAX(last_updated) AS latest_updated
  FROM financial_services.securities
  GROUP BY sector
)
SELECT
  ss.sector,
  s_min.ticker_symbol AS earliest_ticker,
  ss.earliest_updated,
  s_max.ticker_symbol AS latest_ticker,
  ss.latest_updated
FROM sector_stats ss
LEFT JOIN financial_services.securities s_min
  ON s_min.sector = ss.sector
  AND s_min.last_updated = ss.earliest_updated
LEFT JOIN financial_services.securities s_max
  ON s_max.sector = ss.sector
  AND s_max.last_updated = ss.latest_updated;

[User] Actually, only include sectors where the time span between latest_updated and earliest_updated exceeds 30 days.

[Assistant]
WITH sector_stats AS (
  SELECT
    sector,
    MIN(last_updated) AS earliest_updated,
    MAX(last_updated) AS latest_updated
  FROM financial_services.securities
  GROUP BY sector
  HAVING MAX(last_updated) - MIN(last_updated) > INTERVAL '30 days'
)
SELECT
  ss.sector,
  s_min.ticker_symbol AS earliest_ticker,
  ss.earliest_updated,
  s_max.ticker_symbol AS latest_ticker,
  ss.latest_updated
FROM sector_stats ss
LEFT JOIN financial_services.securities s_min
  ON s_min.sector = ss.sector
  AND s_min.last_updated = ss.earliest_updated
LEFT JOIN financial_services.securities s_max
  ON s_max.sector = ss.sector
  AND s_max.last_updated = ss.latest_updated;

[User] Now order the results by the time span descending.

[Assistant]
WITH sector_stats AS (
  SELECT
    sector,
    MIN(last_updated) AS earliest_updated,
    MAX(last_updated) AS latest_updated
  FROM financial_services.securities
  GROUP BY sector
  HAVING MAX(last_updated) - MIN(last_updated) > INTERVAL '30 days'
)
SELECT
  ss.sector,
  s_min.ticker_symbol AS earliest_ticker,
  ss.earliest_updated,
  s_max.ticker_symbol AS latest_ticker,
  ss.latest_updated,
  ss.latest_updated - ss.earliest_updated AS time_span
FROM sector_stats ss
LEFT JOIN financial_services.securities s_min
  ON s_min.sector = ss.sector
  AND s_min.last_updated = ss.earliest_updated
LEFT JOIN financial_services.securities s_max
  ON s_max.sector = ss.sector
  AND s_max.last_updated = ss.latest_updated
ORDER BY time_span DESC;

[User] List pairs of securities that trade on different exchanges but belong to the same sector, showing ticker_symbol of both as symbol_a and symbol_b, their exchanges, and the sector.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.ticker_symbol < b.ticker_symbol;

[User] Actually, exclude any pairs where the sector is NULL and ensure uniqueness by requiring symbol_a < symbol_b.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.sector IS NOT NULL
  AND a.ticker_symbol < b.ticker_symbol;

[User] Now also order the results by sector ascending and symbol_a ascending.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.sector IS NOT NULL
  AND a.ticker_symbol < b.ticker_symbol
ORDER BY a.sector ASC, a.ticker_symbol ASC;

[User] Finally, only include pairs where both securities are denominated in USD.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.sector IS NOT NULL
  AND a.currency = 'USD'
  AND b.currency = 'USD'
  AND a.ticker_symbol < b.ticker_symbol
ORDER BY a.sector ASC, a.ticker_symbol ASC;

[User] Show the number of securities per exchange and the average length of their ticker symbols, including only exchanges that have more than 5 securities.

[Assistant]
SELECT exchange, COUNT(*) AS securities_count, AVG(LENGTH(ticker_symbol)) AS avg_ticker_length
FROM financial_services.securities
GROUP BY exchange
HAVING COUNT(*) > 5;

[User] Actually, exclude any entries where exchange is NULL.

[Assistant]
SELECT exchange, COUNT(*) AS securities_count, AVG(LENGTH(ticker_symbol)) AS avg_ticker_length
FROM financial_services.securities
WHERE exchange IS NOT NULL
GROUP BY exchange
HAVING COUNT(*) > 5;

[User] Also, sort the output by the securities_count in descending order.

[Assistant]
SELECT exchange, COUNT(*) AS securities_count, AVG(LENGTH(ticker_symbol)) AS avg_ticker_length
FROM financial_services.securities
WHERE exchange IS NOT NULL
GROUP BY exchange
HAVING COUNT(*) > 5
ORDER BY securities_count DESC;

[User] List the ticker_symbol and average close price for all securities of type 'ETF'.

[Assistant]
SELECT s.ticker_symbol, AVG(md.close_price) AS avg_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.security_type = 'ETF'
GROUP BY s.ticker_symbol;

[User] Sort the result by average close price descending.

[Assistant]
SELECT s.ticker_symbol, AVG(md.close_price) AS avg_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.security_type = 'ETF'
GROUP BY s.ticker_symbol
ORDER BY avg_close_price DESC;

[User] Show me all securities listed on the 'NYSE' exchange with their ticker symbol and most recent close price.

[Assistant]
SELECT s.security_name, s.ticker_symbol, md.close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.exchange = 'NYSE' AND md.data_timestamp = (
    SELECT MAX(md2.data_timestamp)
    FROM financial_services.market_data md2
    WHERE md2.security_id = s.security_id
);

[User] Only include securities where the close price is below 30.

[Assistant]
SELECT s.security_name, s.ticker_symbol, md.close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.exchange = 'NYSE'
  AND md.data_timestamp = (
    SELECT MAX(md2.data_timestamp)
    FROM financial_services.market_data md2
    WHERE md2.security_id = s.security_id
  )
  AND md.close_price < 30;

[User] Please add the sector information to the result as well.

[Assistant]
SELECT s.security_name, s.ticker_symbol, s.sector, md.close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.exchange = 'NYSE'
  AND md.data_timestamp = (
    SELECT MAX(md2.data_timestamp)
    FROM financial_services.market_data md2
    WHERE md2.security_id = s.security_id
  )
  AND md.close_price < 30;

[User] Show me all securities (security_id, ticker_symbol, security_name) that are traded on the NASDAQ exchange and belong to the 'Technology' sector, along with the employees (employee_id, first_name, last_name) who work in the 'Investment' department and were hired in the last 3 years.

[Assistant] SELECT s.security_id, s.ticker_symbol, s.security_name, e.employee_id, e.first_name, e.last_name FROM financial_services.securities s CROSS JOIN financial_services.employees e WHERE s.exchange = 'NASDAQ' AND s.sector = 'Technology' AND e.department = 'Investment' AND e.hire_date >= CURRENT_DATE - INTERVAL '3 years' AND e.status = 'Active';

[User] Now modify the query to only include securities with a ticker_symbol starting with 'A' and sort the results by security_name in ascending order.

[Assistant] SELECT s.security_id, s.ticker_symbol, s.security_name, e.employee_id, e.first_name, e.last_name FROM financial_services.securities s CROSS JOIN financial_services.employees e WHERE s.exchange = 'NASDAQ' AND s.sector = 'Technology' AND s.ticker_symbol LIKE 'A%' AND e.department = 'Investment' AND e.hire_date >= CURRENT_DATE - INTERVAL '3 years' AND e.status = 'Active' ORDER BY s.security_name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.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.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.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 names of service locations and categories of active services offered by the same agency.

[Assistant]
SELECT sl.location_name, s.category
FROM government_services.service_locations AS sl
JOIN government_services.services AS s
  ON sl.agency_id = s.agency_id
WHERE s.is_active = TRUE;

[User] Please exclude service locations that are not accessible.

[Assistant]
SELECT sl.location_name, s.category
FROM government_services.service_locations AS sl
JOIN government_services.services AS s
  ON sl.agency_id = s.agency_id
WHERE s.is_active = TRUE
  AND sl.is_accessible = TRUE;

[User] List the first name and last name of citizens along with the type and verification status of their documents.

[Assistant] SELECT T1.first_name, T1.last_name, T2.document_type, T2.verification_status FROM government_services.citizens AS T1 JOIN government_services.documents AS T2 ON T1.citizen_id = T2.citizen_id;

[User] Count the number of documents for each document type.

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

[User] Only include document types that have more than 50 documents.

[Assistant] SELECT document_type, COUNT(*) FROM government_services.documents GROUP BY document_type HAVING COUNT(*) > 50;

[User] Exclude documents that have an expiry date in the past.

[Assistant] SELECT document_type, COUNT(*) FROM government_services.documents WHERE expiry_date IS NULL OR expiry_date >= CURRENT_DATE GROUP BY document_type HAVING COUNT(*) > 50;

[User] Show the results ordered by the count in descending order.

[Assistant] SELECT document_type, COUNT(*) FROM government_services.documents WHERE expiry_date IS NULL OR expiry_date >= CURRENT_DATE GROUP BY document_type HAVING COUNT(*) > 50 ORDER BY COUNT(*) DESC;

[User] Retrieve the service names, location names, and cities for active services offered at accessible locations in California.

[Assistant]
SELECT s.service_name,
       sl.location_name,
       sl.city
FROM government_services.services AS s
JOIN government_services.service_locations AS sl
  ON s.agency_id = sl.agency_id
WHERE s.is_active = TRUE
  AND sl.is_accessible = TRUE
  AND sl.state = 'California';

[User] List the names of services available at service locations that are accessible and located in the state of 'California'.

[Assistant] SELECT T1.service_name, T2.location_name 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';

[User] Modify to only include services that are active.

[Assistant] SELECT T1.service_name, T2.location_name 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' AND T1.is_active = TRUE;

[User] List the names of services that have been scheduled at accessible service locations.

[Assistant] SELECT DISTINCT T1.service_name FROM government_services.services AS T1 JOIN government_services.appointments AS T2 ON T1.service_id = T2.service_id JOIN government_services.service_locations AS T3 ON T2.location_id = T3.location_id WHERE T3.is_accessible = TRUE

[User] Now, only include services from agencies with 'State' jurisdiction level.

[Assistant] SELECT DISTINCT T1.service_name FROM government_services.services AS T1 JOIN government_services.appointments AS T2 ON T1.service_id = T2.service_id JOIN government_services.service_locations AS T3 ON T2.location_id = T3.location_id JOIN government_services.agencies AS T4 ON T1.agency_id = T4.agency_id WHERE T3.is_accessible = TRUE AND T4.jurisdiction_level = 'State'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Node Label: :Station
// Properties:
//   station_id: String (Constraint: UNIQUE)
//   station_name: String
//   city: String (Index recommended)
//   state_province: String
//   country_code: String
//   address: String
//   timezone: String
//   number_of_platforms: Integer
//   created_at: DateTime
//   last_updated_at: DateTime
// Example Cypher CREATE:
// CREATE (:Station {station_id: 'station_xyz', station_name: 'Grand Central Terminal', city: 'New York', ...})
// Node Label: :Platform
// Properties:
//   platform_id: String (Constraint: UNIQUE)
//   platform_number: String
//   track_number: String
//   status: String
//   length_meters: Float
//   accessible: Boolean
// Relationship: (:Platform)-[:LOCATED_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (s:Station {station_id: 'station_xyz'})
// CREATE (p:Platform {platform_id: 'plat_123', ...})-[:LOCATED_AT]->(s)
// Node Label: :Train
// Properties:
//   train_id: String (Constraint: UNIQUE)
//   train_number: String (Constraint: UNIQUE)
//   model: String
//   manufacturer: String
//   year_manufactured: Integer
//   capacity: Integer
//   status: String
//   last_maintenance_date: Date
//   next_maintenance_date: Date
// Example Cypher CREATE:
// CREATE (:Train {train_id: 'train_789', train_number: 'Acela 2151', ...})
// Node Label: :TrainCar
// Properties:
//   car_id: String (Constraint: UNIQUE)
//   car_number: String
//   car_type: String
//   class: String
//   capacity: Integer
//   features: String (Or List<String> if driver supports)
// Relationship: (:TrainCar)-[:PART_OF_TRAIN]->(:Train)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'})
// CREATE (c:TrainCar {car_id: 'car_abc', ...})-[:PART_OF_TRAIN]->(t)
// Relationship: (:Route)-[rel:HAS_STOP]->(:Station)
// Relationship Properties on :HAS_STOP:
//   sequence_order: Integer
//   distance_from_previous_km: Float
//   typical_stop_duration_minutes: Integer
// Example Cypher CREATE:
// MATCH (r:Route {route_id: 'route_ne_corr'}), (s:Station {station_id: 'station_pvd'})
// CREATE (r)-[:HAS_STOP {sequence_order: 2, distance_from_previous_km: 70.5, ...}]->(s)
// Node Label: :Passenger
// Properties:
//   passenger_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   email: String (Constraint: UNIQUE, if not null)
//   phone_number: String (Constraint: UNIQUE, if not null)
//   date_of_birth: Date
//   loyalty_program_id: String
//   created_at: DateTime
// Example Cypher CREATE:
// CREATE (:Passenger {passenger_id: 'pass_pqr', first_name: 'Alice', ...})
// Node Label: :Booking
// Properties:
//   booking_id: String (Constraint: UNIQUE)
//   booking_datetime: DateTime
//   status: String
//   total_price: Float
//   currency_code: String
//   special_requests: String
// Relationships:
//   (:Passenger)-[:MADE_BOOKING]->(:Booking)
//   (:Booking)-[:FOR_TRIP]->(:ScheduledTrip)
// Example Cypher CREATE:
// MATCH (p:Passenger {passenger_id: 'pass_pqr'}), (sched:ScheduledTrip {schedule_id: 'sched_1122'})
// CREATE (p)-[:MADE_BOOKING]->(b:Booking {booking_id: 'book_zyx', ...})-[:FOR_TRIP]->(sched)
// Node Label: :Staff
// Properties:
//   staff_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   role: String
//   employee_number: String (Constraint: UNIQUE)
//   hire_date: Date
//   contact_email: String (Constraint: UNIQUE, if not null)
//   contact_phone: String
//   is_active: Boolean
// Relationship (Optional):
//   (:Staff)-[:BASED_AT]->(:Station)
// Example Cypher CREATE:
// CREATE (:Staff {staff_id: 'staff_mno', first_name: 'Bob', ...})
// OPTIONAL MATCH (s:Station {station_id: 'station_xyz'}) // If primary_station_id exists
// WITH s, staff_mno // Need to get the created staff node reference
// WHERE s IS NOT NULL
// CREATE (staff_mno)-[:BASED_AT]->(s)

[User] Can you retrieve the total number of train cars for each train in the database?

[Assistant]
MATCH (t:Train)<-[:PART_OF_TRAIN]-(tc:TrainCar)
RETURN t.train_id, t.train_number, COUNT(tc) AS total_cars
ORDER BY t.train_id

[User] Can you help me find all bookings made by passengers from a specific city, say 'Boston', including the passenger details and the scheduled trip information?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, st.schedule_id

[User] Can you modify the query to include only bookings with a status of 'Confirmed'?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston' AND b.status = 'Confirmed'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, st.schedule_id

[User] Can you also add the total price of each booking to the result?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston' AND b.status = 'Confirmed'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, b.total_price, st.schedule_id

[User] Can you sort the results by booking datetime in ascending order?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston' AND b.status = 'Confirmed'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, b.total_price, st.schedule_id
ORDER BY b.booking_datetime ASC

[User] 能否帮我统计特定车站(station_id 为 'station_xyz')的所有工作人员数量？

[Assistant]
MATCH (s:Station {station_id: 'station_xyz'})<-[:BASED_AT]-(staff:Staff)
RETURN COUNT(staff) AS total_staff

[User] Can you help me find all staff members based at a specific station with station_id 'station_xyz', including the station details and platform information they are associated with?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status

[User] Can you filter the results to include only staff with the role of 'Manager' and platforms with status 'Operational'?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
WHERE stf.role = 'Manager' AND (p.status = 'Operational' OR p IS NULL)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status

[User] Can you sort the results by staff last name and platform number?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
WHERE stf.role = 'Manager' AND (p.status = 'Operational' OR p IS NULL)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status
ORDER BY stf.last_name, p.platform_number

[User] Can you provide the total number of maintenance records for a specific train with train_id 'train_789'?

[Assistant]
MATCH (t:Train {train_id: 'train_789'})<-[:PERFORMED_ON]-(mr:MaintenanceRecord)
RETURN COUNT(mr) AS total_maintenance_records


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )

[User] Show me the total number of players who have unlocked at least one achievement on each server, along with the server name and game title.

[Assistant]
SELECT s.server_id, s.server_name, s.game_id, COUNT(DISTINCT pa.player_id) AS total_players
FROM gaming_technology.player_achievements pa
JOIN gaming_technology.game_sessions gs ON pa.player_id = gs.player_id AND pa.achievement_id IS NOT NULL AND gs.server_id IS NOT NULL
JOIN gaming_technology.servers s ON gs.server_id = s.server_id
GROUP BY s.server_id, s.server_name, s.game_id;

[User] Can you also include each server's current_players and status in the result?

[Assistant]
SELECT s.server_id, s.server_name, s.game_id, s.current_players, s.status, COUNT(DISTINCT pa.player_id) AS total_players
FROM gaming_technology.player_achievements pa
JOIN gaming_technology.game_sessions gs ON pa.player_id = gs.player_id AND pa.achievement_id IS NOT NULL AND gs.server_id IS NOT NULL
JOIN gaming_technology.servers s ON gs.server_id = s.server_id
GROUP BY s.server_id, s.server_name, s.game_id, s.current_players, s.status;

[User] Give me a list of developers and how many unique games they have created. Show developer name and total_games.

[Assistant]
SELECT d.name AS developer_name, COUNT(DISTINCT g.game_id) AS total_games
FROM gaming_technology.developers d
LEFT JOIN gaming_technology.games g ON d.developer_id = g.developer_id
GROUP BY d.developer_id, d.name;

[User] Oops, it says table 'gaming_technology.games' does not exist. Please adjust the SQL to just show information about the developers.

[Assistant]
SELECT name AS developer_name, country, founded_year
FROM gaming_technology.developers;

[User] I only want to see developers founded after 2015.

[Assistant]
SELECT name AS developer_name, country, founded_year
FROM gaming_technology.developers
WHERE founded_year > 2015;

[User] Also include the website column, and order by founded_year descending.

[Assistant]
SELECT name AS developer_name, country, founded_year, website
FROM gaming_technology.developers
WHERE founded_year > 2015
ORDER BY founded_year DESC;

[User] List all items of type 'Armor' in the database, showing the item name, rarity, and their corresponding game_id.

[Assistant]
SELECT item_id, item_name, rarity, game_id
FROM gaming_technology.in_game_items
WHERE item_type = 'Armor';

[User] Please also show their cost_amount and cost_currency.

[Assistant]
SELECT item_id, item_name, rarity, game_id, cost_amount, cost_currency
FROM gaming_technology.in_game_items
WHERE item_type = 'Armor';

[User] Now only include results where the cost_amount is at least 500.

[Assistant]
SELECT item_id, item_name, rarity, game_id, cost_amount, cost_currency
FROM gaming_technology.in_game_items
WHERE item_type = 'Armor' AND cost_amount >= 500;

[User] Order the items by cost_amount in descending order.

[Assistant]
SELECT item_id, item_name, rarity, game_id, cost_amount, cost_currency
FROM gaming_technology.in_game_items
WHERE item_type = 'Armor' AND cost_amount >= 500
ORDER BY cost_amount DESC;

[User] Show the usernames of players and a count of how many different item types they have in their inventory.

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username;

[User] Only include players who have 3 or more different item types.

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username HAVING count(DISTINCT T3.item_type) >= 3;

[User] Order the results by the count of unique item types in descending order.

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username HAVING count(DISTINCT T3.item_type) >= 3 ORDER BY count(DISTINCT T3.item_type) DESC;

[User] For these players, could you also show the total quantity of all items they possess?

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type), sum(T2.quantity) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username HAVING count(DISTINCT T3.item_type) >= 3 ORDER BY count(DISTINCT T3.item_type) DESC;

[User] List the names and types of all in-game items that have a rarity of 'Epic'.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic';

[User] Further restrict the list to only include items of item_type 'Weapon'.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon';

[User] Order these results by their cost_amount in descending order.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon' ORDER BY cost_amount DESC;

[User] Please also include the cost_currency and cost_amount in the output.

[Assistant] SELECT item_name, item_type, cost_currency, cost_amount FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon' ORDER BY cost_amount DESC;

[User] Show for each player the total score achieved in sessions on each server, and the number of sessions per server.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id;

[User] Now also include the maximum duration of any session that player has had on that server.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count, MAX(duration_seconds) AS max_session_duration
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id;

[User] For each player-server pair, include the average session duration as well.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count, MAX(duration_seconds) AS max_session_duration, AVG(duration_seconds) AS avg_session_duration
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id;

[User] Finally, only include player-server pairs where the session_count is at least 5.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count, MAX(duration_seconds) AS max_session_duration, AVG(duration_seconds) AS avg_session_duration
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id
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 hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, type_name character varying(100) NOT NULL, description text, base_rate numeric(10, 2) NOT NULL, max_occupancy integer NOT NULL, bed_type character varying(50), area_sqft numeric(8,2), amenities text, PRIMARY KEY (room_type_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.payments ( payment_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, bill_id character varying(64), amount numeric(12,2) NOT NULL, currency_code character varying(3) NOT NULL, payment_method character varying(50) NOT NULL, card_type character varying(50), card_last_four character varying(4), transaction_ref character varying(128), payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, status character varying(50) NOT NULL, staff_id_processed character varying(64), notes text, PRIMARY KEY (payment_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )

[User] List all services in the 'Concierge' department along with their names, price, and whether they are currently available. Include the property name as well.

[Assistant]
SELECT s.service_name, s.price, s.is_available, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.department = 'Concierge';

[User] Could you filter only those services that are not currently available and sort by price ascending?

[Assistant]
SELECT s.service_name, s.price, s.is_available, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.department = 'Concierge'
  AND s.is_available = false
ORDER BY s.price ASC;

[User] Instead, show only properties in the city of 'Miami' and add the service category to the results.

[Assistant]
SELECT s.service_name, s.category, s.price, s.is_available, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.department = 'Concierge'
  AND s.is_available = false
  AND p.city = 'Miami'
ORDER BY s.price ASC;

[User] List all reservations along with the guest's full name and the property name for reservations made in properties outside the USA.

[Assistant]
SELECT r.reservation_id, g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE p.country_code <> 'USA';

[User] Only include reservations with a total amount greater than 800, and sort the results by total_amount descending.

[Assistant]
SELECT r.reservation_id, g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name, r.total_amount
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE p.country_code <> 'USA'
  AND r.total_amount > 800
ORDER BY r.total_amount DESC;

[User] Get a list of room types along with their property name and the count of rooms currently Available for each type.

[Assistant]
SELECT rt.type_name, p.property_name, COUNT(r.room_id) AS available_rooms_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.rooms r ON rt.room_type_id = r.room_type_id
  AND r.status = 'Available'
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
GROUP BY rt.type_name, p.property_name;

[User] Get the full name of guests, the property name, check-in and check-out dates, and total amount for all reservations with more than 2 adults.

[Assistant] SELECT g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name, r.check_in_date, r.check_out_date, r.total_amount FROM hospitality_technology.reservations r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id JOIN hospitality_technology.properties p ON r.property_id = p.property_id WHERE r.num_adults > 2;

[User] Actually, only include reservations where total_amount exceeds 1000 and sort the results by total_amount descending.

[Assistant] SELECT g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name, r.check_in_date, r.check_out_date, r.total_amount FROM hospitality_technology.reservations r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id JOIN hospitality_technology.properties p ON r.property_id = p.property_id WHERE r.num_adults > 2 AND r.total_amount > 1000 ORDER BY r.total_amount DESC;

[User] List all active staff members who are managers, along with their hire dates and email addresses.

[Assistant] SELECT staff_id, first_name, last_name, position, work_email, hire_date FROM hospitality_technology.staff WHERE is_active = true AND position = 'Manager';

[User] Now include only managers who were hired in the last 3 years.

[Assistant] SELECT staff_id, first_name, last_name, position, work_email, hire_date FROM hospitality_technology.staff WHERE is_active = true AND position = 'Manager' AND hire_date >= CURRENT_DATE - INTERVAL '3 years';

[User] The query should also show how many staff members each manager supervises.

[Assistant] SELECT s.staff_id, s.first_name, s.last_name, s.position, s.work_email, s.hire_date, COUNT(sub.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s LEFT JOIN hospitality_technology.staff sub ON s.staff_id = sub.manager_id WHERE s.is_active = true AND s.position = 'Manager' AND s.hire_date >= CURRENT_DATE - INTERVAL '3 years' GROUP BY s.staff_id, s.first_name, s.last_name, s.position, s.work_email, s.hire_date;

[User] Actually, I only need managers who supervise at least 3 staff members.

[Assistant] SELECT s.staff_id, s.first_name, s.last_name, s.position, s.work_email, s.hire_date, COUNT(sub.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s LEFT JOIN hospitality_technology.staff sub ON s.staff_id = sub.manager_id WHERE s.is_active = true AND s.position = 'Manager' AND s.hire_date >= CURRENT_DATE - INTERVAL '3 years' GROUP BY s.staff_id, s.first_name, s.last_name, s.position, s.work_email, s.hire_date HAVING COUNT(sub.staff_id) >= 3;

[User] Show all active staff members' full names and their positions.

[Assistant]
SELECT staff_id, first_name || ' ' || last_name AS staff_full_name, position
FROM hospitality_technology.staff
WHERE is_active = true;

[User] Also include the name of the property they work at.

[Assistant]
SELECT s.staff_id, s.first_name || ' ' || s.last_name AS staff_full_name, s.position, p.property_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.is_active = true;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )

[User] Find all applications that were submitted in 2023 but received a decision ('Approved' or 'Rejected') in 2024. List the application ID, submitted date, decision date, and status.

[Assistant] SELECT application_id, submitted_at, decision_date, status FROM government_services.applications WHERE submitted_at BETWEEN '2023-01-01 00:00:00' AND '2023-12-31 23:59:59' AND status IN ('Approved', 'Rejected') AND decision_date BETWEEN '2024-01-01' AND '2024-12-31';

[User] For each service ID, what is the average number of days between the submission date and the decision date for applications that have a recorded decision?

[Assistant] SELECT service_id, AVG(EXTRACT(EPOCH FROM (decision_date - submitted_at)) / 86400) AS average_days_to_decision FROM government_services.applications WHERE decision_date IS NOT NULL GROUP BY service_id;

[User] List the application ID, submitted date, and assigned employee ID for all applications that are currently in 'Processing' status and were submitted before January 1st, 2024.

[Assistant] SELECT application_id, submitted_at, assigned_employee_id FROM government_services.applications WHERE status = 'Processing' AND submitted_at < '2024-01-01';

[User] List the reference_number and status for all applications assigned to employee 'emp200', along with the submitted_at date of each application.

[Assistant] SELECT reference_number, status, submitted_at FROM government_services.applications WHERE assigned_employee_id = 'emp200';

[User] Show only those applications that have status 'Pending' and were submitted after January 1, 2024.

[Assistant] SELECT reference_number, status, submitted_at FROM government_services.applications WHERE assigned_employee_id = 'emp200' AND status = 'Pending' AND submitted_at > '2024-01-01';

[User] Show all applications for citizen 'cit789' that were last updated in March 2024, including their reference_number, status, and last_updated_at.

[Assistant] SELECT reference_number, status, last_updated_at FROM government_services.applications WHERE citizen_id = 'cit789' AND last_updated_at >= '2024-03-01' AND last_updated_at < '2024-04-01';

[User] List the reference number and status for applications where the notes contain the keyword 'urgent'.

[Assistant] SELECT reference_number, status FROM government_services.applications WHERE notes ILIKE '%urgent%';

[User] Among those, show only the applications with a status of 'Pending'.

[Assistant] SELECT reference_number, status FROM government_services.applications WHERE notes ILIKE '%urgent%' AND status = 'Pending';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] Retrieve all unique chief complaints from medical_records.

[Assistant]
SELECT DISTINCT chief_complaint
FROM healthcare.medical_records;

[User] Now show chief complaints that occur more than 3 times along with their occurrence count.

[Assistant]
SELECT chief_complaint,
       COUNT(*) AS complaint_count
FROM healthcare.medical_records
GROUP BY chief_complaint
HAVING COUNT(*) > 3;

[User] Show prescriptions with their corresponding chief complaint from the medical record. Return prescription_id, record_id, and chief_complaint.

[Assistant]
SELECT p.prescription_id, p.record_id, mr.chief_complaint
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id;

[User] Only include prescriptions where chief_complaint contains 'fever' and the route is 'Oral'.

[Assistant]
SELECT p.prescription_id, p.record_id, mr.chief_complaint
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id
WHERE mr.chief_complaint ILIKE '%fever%'
  AND p.route = 'Oral';

[User] Also include the medication_name by joining the medications table and sort the results by prescription_date ascending.

[Assistant]
SELECT p.prescription_id,
       p.record_id,
       mr.chief_complaint,
       m.medication_name
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id
LEFT JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE mr.chief_complaint ILIKE '%fever%'
  AND p.route = 'Oral'
ORDER BY p.prescription_date ASC;

[User] List patient_id, full name, policy_number, plan_type, and insurance_provider for all active primary insurance policies.

[Assistant]
SELECT pi.patient_id,
       p.first_name,
       p.last_name,
       pi.policy_number,
       ip.plan_type,
       ip.insurance_provider
FROM healthcare.patient_insurance pi
JOIN healthcare.patients p
  ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip
  ON ip.plan_id = pi.plan_id
WHERE pi.is_primary = TRUE
  AND pi.effective_date <= CURRENT_DATE
  AND pi.expiration_date >= CURRENT_DATE;

[User] Now also restrict to policies expiring within the next 30 days.

[Assistant]
SELECT pi.patient_id,
       p.first_name,
       p.last_name,
       pi.policy_number,
       ip.plan_type,
       ip.insurance_provider
FROM healthcare.patient_insurance pi
JOIN healthcare.patients p
  ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip
  ON ip.plan_id = pi.plan_id
WHERE pi.is_primary = TRUE
  AND pi.effective_date <= CURRENT_DATE
  AND pi.expiration_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days';

[User] How many patients are there in each gender category?

[Assistant]
SELECT gender,
       COUNT(*) AS patient_count
FROM healthcare.patients
GROUP BY gender;

[User] Only include categories with more than 50 patients.

[Assistant]
SELECT gender,
       COUNT(*) AS patient_count
FROM healthcare.patients
GROUP BY gender
HAVING COUNT(*) > 50;

[User] Show me all patients who have scheduled appointments with doctors specializing in Cardiology, along with their appointment times and the doctors' full names.

[Assistant] SELECT p.patient_id, p.first_name, p.last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name FROM healthcare.patients p JOIN healthcare.appointments a ON p.patient_id = a.patient_id JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id WHERE d.specialty = 'Cardiology' ORDER BY a.appointment_time;

[User] I need to find patients who received prescriptions within 7 days after their latest appointment. Show patient_id, first and last name, appointment_time, prescription_date, and medication_name.

[Assistant]
WITH latest_appt AS (
  SELECT patient_id, MAX(appointment_time) AS latest_time
  FROM healthcare.appointments
  GROUP BY patient_id
)
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       la.latest_time AS appointment_time,
       pr.prescription_date,
       m.medication_name
FROM latest_appt la
JOIN healthcare.patients p
  ON p.patient_id = la.patient_id
JOIN healthcare.prescriptions pr
  ON pr.patient_id = la.patient_id
  AND pr.prescription_date BETWEEN la.latest_time AND la.latest_time + INTERVAL '7 days'
JOIN healthcare.medications m
  ON m.medication_id = pr.medication_id

[User] Actually, restrict it to prescriptions where dosage contains 'mg'.

[Assistant]
WITH latest_appt AS (
  SELECT patient_id, MAX(appointment_time) AS latest_time
  FROM healthcare.appointments
  GROUP BY patient_id
)
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       la.latest_time AS appointment_time,
       pr.prescription_date,
       m.medication_name
FROM latest_appt la
JOIN healthcare.patients p
  ON p.patient_id = la.patient_id
JOIN healthcare.prescriptions pr
  ON pr.patient_id = la.patient_id
  AND pr.prescription_date BETWEEN la.latest_time AND la.latest_time + INTERVAL '7 days'
  AND pr.dosage LIKE '%mg%'
JOIN healthcare.medications m
  ON m.medication_id = pr.medication_id

[User] Also, sort the results by prescription_date descending and limit to 5.

[Assistant]
WITH latest_appt AS (
  SELECT patient_id, MAX(appointment_time) AS latest_time
  FROM healthcare.appointments
  GROUP BY patient_id
)
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       la.latest_time AS appointment_time,
       pr.prescription_date,
       m.medication_name
FROM latest_appt la
JOIN healthcare.patients p
  ON p.patient_id = la.patient_id
JOIN healthcare.prescriptions pr
  ON pr.patient_id = la.patient_id
  AND pr.prescription_date BETWEEN la.latest_time AND la.latest_time + INTERVAL '7 days'
  AND pr.dosage LIKE '%mg%'
JOIN healthcare.medications m
  ON m.medication_id = pr.medication_id
ORDER BY pr.prescription_date DESC
LIMIT 5


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

[User] Count how many tokens exist for each contract_address.

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

[User] Now only include contract_address values that have more than 2 tokens.

[Assistant]
SELECT contract_address,
       COUNT(*) AS token_count
FROM web3.tokens
GROUP BY contract_address
HAVING COUNT(*) > 2;

[User] Show the distribution of total supply for tokens, grouped into ranges like < 1 million, 1 million to 1 billion, and > 1 billion. Count how many tokens fall into each range.

[Assistant] SELECT CASE WHEN total_supply < 1000000 THEN '< 1 million' WHEN total_supply >= 1000000 AND total_supply <= 1000000000 THEN '1 million to 1 billion' WHEN total_supply > 1000000000 THEN '> 1 billion' ELSE 'Other' END AS supply_range, COUNT(*) AS token_count FROM web3.tokens GROUP BY supply_range ORDER BY CASE WHEN supply_range = '< 1 million' THEN 1 WHEN supply_range = '1 million to 1 billion' THEN 2 WHEN supply_range = '> 1 billion' THEN 3 ELSE 4 END;

[User] Instead of the count, can you show the average total supply for tokens in each range?

[Assistant] SELECT CASE WHEN total_supply < 1000000 THEN '< 1 million' WHEN total_supply >= 1000000 AND total_supply <= 1000000000 THEN '1 million to 1 billion' WHEN total_supply > 1000000000 THEN '> 1 billion' ELSE 'Other' END AS supply_range, AVG(total_supply) AS average_total_supply FROM web3.tokens GROUP BY supply_range ORDER BY CASE WHEN supply_range = '< 1 million' THEN 1 WHEN supply_range = '1 million to 1 billion' THEN 2 WHEN supply_range = '> 1 billion' THEN 3 ELSE 4 END;

[User] For each token, show its token_id, decimals, and the average total_supply of all tokens with the same decimals.

[Assistant]
SELECT t.token_id,
       t.decimals,
       avg_data.avg_total_supply
FROM web3.tokens t
JOIN (
  SELECT decimals,
         AVG(total_supply) AS avg_total_supply
  FROM web3.tokens
  GROUP BY decimals
) AS avg_data
  ON t.decimals = avg_data.decimals;

[User] Find all pairs of tokens that have the same token name but different contract addresses, showing both token IDs, the shared token name, and each contract address.

[Assistant]
SELECT t1.token_id AS token_id_1, t2.token_id AS token_id_2, t1.token_name, t1.contract_address AS contract_address_1, t2.contract_address AS contract_address_2
FROM web3.tokens t1
JOIN web3.tokens t2
  ON t1.token_name = t2.token_name
  AND t1.contract_address <> t2.contract_address
  AND t1.token_id < t2.token_id;

[User] List the token symbol, token name, and contract address for all tokens that have no recorded transfers in the token_transfers table.

[Assistant] SELECT T.token_symbol, T.token_name, T.contract_address FROM web3.tokens AS T LEFT JOIN token_transfers AS TT ON T.token_id = TT.token_id WHERE TT.transfer_id IS NULL;

[User] List the token symbol and name for all tokens whose associated contract address has emitted at least one event. Also include the contract address.

[Assistant] SELECT T.token_symbol, T.token_name, T.contract_address FROM web3.tokens AS T JOIN contracts AS C ON T.contract_address = C.address JOIN events AS E ON C.contract_id = E.contract_id GROUP BY T.token_symbol, T.token_name, T.contract_address;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Retrieve the policy_number, claim_id, incident_date, and document_type for all claims that have at least one "Damage Assessment" document. Sort the results by incident_date descending.

[Assistant]
SELECT p.policy_number, c.claim_id, c.incident_date, cd.document_type
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
JOIN insurance.policies p ON c.policy_id = p.policy_id
WHERE cd.document_type = 'Damage Assessment'
ORDER BY c.incident_date DESC;

[User] How many beneficiaries exist for each relationship type in the policy_beneficiaries table? Return relationship and beneficiary_count, ordered by count descending.

[Assistant]
SELECT relationship, COUNT(*) AS beneficiary_count
FROM insurance.policy_beneficiaries
GROUP BY relationship
ORDER BY beneficiary_count DESC;

[User] List all insurance products that have a base premium greater than 1000 and are currently active, showing product name, type, and base premium.

[Assistant] SELECT product_name, product_type, base_premium FROM insurance.insurance_products WHERE base_premium > 1000 AND is_active = TRUE

[User] Now, find policies associated with these products that were issued in 2024, showing the policy number and its premium amount.

[Assistant] SELECT p.policy_number, p.premium_amount FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE ip.base_premium > 1000 AND ip.is_active = TRUE AND date_part('year', p.issued_at) = 2024

[User] Show the total file size in bytes for all documents uploaded with a MIME type of 'application/pdf'.

[Assistant] SELECT SUM(file_size_bytes) FROM insurance.claim_documents WHERE mime_type = 'application/pdf'

[User] Show policy numbers and product names for all policies that started in 2023.

[Assistant] SELECT p.policy_number, ip.product_name FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE date_part('year', p.start_date) = 2023

[User] Add the policy status and the product type to the list.

[Assistant] SELECT p.policy_number, ip.product_name, p.status, ip.product_type FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE date_part('year', p.start_date) = 2023

[User] Filter these policies to only include those where the product is currently active and the policy status is 'active'.

[Assistant] SELECT p.policy_number, ip.product_name, p.status, ip.product_type FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE date_part('year', p.start_date) = 2023 AND p.status = 'active' AND ip.is_active = TRUE

[User] For all claims filed in 2024, show the claim ID, incident date, policy number, and the name of the associated insurance product.

[Assistant]
SELECT c.claim_id, c.incident_date, p.policy_number, ip.product_name
FROM insurance.claims c
JOIN insurance.policies p ON c.policy_id = p.policy_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE EXTRACT(YEAR FROM c.incident_date) = 2024;