How can I create and use a calculated column in a SQL Server query?
How can I create and use a calculated column in a SQL Server query?
14511-Jul-2024
Updated on 12-Jul-2024
Home / DeveloperSection / Forums / How can I create and use a calculated column in a SQL Server query?
How can I create and use a calculated column in a SQL Server query?
Ravi Vishwakarma
12-Jul-2024Creating and using calculated columns in an SQL Server query allows you to generate values based on existing data in your table. These calculated columns can be used in
SELECT
statements or defined directly in the table schema.Here's how to create and use calculated columns in both ways:
1. Using Calculated Columns in a
SELECT
StatementYou can create calculated columns directly in your
SELECT
statement by using expressions or functions.Querying the Table
Now, let's query the
CollageStudents
table to see how the calculated columnAge
works:Explanation
Table Definition:
CollageStudents
table has columnsStudentID
,FirstName
,LastName
,DOB
,Address
.Age
is a calculated column using theAS
keyword and theDATEDIFF
function to calculate the difference in years betweenDOB
and the current date (GETDATE()
).Querying the Table:
SELECT
statement retrieves all columns includingAge
, which is computed dynamically based on theDOB
of each student.Additional Notes
Modify the Table and Create a new Computed Column
Let's see in table
Querying the Table
Now, let's query the
CollageStudents
table to see how the calculated columnAge
works:You can create a computed column with conditions.
Create
ParmanantAddress
whenIsSameAddress
value is true.Output
Read more
Explain the SQL Server backups and their types
Explain the SQL triggers and their uses
Define the PIVOT Table with examples in SQL server.
Differences between stored procedures and functions in SQL