T-SQL Tutorial

SQL Check if row exists in table


Check if row exists in table

Before you insert, update or delete rows from a sql table, you may need to know if there are any records in the table. Check if there are rows in the table using TOP, COUNT, EXISTS or NOT EXISTS.

Example


Tutorials table:

IDNAMEDURATIONPRICE
1SQL tutorial2200
2T-SQL tutorial5300
3Learn ASP5400
4PHP tutorial3200
5Learn HTML2100

SELECT TOP 1 * FROM tutorials;
SELECT count(1) FROM tutorials;
SELECT TOP 1 * FROM tutorials WHERE price=200;
SELECT count(1) FROM tutorials WHERE price=200;





Insert row in a table

USE model;
GO
IF NOT EXISTS ( select 1 from tutorials where name='Learn MySQL' )
BEGIN
    INSERT INTO tutorials(id, name, duration, price) VALUES (6, 'Learn MySQL', 3, 250);
END
ELSE
PRINT 'Record exists'
GO

Delete row from a table

USE model;
GO
IF EXISTS ( select 1 from tutorials where name='Learn MySQL' )
BEGIN
    delete from tutorials where name='Learn MySQL';
END
ELSE
PRINT 'No row found'
GO