Sunday, March 1, 2015

SQL Server Brain Basher of the Week #001

I have been doing a series of session called SQL Server Brain Basher in SQL Server Sri Lanka User Group (https://www.facebook.com/groups/sqlserveruniverse/) that explains some tricky questions which we cannot answer immediately, unless you have excelled the area related. Thought to have at least one I used before (and planning to use in future) as a blog post in every week, hence, here is the first one which is fairly an easy one.

What would be result of following query?

SELECT 100, 200 '300';

If you are familiar with adding aliases to columns, you can immediately answer. This query returns two columns; first column with value of 100 without a column name, and second with a value of 200 with a column name of 300.



Column alias can be used to relabel column if required. This is really useful if you need to have a different name for the column without having the one coming from the table and name calculated columns. There are multiple ways of adding column aliases, here are some of the ways;

-- Column alias using AS keyword
SELECT 100 AS Column1, 200 AS 'Column2';

-- Column alias with an Equal sign
SELECT Column1 = 100, 'Column2' = 200;

-- Column alias following column name
SELECT 100 Column1, 200 'Column2';

No comments:

Post a Comment