Find Youtube ID from Youtube URL using SUBSTRING and CHARINDEX in SQL Server


In this example, I will show you how to find the Youtube ID from the Youtube URL using SUBSTRING and CHARINDEX in SQL Server.

extract youtube id from youtube link in sql server

--Create Table tbl_youtube

CREATE TABLE [dbo].[tbl_youtube](
       [SerialNo] [int] PRIMARY KEY,
       [YoutubeLink] [nvarchar](100) NOT NULL
)
GO

-- Insert data into Table tbl_youtube

INSERT [dbo].[tbl_youtube] ([SerialNo], [YoutubeLink]) VALUES (1, N'www.youtube.com/watch?v=LlWczLf_1aI')
GO
INSERT [dbo].[tbl_youtube] ([SerialNo], [YoutubeLink]) VALUES (2, N'www.youtube.com/watch?v=qriIWFg7EGQ')
GO
INSERT [dbo].[tbl_youtube] ([SerialNo], [YoutubeLink]) VALUES (3, N'www.youtube.com/watch?v=FuZCS4Yv78s')
GO
INSERT [dbo].[tbl_youtube] ([SerialNo], [YoutubeLink]) VALUES (4, N'www.youtube.com/watch?v=qoeovUaE9CA')
GO
INSERT [dbo].[tbl_youtube] ([SerialNo], [YoutubeLink]) VALUES (5, N'www.youtube.com/watch?v=nldWPzHmUGU')
GO

-- Select data from tbl_youtube

SELECT * FROM tbl_youtube

finding youtube id from youtube url


-- Select Youtube ID from the Table tbl_youtube

SELECT SerialNo, SUBSTRING([YoutubeLink], CHARINDEX('?v=',[YoutubeLink])+3 ,11) AS YoutubeID
FROM dbo.tbl_youtube

string operation in sql server

Above example just shows how to use SUBSTRING and CHARINDEX together. But we can find the Youtube ID more easily just by using RIGHT() function.

SELECT RIGHT('www.youtube.com/watch?v=LlWczLf_1aI',11)