Oracle | Select * besides <column_name> - sql

How to select all columns from the table besides two or three?
I work with a lot of tables with more than 50 columns, so I can not list of column name...
I hope that it works, but it doesn't
SELECT(
SELECT column_name FROM all_tab_columns
WHERE table_name = <table_name>
AND column_name NOT IT (<columns_name>)
)
from <table_name>;
Could you help me please?

You can construct the query dynamically through a pl/sql procedure and then run it using "execute immediate"

I found some workaround (because PL/SQL to hard for simple select):
CREAT TABLE <tmp> AS SELECT * FROM <table_name>;
ALTER TALBE <tmp> DROP COLUMN <column_name>;
SELECT * FROM <tmp>;
DROP TALBE <tmp>;
It will be useful to simple query...
But for development PL/SQL will be more useful (universally, optimized for server, etc).

Related

How to truncate all tables that start with the same prefix - Postgresql

With the code:
SELECT *
FROM information_schema.tables
WHERE table_name LIKE 'prefix%';
I can obtain all the tables that I want to truncate, but how can I execute the TRUNCATE TABLE function for the results of that SELECT statement?
You cannot execute TRUNCATE from a SELECT statement. You could do something like
SELECT concat('TRUNCATE TABLE ',table_catalog,'.',table_schema,'.',table_name)
FROM information_schema.tables
WHERE table_name LIKE 'prefix%';
which would return a TRUNCATE statement for each table with the prefix. You could even look into using a stored procedure to execute each single row.

How to show column names in a row

I want to write a SELECT statement to show the list of fields in the table.
COLUMN
column_1
column_2
column_3
You can use the information schema tables, particularly columns:
select column_name
from INFORMATION_SCHEMA.COLUMNS
where table_schema = #schema_name and table_name = #table_name;
Note that this metadata is stored per database. So if you want a table in another database, you need three part naming:
select column_name
from <database>.INFORMATION_SCHEMA.COLUMNS
where table_schema = #schema_name and table_name = #table_name;
Yet one more option: This will return results on any table,ad-hoc query or even a stored procedure.
(using spt_values as a demonstration)
Example
Select column_ordinal
,name
,system_type_name
From sys.dm_exec_describe_first_result_set('Select * From master..spt_values',null,null )
Returns
In SQL Server you can also highlight the tablename in a query then press ALT+F1 to show the highlighted table info.

Finding number of columns returned by a query

How can I get the number of columns returned by an SQL query using SQL Server?
For example, if I have a query like following:
SELECT *
FROM A1, A2
It should return the total number of columns in table A1 + total number of columns in table A2. But the query might be more complicated.
Here is one method:
select top 0
into _MYLOCALTEMPTABLE
from (your query here) t
select count(*)
from Information_Schema.Columns c
where table_name = '_MYLOCALTEMPTABLE'
You can do something similar by creating a view.
You didn't specify your SQL Server version but I'm assuming it's not 2012. However, future readers of this question might be on 2012+ so I'm posting this answer for them.
SQL Server 2012 provides a set of procedures to provide more meta-data about queries and parameters. In this case, the stored procedure sp_describe_first_result_set will provide a handy tabular form.
There is also a DMO function, sys.dm_exec_describe_first_result_set, to provide similar content which is what you'd want to use in your example
DECLARE
-- Your query goes here
#query nvarchar(4000) = N'SELECT * FROM mdm.tblStgBatch AS TSB';
-- Tabular results
EXECUTE sys.sp_describe_first_result_set #tsql = #query;
-- Simple column count
SELECT
COUNT(1) AS column_count
FROM
sys.dm_exec_describe_first_result_set(#query, NULL, 0);
The new metadata discovery options are replacing FMTONLY which is how one would solve this problem prior to 2012. My TSQL chops are apparently not strong enough to do anything useful with it and instead I'd have to bail out to a .NET language to work with the output of FMTONLY.
SET FMTONLY ON;
SELECT *
FROM A1, A2;
SET FMTONLY OFF;
Try this;
--Insert into a temp table (this could be any query)
SELECT *
INTO #temp
FROM [yourTable]
--Select from temp table
SELECT * FROM #temp
--List of columns
SELECT COUNT(name) NumOfColumns FROM tempdb.sys.columns WHERE object_id =
object_id('tempdb..#temp');
--drop temp table
DROP TABLE #temp
Ugly I know:
SELECT COUNT(*) +
(
SELECT COUNT(*)
FROM information_schema.columns
WHERE table_name = 'A1'
)
FROM information_schema.columns
WHERE table_name = 'A2'

SQL - INFORMATION_SCHEMA for All Databases On Server

INFORMATION_SCHEMA.TABLES or INFORMATION_SCHEMA.COLUMNS work for only specified databases.
Is it possible to query table metadata for ALL databases on server by using INFORMATION_SCHEMA?
You can do this only by using dynamic query for database iteration. One way is using ms_ForEachDB stored procedure, second is querying sys.databases dynamic view.
Expanding Dalex's answer into code.
--Make sure you have a global temporary table to use. Double dots are shorthand for .dbo.
IF OBJECT_ID('tempdb..##test') IS NOT NULL DROP TABLE ##test
--Create the table definition the easy way.
SELECT * INTO ##test
FROM ???.INFORMATION_SCHEMA.TABLES --The ??? will be whatever the name of your first database is.
DELETE FROM ##test
--Add all the data.
EXEC sp_MSforeachdb 'USE ? INSERT INTO ##test SELECT * FROM INFORMATION_SCHEMA.TABLES'
--View all the data.
SELECT * FROM ##test
--Clean up.
DROP TABLE ##test
Modified Dustin's code (from Dalex's suggestion) to accommodate database names with spaces and eliminate common system tables from results.
--Make sure you have a global temporary table to use. Double dots are shorthand for .dbo.
IF OBJECT_ID('tempdb..##test') IS NOT NULL DROP TABLE ##test
--Create the table definition the easy way.
SELECT top 1 * INTO ##test
FROM INFORMATION_SCHEMA.TABLES
DELETE FROM ##test
--Add all the data.
EXEC sp_MSforeachdb 'USE [?] INSERT INTO ##test SELECT * FROM INFORMATION_SCHEMA.TABLES'
--View all the data.
SELECT * FROM ##test
WHERE TABLE_CATALOG NOT IN ('master','tempdb', 'msdb')
ORDER BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME
--Clean up.
DROP TABLE ##test
You can use this:
SELECT TABLE_SCHEMA
FROM information_schema.tables
group by tables.TABLE_SCHEMA
This isn't the answer to the question but this text adds context ... and text is likely to be useful to someone to gain understanding.
It is possible and often required to add a use clause to select which database is being referenced above the select clause ..
e.g.
use CaseData
SELECT *
FROM information_schema.columns
--WHERE
--TABLE_CATALOG = 'CaseData'
--and TABLE_SCHEMA ='Clinical'
--and
--TABLE_NAME = 'SAASCaseData_NewFieldsOct2018'
SELECT DISTINCT `TABLE_SCHEMA` FROM `information_schema`.`TABLES`;

