Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Friday, January 24, 2020

PostgresSql option for creating table like another table


In MSSQL there is an easy, code-based, way to create a table with the same DDL and data as another table.
This is simply by running a query similar to this:



select * INTO "NEW TABLE" FROM "SOURCE TABLE"

I needed to do something similar in PostgreSQL and found this to be a nice way to recreate a table using another as a templet

CREATE TABLE TESTTABLE
AS
  SELECT *
  FROM "SOURCE TABLE"
  WHERE false;

Friday, March 20, 2015

Postgres -- Tables and Column Length

To generate the following outoput in PostgresSQl


ID Table Name Schema Count of Columns TotalRows
1 Test1 public 4 600
2 Test2 public 12 1268

The following code works well:

SELECT
  t.table_name, t.table_schema, count(columns.column_name), n_live_tup AS totalRowCount  FROM
  information_schema.tables t
  LEFT OUTER JOIN  information_schema.columns on  columns.table_name = t.table_name
  LEFT OUTER JOIN  pg_catalog.pg_stat_user_tables pc on t.table_name = pc.relname
  WHERE t.table_schema ='public'
GROUP BY t.table_name, t.table_schema, n_live_tup


Saturday, October 26, 2013

Just out of interest


While researching a SQL date problem, I came across this and as it is quite interesting and informative, I have decided to post it here as well.

This is not my or the Research Team's work, so credit is given to the original source:
http://www.karaszi.com/sqlserver/info_datetime.asp#RecommendationsInput


Why is 1753 the earliest date for datetime?
Good question. It is for historical reasons. In what we sometimes refer to as the western world, we have had two calendars in modern time: the Julian and the Gregorian calendars. These calendars were a number of days apart (depending on which century you look at), so when a culture that used the Julian calendar moved to the Gregorian calendar, they dropped from 10 to 13 days. Great Britain made this shift in 1752 (1752-09-02 were followed by 1752-09-14). An educated guess why Sybase selected 1753 as earliest date is that if you were to store an earlier date than 1753, you would also have to know which country and also handle this 10-13 day jump. So they decided to not allow dates earlier than 1753. Note, however that other countries did the shift later than 1752. Turkey, for instance, did it as late as 1927.
Being Swedish, I find it a bit amusing that Sweden had the weirdest implementation. They decided to skip the leap day over a period of 40 years (from 1700 to 1740), and Sweden would be in sync with the Gregorian calendar after 1740 (but meanwhile not in sync with anyone). However, in 1704 and 1708 the leap day wasn't skipped for some reason, so in 1712 which was a leap year, they inserted yet an extra day (imagine being born in Feb 30!) and then did the shift over a day like everyone else, in 1753.