def insert_query(db_conn, group_id, query, domain=None):
    """
    Insert query and optional domain.

    If the pair already exists, simply return the ID of the existing pair.

    Args:
        db_conn (psycopg2.extensions.connection): Connection to a database
        group_id (int): A unique integer identifier for the group of results
        query (str): A query string
        domain (str): Optional domain (eg. "data.cityofchicago.org")

    Returns:
        The query ID for the newly inserted query (or the existing query if its already in the DB)
    """
    with db_conn.cursor() as cur:
        insert = "INSERT INTO arcs_query (query, domain) " \
                 "SELECT %s, %s WHERE NOT EXISTS " \
                 "(SELECT id FROM arcs_query WHERE query=%s AND domain=%s) " \
                 "RETURNING id"

        cur.execute(insert, (query, domain, query, domain))
        last_result = cur.fetchone()

        if not last_result:
            cond_select = "SELECT id FROM arcs_query WHERE query=%s AND domain=%s"
            cur.execute(cond_select, (query, domain))
            last_result = cur.fetchone()

        query_id = last_result[0]

        insert2 = "INSERT INTO arcs_query_group_join (query_id, group_id) " \
                  "VALUES (%s, %s)"
        cur.execute(insert2, (query_id, group_id))

        return query_id