How to use the OVERLAY() function in SQL
The SQL OVERLAY() function
The OVERLAY() function is used to replace a substring within a string at the given starting position.
Syntax
OVERLAY(string PLACING replacing_string FROM start [FOR count])
Parameters
string: It represents the string whose substring is to be replaced.replacing_string: It represents the substring to be replaced with.start: It represents the index to start the replacement.count: This is an optional parameter. It represents the number of characters to be replaced.
Code example
The following code shows how to use the OVERLAY() function in SQL.
CREATE TABLE Product (id int,product_name varchar(50),price varchar(50),product_id varchar (20));-- Insert dataINSERT INTO ProductVALUES (101,'T-shirt','$100','oo-01-345');INSERT INTO ProductVALUES (102,'Hand Bag','$65','oo-01-238');INSERT INTO ProductVALUES (103,'Ipad','$1200','oo-01-103');INSERT INTO ProductVALUES (104,'Cereal','$30','oo-01-775');INSERT INTO ProductVALUES (105,'Microwave','$520','oo-01-788');INSERT INTO ProductVALUES (106,'cloth clips','$15','oo-01-924');INSERT INTO ProductVALUES (108,'Zara Perfume','$120','oo-01-245');-- QuerySELECT product_id, product_name, OVERLAY(product_id PLACING 'bkEDA' FROM 1) AS ovl_product_idFROM Product;
Code explanation
- Lines 1–7: We create a table called
Product, which has the columnsid,product_name,price, andbook_id. - Lines 11–21: We add data to the table.
- Lines 24–26: We retrieve the data in the columns
product_idandproduct_name. We then use theOVERLAY()function to replace the substringoo-01of each product ID withbkEDAand store it in a new columnovl_product_id.