Types of Select Statement - sql

This has been bothering me for quite some time but I do come across two ways of using select statement in SQL.
The first way is the obvious :
Select column_Name
from table_Name
And then there is a second one:
Select column_Name a
from table_Name
What is the difference in using the second one?

The second version is more properly written using as:
Select column_Name as a
This produces a result set with one column. The column is called a. Without the alias, the column would be called column_name.
Although the as is optional, I strongly recommend using it for column aliases.

Using an column alias comes handy when you want to change the table column name for display purpose, for an example think that you want to generate the excel sheet from your program that returns data set from sql server. You can concentrate only the excel generation part in your application [treat this is an common routine to generate multiple excels] and you can change your column names what ever you want using the mentioned method. Alias can be seen in below syntaxas
SELECT yourcolumnname abc
SELECT yourcolumnname [abc def]
SELECT yourcolumnname AS abc
SELECT yourcolumnname AS 'abc def'
SELECT yourcolumnname AS [abc def]

Related

How to select the same column from multiple table with almost same name in SQL?

I'd like to select a 2 column from lot of table.
Exemple
Table_2017-01
id name value
Table_2017-02
id name value
Table_2017-03
id name value
etc...
My Query would be
SELECT name, value
FROM Table_2017-01, Table_2017-02, Table_2017-03
But I'd like to know if something it's possible like
SELECT name, value FROM LIKE Table_%
I know this last query is not possible and it could be easier for me if a query exist for this problem as I can have a lot of table with just a part of the name different.
To select mutiple columns with the same name you have to the table as prefix like:
SELECT `Table_2017-01.name`, `Table_2017-02.name`, `Table_2017-03.name` FROM Table_2017-01,`Table_2017-02, Table_2017-03
If you want them in one Column, use Union.
(SELECT `Table_2017-01.name` from Table_2017-01)
Union
(SELECT `Table_2017-02.name` from Table_2017-02)
It depends on your database. Oracle f.e. has a data dictionary with all tables.
Because I know oracle better than others I use this for the example:
SELECT TABLE_NAME FROM ALL_TABLES WHERE TABLE_NAME LIKE 'Table_2017-%';
Now there are the following ways I sometimes use:
I build a list of selects and fire them into the database:
via Excel (not explained here)
via SQL
SELECT
'SELECT '''||TABLE_NAME||''' TABLE_NAME, NAME, VALUE FROM '||
TABLE_NAME
||' UNION '
FROM ALL_TABLES WHERE TABLE_NAME LIKE 'Table_2017-%';
Now you can copy the result to your database (dont forget to delete the last "UNION")
via program (python, Lazarus, c# .. whatever, same view is needed)
But pay attention: It is quick and dirty, the column names and types have to match.

How to get few column names among all columns in the one table with query in sql server 2008

select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='Submenu';
The above query gave all column names in Submenu table but I want only three column names of Submenu table.
Is there any way to get column names?
I assumed this is SQL Server, so the below queries might not work on other RDBMS's).
If your question is how to find only the column names you need (presuming you know in advance which ones those are), you would have to do something like this:
SELECT
COLUMN_NAME
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME='Submenu'
AND COLUMN_NAME IN ('Column1', 'Column2', 'Column3')
At this moment, you basically are requesting a list of any column within your table, without any restrictions whatsoever.
Alternatively, if you're looking only for the first three column names, this would work:
SELECT TOP 3
COLUMN_NAME
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME='Submenu'
ORDER BY
ORDERINAL_POSITION
In the latter case, you will have to determine how you want to sort the column names though (either by using something like ORDER BY COLUMN_NAME, in case you want them listed alphabetically, or ORDER BY ORDERINAL_POSITION in case you're trying to get them in the order they appear in the table).
If this is not what you meant, please elaborate on what you are trying to achieve.
SELECT TOP 3 COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Submenu';
As easy as that!

Mysql Query data filled check

I had created the table with 200 columns and i had inserted data
Now i need to check that specific 100 columns in one row are filled or not,how can we check this using mysql query .the primary key is defined .please help me out how to resolve this.
select * from tablename where column1 != null or column2 != null ......
That is a lot of columns so at the risk of being mysql server version specific you can use the information schema to get the column names and then write a SQL procedure or something in your chosen shell / language that iterates over them performing a test.
select distinct COLUMN_NAME as 'Field', IS_NULLABLE from information_schema.columns where TABLE_SCHEMA="YourDatabase" and TABLE_NAME="YourTableName" and TABLE_NAME not like "%view%" escape '!' ;
The example above will tell you the column name as "Field" and tell you if it can hold a NULL. Having the field name may give you a better way of automating a field name specific test.

Is it possible in SQL to return a first row that has attribute names and then values

I am wondering if there is a way to write the SQL so that it would return me a result as usual but now, on the first row that would return also the attribute names.
To explain what I mean:
say you have a table "test" which has 2 attributes "id" and "name":
id name
1 nik
2 tst
query:
SELECT * FROM test;
produces:
1 nik
2 tst
but what I want it to return is this:
id name
1 nik
2 tst
Is this possible?
edit: I am using PostreSQL
You cannot return the names and the actual column values in a single result unless you give up on the real datatypes (which is probably not what you want).
Your example mixes character data and numeric data in the id column and Postgres will (rightfully) refuse to return such a result set.
Edit:
I tested the "union" solution given e.g. by JNK and it fails (as expected) on Postgres, Oracle and SQL Server precisely because of the non-matching datatypes. MySQL follows it's usual habits of not throwing errors and simply converts everything to characters.
Extremely generic answer since you don't provide an RDBMS:
SELECT id, name FROM(
SELECT 'id' as 'id', 'name' as 'name', 1 as 'Rank'
UNION ALL
SELECT *, 2 as 'Rank' FROM test) as X
ORDER BY [RANK]
EDIT
Thanks to Martin for pointing out the need for the ORDER BY
Assuming you are on SQL Server, you can get the column names of a specific table by using this query:
select column_name 'Column Name', data_type 'Data Type'
from information_schema.columns
where table_name = 'putYourTableNameHere'
Then, you'll have to UNION your things together.
I agree with OMG Ponies above, the way to get this meta-data is usually from the interface you use.
for example the Perl DBI module has a method fetchrow_hashref where the columns of the returned row are returned as an associative array (hash) where the colnames are the keys.
print $ref->{'name'}; # would print nik or tst
Update:
I had forgotten to add that some of these interface layers have a method that return s the col names and you could use that instead of adding the names into your result set.
The DBI method you'd use would be $sth->{NAMES}->[0] would return the first column name.
Depending on your tools / technique, but here are a couple:
If you're using SSMS (Sql-Server), and want to copy/paste your results with the column headers:
Query Window -->
R-Click
Results -->
Grid or Text -->
Check-mark the 'Include column headers in the result set' option
If you're using Sql-Server, you can query meta-tables (sys.columns, etc.)
If you're using an ASP.NET databound control, you usually have access to methods or properties (sqldatareader.getname(i), etc.)
Anyway -- just depends on the layer you're trying to get the names from -- if these above don't help, then edit / re-tag your question so we can focus on whatever tool you're wanting to use to do this.
EDIT for PostgresSQL
If you're using PostgresSQL, you can query meta-tables (information_schema.columns, etc.)

SQL set column names from another query

I'm am using MS Reporting Services to graph some data from an Oracle database. I want to name the columns in my select statement with values from another select statement. Is this possible?
Like instead of
Select Column1 As 'Test' From Table1
could I do something like
Select Column1 As (Select column2 from Table2 where Value = 1) From Table1
?
I would think you'd have to query out separately, then form the query dynamically. Interested to see if there is a different answer.
My PL/SQL's a little rusty, so what follows is more pseudocode than compilable & tested code. And this is completely off the top of my head. But if you know the specific ordinal location of the column in the table, you may try this:
columnName varchar2(50) :=
Select column_name
From all_tab_columns c
Where lower(table_name) = '<% Your Table2 Name %>' And
column_id = 9 -- The appropriate ordinal
Order By column_id;
Select Column1 As columnName From Table1;
There may be more column values drawn from "all_tab_columns" that'll help you as well. Take a look around and see.
I hope this helps.
You can query all needed column names into separate report dataset, create hidden multivalue report parameter vColumns, set dataset with columns as a parameter default values, and use it as a string array:
Parameters!vColumns(0).Value - will be the first column etc. So you can use them as a query parameters.
See Lesson 4: Adding a Multivalue Parameter