Skip to content
Related Articles

Related Articles

Improve Article

COUNT() Function in SQL Server

  • Last Updated : 19 Jan, 2021

COUNT() function :

This function in SQL Server is used to find the number of indexes as returned from the query selected.

Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.

Features :

  • This function is used to find the number of indexes as returned from the query selected.
  • This function comes under Numeric Functions.
  • This function accepts only one parameter namely expression.
  • This function ignore NULL values and doesn’t count them.

Syntax :



COUNT(expression)

Parameter :

This method accepts only one parameter as given below:

  • expression: Specified expression which can either be a field or a string type value.

Returns :

It returns the number of indexes as returned from the query selected.

Example-1 :

Using COUNT() function and getting the output.

CREATE TABLE product
(  
user_id int IDENTITY(100, 2) NOT NULL,    
product_1 VARCHAR(10),
product_2 VARCHAR(10),
price int  
);
INSERT product(product_1, price)  
VALUES ('rice', 400);

INSERT product(product_2, price)  
VALUES ('grains', 600);
SELECT COUNT(user_id) FROM product;

Output :

2

Example-2 :



Using COUNT() function and counting float values.

CREATE TABLE floats
(  
user_id int IDENTITY(100, 2) NOT NULL,
float_val float
);
INSERT floats(float_val)  
VALUES (3.5);
INSERT floats(float_val)  
VALUES (2.1);
INSERT floats(float_val)  
VALUES (6.3);
INSERT floats(float_val)  
VALUES (9.9);
INSERT floats(float_val)  
VALUES (7.0);
SELECT COUNT(float_val) FROM floats;

Output :

5

Example-3 :

Using COUNT() function and getting the output where MRP is greater than the number of counts of MRP.

CREATE TABLE package
(  
user_id int IDENTITY(100, 4) NOT NULL,  
item VARCHAR(10),
mrp int  
);
INSERT package(item, mrp)  
VALUES ('book1', 3);

INSERT package(item, mrp)  
VALUES ('book2', 350);

INSERT package(item, mrp)  
VALUES ('book3', 400);

SELECT * FROM package
WHERE mrp > (SELECT COUNT(mrp) FROM package);

Output :

  | user_id  | item     | mrp
--------------------------------
1 | 104      | book2    | 350
--------------------------------
2 | 108      | book3    | 400

Example-4 :

Using COUNT() function and getting the records of (MRP-sales price).

CREATE TABLE package
(  
user_id int IDENTITY(100, 4) NOT NULL,  
item VARCHAR(10),
mrp int,
sp int
);
INSERT package(item, mrp, sp)  
VALUES ('book1', 250, 240);
INSERT package(item, mrp, sp)  
VALUES ('book2', 350, 320);
INSERT package(item, mrp)  
VALUES ('book3', 400);
SELECT COUNT(mrp-sp) FROM package;

Output :

2

Application :

This function is used to find the number of indexes as returned from the query selected.

My Personal Notes arrow_drop_up
Recommended Articles
Page :