Skip to content

Commit 44a0baf

Browse files
added_16
1 parent 4764166 commit 44a0baf

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

sql_tips_ankit_bansal.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1973,3 +1973,36 @@ count(dept_name) .. means count over a column name .. give count of row expect n
19731973
---
19741974
---
19751975

1976+
1977+
## 16 - SQL to Count Occurrence of a Character/Word in a String
1978+
1979+
```sql
1980+
create table strings (name varchar(50));
1981+
delete from strings;
1982+
insert into strings values ('Ankit Bansal'),('Ram Kumar Verma'),('Akshay Kumar Ak k'),('Rahul');
1983+
1984+
1985+
select * from strings;
1986+
```
1987+
1988+
* Query to count no of spaces in the string --
1989+
1990+
```sql
1991+
select name , replace( name , ' ' , '') as rep_name , length(name) - length(replace( name , ' ' , '')) as cnt from strings;
1992+
1993+
```
1994+
1995+
* Query to count no of occurrences of 'Ak' in the strings -- this is a sample use case
1996+
1997+
```sql
1998+
1999+
SELECT
2000+
name,
2001+
REPLACE(name, 'Ak', '') AS rep_name,
2002+
ROUND((LENGTH(name) - LENGTH(REPLACE(name, 'Ak', ''))) / LENGTH('Ak')) AS cnt
2003+
FROM strings;
2004+
2005+
```
2006+
2007+
---
2008+
---

0 commit comments

Comments
 (0)