SiteMap  | About    

C# ADO.NET SqlCommand - ExecuteScalar

The ExecuteScalar() in C# SqlCommand Object is using for retrieve a single value from Database after the execution of the SQL Statement. The ExecuteScalar() executes SQL statements as well as Stored Procedure and returned a scalar value on first column of first row in the returned Result Set.

If the Result Set contains more than one columns or rows , it will take only the value of first column of the first row, and all other values will ignore. If the Result Set is empty it will return a NULL reference.

It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources.

using System;
using System.Windows.Forms;
using System.Data.SqlClient; 

namespace WindowsApplication1
    public partial class Form1 : Form
        public Form1()

        private void button1_Click(object sender, EventArgs e)
            string connetionString = null;
            SqlConnection cnn ;
            SqlCommand cmd ;
            string sql = null;

            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
            sql = "Your SQL Statement Here like Select Count(*) from product";

            cnn = new SqlConnection(connetionString);
                cmd = new SqlCommand(sql, cnn);
                Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
                MessageBox.Show (" No. of Rows " + count);
            catch (Exception ex)
                MessageBox.Show("Can not open connection ! ");
} (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.