What is the SQL command to return the field names of a table?

Say I have a table called myTable. What is the SQL command to return all of the field names of this table? If the answer is database specific then I need SQL Server right now but would be interested in seeing the solution for other database systems as well.
MySQL 3 and 4 (and 5):
desc tablename
which is an alias for
show fields from tablename
SQL Server (from 2000) and MySQL 5:
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'tablename'
Completing the answer: like people below have said, in SQL Server you can also use the stored procedure sp_help
exec sp_help 'tablename'
SQL-92 standard defines INFORMATION_SCHEMA which conforming rdbms's like MS SQL Server support. The following works for MS SQL Server 2000/2005/2008 and MySql 5 and above
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'myTable'
MS SQl Server Specific:
exec sp_help 'myTable'
This solution returns several result sets within which is the information you desire, where as the former gives you exactly what you want.
Also just for completeness you can query the sys tables directly. This is not recommended as the schema can change between versions of SQL Server and INFORMATION_SCHEMA is a layer of abstraction above these tables. But here it is anyway for SQL Server 2000
select [name] from dbo.syscolumns where id = object_id(N'[dbo].[myTable]')
You can use the provided system views to do this:
eg
select * from INFORMATION_SCHEMA.COLUMNS
where table_name = '[table name]'
alternatively, you can use the system proc sp_help
eg
sp_help '[table name]'
PostgreSQL understands the
select column_name from information_schema.columns where table_name = 'myTable'
syntax. If you're working in the psql shell, you can also use
\d myTable
for a description (columns, and their datatypes and constraints)
For those looking for an answer in Oracle:
SELECT column_name FROM user_tab_columns WHERE table_name = 'TABLENAME'
Just for completeness, since MySQL and Postgres have already been mentioned: With SQLite, use "pragma table_info()"
sqlite> pragma table_info('table_name');
cid name type notnull dflt_value pk
---------- ---------- ---------- ---------- ---------- ----------
0 id integer 99 1
1 name 0 0
This is also MySQL Specific:
show fields from [tablename];
this doesnt just show the table names but it also pulls out all the info about the fields.
In Sybase SQL Anywhere, the columns and table information are stored separately, so you need a join:
select c.column_name from systabcol c
key join systab t on t.table_id=c.table_id
where t.table_name='tablename'
MySQL is the same:
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'
If you just want the column names, then
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'
On MS SQL Server, for more information on the table such as the types of the columns, use
sp_help 'tablename'
For IBM DB2 (will double check this on Monday to be sure.)
SELECT TABNAME,COLNAME from SYSCAT.COLUMNS where TABNAME='MYTABLE'
MySQL
describe tablename
select COLUMN_NAME1,COLUMN_NAME2 from SCHEMA_NAME.TABLE_NAME
where TABLE_NAME.COLUMN_NAME = 'COLUMN_NAME1';