PostgreSQL query fails over PGNP provider for SQL Server - sql-server

This query is failing in SQL Server over the PGNP provider:
SELECT 1 AS x
FROM pg_catalog.pg_attribute a
LEFT OUTER JOIN pg_catalog.pg_index i
ON (i.indrelid = a.attrelid
AND a.attnum = i.indkey[a.attnum-1])
This is the error message returned:
The OLE DB provider "PGNP" for linked server "XXX" indicates that either the object has no columns or the current user does not have permissions on that object.
If I run this query directly on the PostgreSQL server with pgAdmin, it returns results. Furthermore, if I remove the clause "a.attnum = i.indkey[a.attnum-1]", the query works over the PGNP provider. (I need this clause in my original query to identify which of a table's columns is the primary key.)
What is the issue, and how do I resolve it?
For the record, this is the complete query that I am executing, from which the query above was excerpted:
SELECT c.relname as table_name, a.attname as column_name
, t.typname as type_name
, i.indisunique AS is_unique_key
, i.indisprimary AS is_primary_key
, CASE t.typname
WHEN 'bpchar' THEN 'char('+CAST(atttypmod - 4 AS VARCHAR)+')'
WHEN 'numeric' THEN 'numeric('+CAST((atttypmod - 4)/65536 AS VARCHAR)
+','+CAST((atttypmod - 4)%65536 AS VARCHAR)
+')'
WHEN 'text' THEN 'varchar(max)'
WHEN 'varchar' THEN 'varchar('+CASE atttypmod WHEN -1 THEN 'max' ELSE CAST(atttypmod-4 AS VARCHAR) END+')'
ELSE t.typname
END as type_name_1
, CAST(CASE atttypmod WHEN -1 THEN NULL ELSE atttypmod - 4 END AS INT4) AS type_precision_scale
FROM pg_catalog.pg_attribute a
JOIN pg_catalog.pg_class c on ( a.attrelid = c.oid)
JOIN pg_catalog.pg_namespace n on (c.relnamespace = n.oid)
JOIN pg_catalog.pg_type t on (a.atttypid = t.oid)
LEFT OUTER JOIN pg_catalog.pg_index i
ON (c.oid = i.indrelid
AND i.indrelid = a.attrelid
AND a.attnum = i.indkey[a.attnum-1])
WHERE c.relkind = 'r' and a.attnum > 0
AND n.nspname = 'public'

Related

Microsoft SQL Server 2016 - SSMS, cannot expand tables for a database

There are many databases on my server, recently of them one (which I am the dbo on) has become inaccessible through SSMS. When I expand the tables node in 'object explorer' for this database I get the following error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. (.Net SqlClient Data Provider)
However, I can execute selects successfully on that database and other users are not having this problem.
I have;
Checked my login for incorrect settings.
Checked my user for incorrect settings.
Restarted the SQL Server Engine.
Repaired SSMS using the installer utility.
Would very much appreciate your input, I am stumped (this has never happened before).
EDIT: After tracing using SQL Profiler and causing this event I extracted the query and ran it in a SSMS session window. The returned results are from the wrong database.
EDIT: Further to this, I ran dbcc checkdb(databasename) and no errors were returned, I then did the same for master, no errors were returned.
EDIT: The query being executed when I expand the table folder:
exec sp_executesql N'SELECT
tbl.name AS [Name],
SCHEMA_NAME(tbl.schema_id) AS [Schema],
''Server[#Name='' + quotename(CAST(
serverproperty(N''Servername'')
AS sysname),'''''''') + '']'' + ''/Database[#Name='' + quotename(db_name(),'''''''') + '']'' + ''/Table[#Name='' + quotename(tbl.name,'''''''') + '' and #Schema='' + quotename(SCHEMA_NAME(tbl.schema_id),'''''''') + '']'' AS [Urn],
tbl.create_date AS [CreateDate],
CAST(tbl.is_memory_optimized AS bit) AS [IsMemoryOptimized],
CAST(CASE idx.type WHEN 5 THEN 1 ELSE 0 END AS bit) AS [HasClusteredColumnStoreIndex],
CAST(tbl.is_remote_data_archive_enabled AS bit) AS [RemoteDataArchiveEnabled],
tbl.temporal_type AS [TemporalType],
CAST(CASE WHEN ''PS''=dsidx.type THEN 1 ELSE 0 END AS bit) AS [IsPartitioned],
CAST(
ISNULL((SELECT 1 from sys.all_columns
WHERE object_id = tbl.object_id
AND is_sparse = 1), 0)
AS bit) AS [HasSparseColumn]
FROM
sys.tables AS tbl
LEFT OUTER JOIN sys.periods as periods ON periods.object_id = tbl.object_id
LEFT OUTER JOIN sys.tables as historyTable ON historyTable.object_id = tbl.history_table_id
INNER JOIN sys.indexes AS idx ON
idx.object_id = tbl.object_id and (idx.index_id < #_msparam_0 or (tbl.is_memory_optimized = 1 and idx.index_id = (select min(index_id) from sys.indexes where object_id = tbl.object_id)))
LEFT OUTER JOIN sys.data_spaces AS dsidx ON dsidx.data_space_id = idx.data_space_id
WHERE
(CAST(
case
when tbl.is_ms_shipped = 1 then 1
when (
select
major_id
from
sys.extended_properties
where
major_id = tbl.object_id and
minor_id = 0 and
class = 1 and
name = N''microsoft_database_tools_support'')
is not null then 1
else 0
end
AS bit)=#_msparam_1 and tbl.is_filetable=#_msparam_2 and CAST(tbl.is_memory_optimized AS bit)=#_msparam_3 and tbl.temporal_type=#_msparam_4 and CAST(tbl.is_external AS bit)=#_msparam_5)
ORDER BY
[Schema] ASC,[Name] ASC',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000),#_msparam_2 nvarchar(4000),#_msparam_3 nvarchar(4000),#_msparam_4 nvarchar(4000),#_msparam_5 nvarchar(4000)',#_msparam_0=N'2',#_msparam_1=N'0',#_msparam_2=N'0',#_msparam_3=N'0',#_msparam_4=N'0',#_msparam_5=N'0'
EDIT: As a work-around, I reinstalled the SSMS 2014. I can access my tables through here.
There is nothing wrong with your database, it's a known issue with SSMS 16.5.2 and has been reported to product team. Please revert back to previous release of SSMS if it causes too much trouble. For more information, please refer to this thread.
Apparently this only happens when the database have table(s) with more than one sparse column.
Try it's
SELECT
NAME
FROM [base].SYS.triggerS
WHERE parent_class_desc = 'DATABASE'
Take the trigger name and perform the procedure below
DISABLE TRIGGER [dbo].[trigger_name]

SQL OpenQuery linked server Oracle DateAdd

I am writing a sql query to pull some data from one of our linked oracle servers.
The only problem with this query is with the two date add rows (with them removed the query runs) but i need their data.
I receive the below error:
OLE DB provider "MSDAORA" for linked server "MAGINUS" returned message "ORA-00904: "DATEADD": invalid identifier
Could anyone prescribe a syntax for these?
Thanks in advance
Will
DECLARE #TSQL VARCHAR(8000)
,#CUSTOMER_ACCOUNT VARCHAR(20)
SELECT #TSQL1 = '
SELECT * FROM OPENQUERY(MAGINUS,''
SELECT
CM.CUSTOMER_ACCOUNT AS "CustomerAccount"
,CM.CONTACT_NAME AS "ContactName"
,CM.MEMBERSHIP_NUMBER AS "MembershipNumber"
,P.LONG_DESCRIPTION_1 AS "ProductDescription"
,DATEADD(SECOND, CM.MEMBERSHIP_START_DATE, "19700101") AS "MembershipStartDate"
,DATEADD(SECOND, CM.MEMBERSHIP_EXPIRY_DATE, "19700101") AS "MemberhrshipEndDate"
,SH.ORDER_VALUE AS "Price Paid"
FROM MAGINUS.CUSTOMER_MEMBERSHIP CM
INNER JOIN MAGINUS.PRODUCT P
ON CM.PRODUCT_CODE = P.PRODUCT_CODE
INNER JOIN MAGINUS.SALES_HEADER SH
ON CM.CUSTOMER_ACCOUNT = SH.CUSTOMER_ACCOUNT
AND CM.SALES_DOCUMENT_NUM = SH.SALES_DOCUMENT_NUM
WHERE CM.CUSTOMER_ACCOUNT = ''''' + #CUSTOMER_ACCOUNT + ''''''')'
EXEC (#TSQL1)
Dateadd is valid for SQL Server, but the query you send to the Oracle db needs to be valid for oracle. So you need to move the dateadd outside of the openquery, and into the SQL Server bit:
DECLARE #TSQL VARCHAR(8000)
,#CUSTOMER_ACCOUNT VARCHAR(20)
SELECT #TSQL1 = '
SELECT CustomerAccount
,ContactName
,MembershipNumber
,ProductDescription
,DATEADD(SECOND, MembershipStartDate, ''19700101'') AS MembershipStartDate
,DATEADD(SECOND, MemberhrshipEndDate, ''19700101'') AS MemberhrshipEndDate
,Price Paid
FROM OPENQUERY(MAGINUS,''
SELECT
CM.CUSTOMER_ACCOUNT AS "CustomerAccount"
,CM.CONTACT_NAME AS "ContactName"
,CM.MEMBERSHIP_NUMBER AS "MembershipNumber"
,P.LONG_DESCRIPTION_1 AS "ProductDescription"
,CM.MEMBERSHIP_START_DATE AS "MembershipStartDate"
,CM.MEMBERSHIP_EXPIRY_DATE AS "MemberhrshipEndDate"
,SH.ORDER_VALUE AS "Price Paid"
FROM MAGINUS.CUSTOMER_MEMBERSHIP CM
INNER JOIN MAGINUS.PRODUCT P
ON CM.PRODUCT_CODE = P.PRODUCT_CODE
INNER JOIN MAGINUS.SALES_HEADER SH
ON CM.CUSTOMER_ACCOUNT = SH.CUSTOMER_ACCOUNT
AND CM.SALES_DOCUMENT_NUM = SH.SALES_DOCUMENT_NUM
WHERE CM.CUSTOMER_ACCOUNT = ''''' + #CUSTOMER_ACCOUNT + ''''''')'
EXEC (#TSQL1)

SQL Profiler shows high duration on unknown TextData

I have been profiling my web app's connection to the sql server for the last 24 hours.
Out of 1.226.709 batchcompleted I have 36 with the duration over 0.1 second.
Out of the 36 I have 4 unknown statements. And here I hoped some of you could help me tell what these are about and from where they come?! :)
The first concerns me a bit, cause it have a duration over 1 second.
(The trace were saved to a table in the database, which is why all the durations are in microseconds)
TextData: SELECT 'Server[#Name=' + quotename(CAST( serverproperty(N'Servername') AS sysname),'''') + ']' + '/Collation[#Name=' + quotename(cl.name,'''') + ']' AS [Urn], cl.name AS [Name], CAST(COLLATIONPROPERTY(name, 'CodePage') AS int) AS [CodePage], CAST(COLLATIONPROPERTY(name, 'LCID') AS int) AS [LocaleID], CAST(COLLATIONPROPERTY(name, 'ComparisonStyle') AS int) AS [ComparisonStyle], cl.description AS [Description], CAST(COLLATIONPROPERTY(name, 'Version') AS int) AS [CollationVersion] FROM sys.fn_helpcollations() cl ORDER BY [Name] ASC
CPU: 93
Reads: 0
Writes: 0
Duration: 1013301
ApplicationName Microsoft SQL Server Management Studio - Transact-SQL IntelliSense
TextData: select IndA.name, IndA.index_id, IndA.fill_factor, IndA.is_padded, IndA.is_disabled,IndA.is_hypothetical, IndA.allow_row_locks, IndA.allow_page_locks,IndA.spatial_index_type, IndB.bounding_box_xmin, IndB.bounding_box_ymin, IndB.bounding_box_xmax, IndB.bounding_box_ymax, IndB.level_1_grid, IndB.level_2_grid, IndB.level_3_grid, IndB.level_4_grid, IndB.cells_per_object, ind_col.index_column_id, col.name as column_nName, ind_col.key_ordinal, ind_col.is_descending_key, ind_col.column_id, st.no_recompute from (sys.spatial_indexes IndA left outer join sys.spatial_index_tessellations IndB on IndB.object_id = IndA.object_id and IndB.index_id = IndA.index_id) inner join(sys.internal_tables IntT inner join sys.stats st on st.object_id = IntT.object_id and st.stats_id = 1) on IntT.parent_id = IndA.object_id and IntT.parent_minor_id = IndA.index_id inner join sys.index_columns ind_col on ind_col.object_id = IndA.object_id and ind_col.index_id = IndA.index_id inner join sys.columns col on col.object_id = ind_col.object_id and col.column_id = ind_col.column_id where IndA.object_id = object_id(N'dbo.rapports') order by IndA.index_id, ind_col.key_ordinal
CPU: 109
Reads: 216
Writes: 0
Duration: 148322
ApplicationName Microsoft SQL Server Management Studio
TextData: select col.name, col.column_id, st.name as DT_name, schema_name(st.schema_id) as DT_schema, col.max_length, col.precision, col.scale, bt.name as BT_name, col.collation_name, col.is_nullable, col.is_ansi_padded, col.is_rowguidcol, col.is_identity, case when(idc.column_id is null) then null else CONVERT(nvarchar(40), idc.seed_value) end, case when(idc.column_id is null) then null else CONVERT(nvarchar(40), idc.increment_value) end, CONVERT(bit, case when(cmc.column_id is null) then 0 else 1 end) as is_computed, convert(bit, ColumnProperty(col.object_id, col.name, N'IsIdNotForRepl')) as IsIdNotForRepl, col.is_replicated, col.is_non_sql_subscribed, col.is_merge_published, col.is_dts_replicated, col.rule_object_id, robj.name as Rul_name, schema_name(robj.schema_id) as Rul_schema, col.default_object_id, OBJECTPROPERTY(col.default_object_id, N'IsDefaultCnst') as is_defcnst, dobj.name as def_name, schema_name(dobj.schema_id) as def_schema, CONVERT(bit, case when (ftc.column_id is null) then 0 else 1 end) as is_FullTextCol, col_name(col.object_id, ftc.type_column_id) FT_type_column, ftc.language_id as FT_language_id, case when(cmc.column_id is null) then null else cmc.definition end as formular, case when(cmc.column_id is null) then null else cmc.is_persisted end as is_persisted, defCst.definition, COLUMNPROPERTY(col.object_id, col.name, 'IsDeterministic') as IsDeterministic, xmlcoll.name as xmlSchema_name, schema_name(xmlcoll.schema_id) as xmlSchema_schema, col.is_xml_document, col.is_sparse, col.is_column_set from sys.columns col left outer join sys.types st on st.user_type_id = col.user_type_id left outer join sys.types bt on bt.user_type_id = col.system_type_id left outer join sys.objects robj on robj.object_id = col.rule_object_id and robj.type = 'R' left outer join sys.objects dobj on dobj.object_id = col.default_object_id and dobj.type = 'D' left outer join sys.default_constraints defCst on defCst.parent_object_id = col.object_id and defCst.parent_column_id = col.column_id left outer join sys.identity_columns idc on idc.object_id = col.object_id and idc.column_id = col.column_id left outer join sys.computed_columns cmc on cmc.object_id = col.object_id and cmc.column_id = col.column_id left outer join sys.fulltext_index_columns ftc on ftc.object_id = col.object_id and ftc.column_id = col.column_id left outer join sys.xml_schema_collections xmlcoll on xmlcoll.xml_Collection_id = col.xml_Collection_id where col.object_id = object_id(N'dbo.rapports') order by col.column_id
CPU: 215
Reads: 6895
Writes: 0
Duration: 142054
ApplicationName Microsoft SQL Server Management Studio
TextData: SELECT dtb.name AS [Name], dtb.database_id AS [ID], CAST(case when dtb.name in ('master','model','msdb','tempdb') then 1 else dtb.is_distributor end AS bit) AS [IsSystemObject], CAST(has_dbaccess(dtb.name) AS bit) AS [IsAccessible], dtb.collation_name AS [Collation], dtb.name AS [DatabaseName2] FROM master.sys.databases AS dtb ORDER BY [Name] ASC
CPU: 15
Reads: 324
Writes: 0
Duration: 111258
ApplicationName Microsoft SQL Server Management Studio - Transact-SQL IntelliSense
Extra info!
I run a script every night to backup the database. I have no idea if the 4 statements have nothing to do with that. The statement for the backup is the following:
TextData: declare #DBName varchar(200) declare #Filename varchar(1000) declare #Description varchar(1000) DECLARE AllDatabases CURSOR FOR SELECT name AS Name FROM MASTER.DBO.SYSDATABASES WHERE [NAME] NOT IN('MODEL', 'tempdb') OPEN AllDatabases FETCH NEXT FROM AllDatabases INTO #DBName WHILE ##FETCH_STATUS = 0 BEGIN print '' print '' print 'Backing up database ' + #DBName -- Backup the database set #Filename = 'D:\backup\' + convert(varchar, getDate(), 112) + ' - ' + #DBName + '.bak' set #Description = 'Full backup of database ' + #Filename BACKUP DATABASE #DBName TO DISK = #Filename WITH INIT , NOUNLOAD , NAME = #Description, NOSKIP , STATS = 10, NOFORMAT FETCH NEXT FROM AllDatabases INTO #DBName END CLOSE AllDatabases DEALLOCATE AllDatabases
CPU: 219
Reads: 2569
Writes: 83
Duration: 4478260
Oh yeah and... I'm not used to profiling my SQL Server. Are there any tips you can give? :) I have of course been googling the topic.
After adding the ApplicationName column you can see that the queries are being run by SSMS to gather metadata about the database. SSMS needs all sorts of metadata to display databases, objects, logins and so on (you can see the reference to Intellisense too), so it's completely normal to see it querying the server. Unless you have a performance problem of some kind that you can directly link to these queries from SSMS, I would forget about them.
This same query is also responsible for hangs of SMSS when changig from one server to another in object explorer. Just kill the process running this query and on goes the show.

SQL Server SP, Function, View source line counter

Is there any utility availble to count the total lines of user created Stored Procedure, Function, Views in a Database?
For SQL Server 2005 and 2008.
This includes all code including blank lines and trailing blank lines, but not the last line (no CRLF). So it's averages out... but it would always be an approximation anyway.
WITH CRLF AS
(
SELECT
CHARINDEX('
', definition) AS CRLF,
SM.[object_ID]
FROM
sys.sql_modules SM
WHERE
OBJECT_NAME([object_ID]) not in ('fn_diagramobjects', 'sp_alterdiagram', 'sp_creatediagram', 'sp_dropdiagram', 'sp_helpdiagramdefinition', 'sp_helpdiagrams', 'sp_renamediagram', 'sp_upgraddiagrams', 'sysdiagrams')
UNION ALL
SELECT
CHARINDEX('
', definition, C.CRLF + 2),
SM.[object_ID]
FROM
sys.sql_modules SM
JOIN
CRLF C ON SM.[object_ID] = C.[object_ID]
WHERE
CHARINDEX('
', definition, C.CRLF + 2) > C.CRLF
)
SELECT
COUNT(*)
FROM
CRLF
OPTION
(MAXRECURSION 0)
Edit:
You may need OBJECTPROPERTY(SM.[object_ID], 'IsMSShipped') = 0 or explicitly exclusions for diagram code etc
Edit 2:
From other solution in otehr answer, corrected to not give "-1" for check constraints and apply same filters/types
select t.sp_name, sum(t.lines_of_code) as lines_ofcode, t.type_desc
from
(
select o.name as sp_name,
(len(c.text) - len(replace(c.text, char(13), ''))) as lines_of_code,
case when o.xtype = 'P' then 'Stored Procedure'
when o.xtype in ('FN', 'IF', 'TF') then 'Function'
end as type_desc
from sysobjects o
inner join syscomments c
on c.id = o.id
where --o.xtype in ('V', 'P', 'FN', 'IF', 'TF', 'TR')
--and
o.category = 0
AND
o.name not in ('fn_diagramobjects', 'sp_alterdiagram', 'sp_creatediagram', 'sp_dropdiagram', 'sp_helpdiagramdefinition', 'sp_helpdiagrams', 'sp_renamediagram', 'sp_upgraddiagrams', 'sysdiagrams')
) t
group by t.sp_name, t.type_desc
order by 1
COMPUTE SUM (sum(t.lines_of_code))
They all give the same results here on several databases. eg 4607 for a SQL Server 2005 SP2 ReportServer database...
Not that I know of, but you could look through the stuff in sysobjects and execute sp_helptext on each proc and view and count the newlines.
If you want a non CTE based solution you could do something like this:
select sum(newlines) from
(
select newlines = (datalength(definition) - datalength(replace(definition, '
', ' '))) / 2 from sys.sql_modules
) as a

PostgreSQL "DESCRIBE TABLE"

How do you perform the equivalent of Oracle's DESCRIBE TABLE in PostgreSQL with psql command?
Try this (in the psql command-line tool):
\d+ tablename
See the manual for more info.
In addition to the PostgreSQL way (\d 'something' or \dt 'table' or \ds 'sequence' and so on)
The SQL standard way, as shown here:
select column_name, data_type, character_maximum_length, column_default, is_nullable
from INFORMATION_SCHEMA.COLUMNS where table_name = '<name of table>';
It's supported by many db engines.
If you want to obtain it from query instead of psql, you can query the catalog schema. Here's a complex query that does that:
SELECT
f.attnum AS number,
f.attname AS name,
f.attnum,
f.attnotnull AS notnull,
pg_catalog.format_type(f.atttypid,f.atttypmod) AS type,
CASE
WHEN p.contype = 'p' THEN 't'
ELSE 'f'
END AS primarykey,
CASE
WHEN p.contype = 'u' THEN 't'
ELSE 'f'
END AS uniquekey,
CASE
WHEN p.contype = 'f' THEN g.relname
END AS foreignkey,
CASE
WHEN p.contype = 'f' THEN p.confkey
END AS foreignkey_fieldnum,
CASE
WHEN p.contype = 'f' THEN g.relname
END AS foreignkey,
CASE
WHEN p.contype = 'f' THEN p.conkey
END AS foreignkey_connnum,
CASE
WHEN f.atthasdef = 't' THEN d.adsrc
END AS default
FROM pg_attribute f
JOIN pg_class c ON c.oid = f.attrelid
JOIN pg_type t ON t.oid = f.atttypid
LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)
LEFT JOIN pg_class AS g ON p.confrelid = g.oid
WHERE c.relkind = 'r'::char
AND n.nspname = '%s' -- Replace with Schema name
AND c.relname = '%s' -- Replace with table name
AND f.attnum > 0 ORDER BY number
;
It's pretty complex but it does show you the power and flexibility of the PostgreSQL system catalog and should get you on your way to pg_catalog mastery ;-). Be sure to change out the %s's in the query. The first is Schema and the second is the table name.
You can do that with a psql slash command:
\d myTable describe table
It also works for other objects:
\d myView describe view
\d myIndex describe index
\d mySequence describe sequence
Source: faqs.org
The psql equivalent of DESCRIBE TABLE is \d table.
See the psql portion of the PostgreSQL manual for more details.
This should be the solution:
SELECT * FROM information_schema.columns
WHERE table_schema = 'your_schema'
AND table_name = 'your_table'
You may do a \d *search pattern * with asterisks to find tables that match the search pattern you're interested in.
In addition to the command line \d+ <table_name> you already found, you could also use the information-schema to look up the column data, using info_schema.columns
SELECT *
FROM info_schema.columns
WHERE table_schema = 'your_schema'
AND table_name = 'your_table'
Use the following SQL statement
SELECT DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
AND COLUMN_NAME = 'col_name'
If you replace tbl_name and col_name, it displays data type of the particular coloumn that you looking for.
You can use this :
SELECT attname
FROM pg_attribute,pg_class
WHERE attrelid=pg_class.oid
AND relname='TableName'
AND attstattarget <>0;
In MySQL , DESCRIBE table_name
In PostgreSQL , \d table_name
Or , you can use this long command:
SELECT
a.attname AS Field,
t.typname || '(' || a.atttypmod || ')' AS Type,
CASE WHEN a.attnotnull = 't' THEN 'YES' ELSE 'NO' END AS Null,
CASE WHEN r.contype = 'p' THEN 'PRI' ELSE '' END AS Key,
(SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid), '\'(.*)\'')
FROM
pg_catalog.pg_attrdef d
WHERE
d.adrelid = a.attrelid
AND d.adnum = a.attnum
AND a.atthasdef) AS Default,
'' as Extras
FROM
pg_class c
JOIN pg_attribute a ON a.attrelid = c.oid
JOIN pg_type t ON a.atttypid = t.oid
LEFT JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid
AND r.conname = a.attname
WHERE
c.relname = 'tablename'
AND a.attnum > 0
ORDER BY a.attnum
This variation of the query (as explained in other answers) worked for me.
SELECT
COLUMN_NAME
FROM
information_schema.COLUMNS
WHERE
TABLE_NAME = 'city';
It's described here in details:
http://www.postgresqltutorial.com/postgresql-describe-table/
To improve on the other answer's SQL query (which is great!), here is a revised query. It also includes constraint names, inheritance information, and a data types broken into it's constituent parts (type, length, precision, scale). It also filters out columns that have been dropped (which still exist in the database).
SELECT
n.nspname as schema,
c.relname as table,
f.attname as column,
f.attnum as column_id,
f.attnotnull as not_null,
f.attislocal not_inherited,
f.attinhcount inheritance_count,
pg_catalog.format_type(f.atttypid,f.atttypmod) AS data_type_full,
t.typname AS data_type_name,
CASE
WHEN f.atttypmod >= 0 AND t.typname <> 'numeric'THEN (f.atttypmod - 4) --first 4 bytes are for storing actual length of data
END AS data_type_length,
CASE
WHEN t.typname = 'numeric' THEN (((f.atttypmod - 4) >> 16) & 65535)
END AS numeric_precision,
CASE
WHEN t.typname = 'numeric' THEN ((f.atttypmod - 4)& 65535 )
END AS numeric_scale,
CASE
WHEN p.contype = 'p' THEN 't'
ELSE 'f'
END AS is_primary_key,
CASE
WHEN p.contype = 'p' THEN p.conname
END AS primary_key_name,
CASE
WHEN p.contype = 'u' THEN 't'
ELSE 'f'
END AS is_unique_key,
CASE
WHEN p.contype = 'u' THEN p.conname
END AS unique_key_name,
CASE
WHEN p.contype = 'f' THEN 't'
ELSE 'f'
END AS is_foreign_key,
CASE
WHEN p.contype = 'f' THEN p.conname
END AS foreignkey_name,
CASE
WHEN p.contype = 'f' THEN p.confkey
END AS foreign_key_columnid,
CASE
WHEN p.contype = 'f' THEN g.relname
END AS foreign_key_table,
CASE
WHEN p.contype = 'f' THEN p.conkey
END AS foreign_key_local_column_id,
CASE
WHEN f.atthasdef = 't' THEN d.adsrc
END AS default_value
FROM pg_attribute f
JOIN pg_class c ON c.oid = f.attrelid
JOIN pg_type t ON t.oid = f.atttypid
LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)
LEFT JOIN pg_class AS g ON p.confrelid = g.oid
WHERE c.relkind = 'r'::char
AND f.attisdropped = false
AND n.nspname = '%s' -- Replace with Schema name
AND c.relname = '%s' -- Replace with table name
AND f.attnum > 0
ORDER BY f.attnum
;
You can also check using below query
Select * from schema_name.table_name limit 0;
Expmple : My table has 2 columns name and pwd. Giving screenshot below.
*Using PG admin3
In postgres \d is used to describe the table structure.
e.g. \d schema_name.table_name
this command will provide you the basic info of table such as, columns, type and modifiers.
If you want more info about table use
\d+ schema_name.table_name
this will give you extra info such as, storage, stats target and description
The best way to describe a table such as a column, type, modifiers of columns, etc.
\d+ tablename or \d tablename
When your table is not part of the default schema, you should write:
\d+ schema_name.table_name
Otherwise, you would get the error saying that "the relation doesn not exist."
When your table name starts with a capital letter you should put your table name in the quotation.
Example: \d "Users"
Use this command
\d table name
like
\d queuerecords
Table "public.queuerecords"
Column | Type | Modifiers
-----------+-----------------------------+-----------
id | uuid | not null
endtime | timestamp without time zone |
payload | text |
queueid | text |
starttime | timestamp without time zone |
status | text |
1) PostgreSQL DESCRIBE TABLE using psql
In psql command line tool, \d table_name or \d+ table_name to find the information on columns of a table
2) PostgreSQL DESCRIBE TABLE using information_schema
SELECT statement to query the column_names,datatype,character maximum length of the columns table in the information_schema database;
SELECT
COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
from INFORMATION_SCHEMA.COLUMNS where table_name = 'tablename';
For more information https://www.postgresqltutorial.com/postgresql-describe-table/
I'll add the pg_dump command even thou the psql command was requested. because it generate an output more common to previous MySQl users.
# sudo -u postgres pg_dump --table=my_table_name --schema-only mydb
/dt is the commad which lists you all the tables present in a database. using
/d command and /d+ we can get the details of a table. The sysntax will be like
* /d table_name (or) \d+ table_name
The command below can describe multiple tables simply
\dt <table> <table>
The command below can describe multiple tables in detail:
\d <table> <table>
The command below can describe multiple tables in more detail:
\d+ <table> <table>
I worked out the following script for get table schema.
'CREATE TABLE ' || 'yourschema.yourtable' || E'\n(\n' ||
array_to_string(
array_agg(
' ' || column_expr
)
, E',\n'
) || E'\n);\n'
from
(
SELECT ' ' || column_name || ' ' || data_type ||
coalesce('(' || character_maximum_length || ')', '') ||
case when is_nullable = 'YES' then ' NULL' else ' NOT NULL' end as column_expr
FROM information_schema.columns
WHERE table_schema || '.' || table_name = 'yourschema.yourtable'
ORDER BY ordinal_position
) column_list;

Resources