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:
ID | NAME | DURATION | PRICE |
---|---|---|---|
1 | SQL tutorial | 2 | 200 |
2 | T-SQL tutorial | 5 | 300 |
3 | Learn ASP | 5 | 400 |
4 | PHP tutorial | 3 | 200 |
5 | Learn HTML | 2 | 100 |
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