DELIMITER $$
CREATE TRIGGER after_insert_into_histories
AFTER INSERT ON tbl_intraday_histories
FOR EACH ROW
BEGIN
    -- Check if an entry exists for the scrip_id and exchange_id
    IF EXISTS (
        SELECT 1 FROM tbl_intraday_prices
        WHERE scrip_id = NEW.scrip_id AND exchange_id = NEW.exchange_id
    ) THEN
        -- Update the existing entry with the latest data
        UPDATE tbl_intraday_prices
        SET 
            ask = NEW.ask,
            bid = NEW.bid,
            open = NEW.open,
            close = NEW.close,
            low = NEW.low,
            high = NEW.high,
            ltp = NEW.ltp,
            volume = NEW.volume,
            net_change = NEW.net_change,
            net_change_per = NEW.net_change_per,
            ltq = NEW.ltq
        WHERE scrip_id = NEW.scrip_id AND exchange_id = NEW.exchange_id;
    ELSE
        -- Insert a new record if none exists
        INSERT INTO tbl_intraday_prices (
            scrip_id, exchange_id, ask, bid, open, close, low, high, ltp, volume,
            net_change, net_change_per, ltq
        ) VALUES (
            NEW.scrip_id, NEW.exchange_id, NEW.ask, NEW.bid, NEW.open, NEW.close,
            NEW.low, NEW.high, NEW.ltp, NEW.volume, NEW.net_change, NEW.net_change_per,
            NEW.ltq
        );
    END IF;
END$$
DELIMITER ;