Create empty table in postgresql - postgresql

i want to create a simple table inside a database in postgresql.
From the Documentation i have CREATE TABLE will create a new, initially empty table in the current database. The table will be owned by the user issuing the command.
With this command
CREATE TABLE *table_name*;
I thought i get a new empty table.But psql throws ERROR: syntax error at or near ";". When i user an empty argument list like:
CREATE TABLE *table_name*();
psql tells me that the table was created through
postgres=# create table *table_name*();
CREATE TABLE
But \l shows is not showing the newly created table. And its also not possible to login with psql -d table_name -U user_name. Can anyone help?

You can have a table with no columns, and even with some rows in it:
CREATE TABLE nocolumn (dummy INTEGER NOT NULL PRIMARY KEY)
;
INSERT INTO nocolumn(dummy) VALUES (1);
ALTER TABLE nocolumn
DROP COLUMN dummy;
\d nocolumn
SELECT COUNT(*) FROM nocolumn;
Output:
CREATE TABLE
INSERT 0 1
ALTER TABLE
Table "tmp.nocolumn"
Column | Type | Modifiers
--------+------+-----------
count
-------
1
(1 row)

You seem to be confusing the terms database and table
But \l is not showing the newly created table.
Of course \l will not show you that table, because \l will list databases not relations. To see all tables you need to use \d or \dt.
And its also not possible to login with psql -d table_name -U user_name
Of course this is not possible, because the -d parameter is used to specify a database, not a table

I'm not sure why other answers suggest to create a table with a column and then ignore that column. It is certainly possible, but it seems different from what you tried to do.
It seems you have to use parenthesis:
postgres=# CREATE TABLE t ();
CREATE TABLE
To insert a row:
postgres=# INSERT INTO t DEFAULT VALUES;
INSERT 0 1
To count the rows you inserted:
postgres=# SELECT FROM t;
--
(2 rows)
You can't delete a single rows, because all rows are equal. But to completely empty the table, you can use DELETE without WHERE, or TRUNCATE TABLE.
You can find more info here: PostgreSQL: Tables without columns.
That said, I have to say that I understand "empty table" as "table without rows", not necessarily without columns.

An hour ago i suggested to add at least one column like this:
create table tab1 (columnname varchar(42) not null)
But this seems to be not necessary as a commentator just told. (I consider to keep the wrong answer here instead of deleting it, to prevent that others suggest the same)

Related

Postgres: difference between DEFAULT in CREATE TABLE and ALTER TABLE in database dump

In database dump created with pg_dump, some tables have DEFAULTs in the CREATE TABLE statement, i.e.:
CREATE TABLE test (
f1 integer DEFAULT nextval('test_f1_seq'::regclass) NOT NULL
);
But others have an additional ALTER statement:
ALTER TABLE ONLY test2 ALTER COLUMN f1 SET DEFAULT nextval('test2_f1_seq'::regclass);
What is the reason of this? All sequential fields were created with type SERIAL, but in the dump they look different, and I can't guess any rule for this.
The difference must be that in the first case, the sequence is “owned” by the table column.
You can specify this dependency using the OWNED BY clause when you create a sequence. A sequence that is owned by a column will automatically be dropped when the column is.
If a sequence is implicitly created by using serial, it will be owned by the column.

Add column to show a row number in the PostgreSQL [duplicate]

I have a table with existing data. Is there a way to add a primary key without deleting and re-creating the table?
(Updated - Thanks to the people who commented)
Modern Versions of PostgreSQL
Suppose you have a table named test1, to which you want to add an auto-incrementing, primary-key id (surrogate) column. The following command should be sufficient in recent versions of PostgreSQL:
ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
Older Versions of PostgreSQL
In old versions of PostgreSQL (prior to 8.x?) you had to do all the dirty work. The following sequence of commands should do the trick:
ALTER TABLE test1 ADD COLUMN id INTEGER;
CREATE SEQUENCE test_id_seq OWNED BY test1.id;
ALTER TABLE test1 ALTER COLUMN id SET DEFAULT nextval('test_id_seq');
UPDATE test1 SET id = nextval('test_id_seq');
Again, in recent versions of Postgres this is roughly equivalent to the single command above.
ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
This is all you need to:
Add the id column
Populate it with a sequence from 1 to count(*).
Set it as primary key / not null.
Credit is given to #resnyanskiy who gave this answer in a comment.
To use an identity column in v10,
ALTER TABLE test
ADD COLUMN id { int | bigint | smallint}
GENERATED { BY DEFAULT | ALWAYS } AS IDENTITY PRIMARY KEY;
For an explanation of identity columns, see https://blog.2ndquadrant.com/postgresql-10-identity-columns/.
For the difference between GENERATED BY DEFAULT and GENERATED ALWAYS, see https://www.cybertec-postgresql.com/en/sequences-gains-and-pitfalls/.
For altering the sequence, see https://popsql.io/learn-sql/postgresql/how-to-alter-sequence-in-postgresql/.
I landed here because I was looking for something like that too. In my case, I was copying the data from a set of staging tables with many columns into one table while also assigning row ids to the target table. Here is a variant of the above approaches that I used.
I added the serial column at the end of my target table. That way I don't have to have a placeholder for it in the Insert statement. Then a simple select * into the target table auto populated this column. Here are the two SQL statements that I used on PostgreSQL 9.6.4.
ALTER TABLE target ADD COLUMN some_column SERIAL;
INSERT INTO target SELECT * from source;
ALTER TABLE test1 ADD id int8 NOT NULL GENERATED ALWAYS AS IDENTITY;

Issue with basic create statements in postgreSQL

I've used the psql module to create a new database using the following syntax:
CREATE DATABASE fish
I can open the database. However, when I try to create tables or columns it gives me a syntax error for the following message.
CREATE TABLE salmon;
this is the error message:
ERROR: syntax error at or near ";"
LINE 1: CREATE TABLE species;
I've checked a lot of online postgreSQL resources and they haven't been of much help. To the best of my knowledge, I haven't messed up the syntax. Thanks.
you can use this syntax for empty table:
create table salmon();
You must create atleast one column in a table:
CREATE TABLE salmon ( column_name data_type ...........);
Postgres create table link: https://www.postgresql.org/docs/9.1/static/sql-createtable.html
You can't create an empty table - it must have at least one column. E.g.:
CREATE TABLE salmon (name VARCHAR(10));
psql is not a module. Please read https://www.postgresql.org/docs/current/static/app-psql.html
you odn't open a database - you connect to it.
Establishes a new connection to a PostgreSQL server
https://www.postgresql.org/docs/current/static/sql-createtable.html
{ column_name | ( expression ) }
Either column list (create table a (a int);) or expression (create table b as select now() time_column) is obligatory part.

Delete column in hive table

I am working with hive version 0.9 and I need delete columns of a hive table. I have searched in several manuals of hive commands but I only I have found commands to version 0.14. Is possible to delete a column of a hive table in hive version 0.9? What is the command?
Thanks.
We can’t simply drop a table column from a hive table using the below statement like sql.
ALTER TABLE tbl_name drop column column_name ---- it will not work.
So there is a shortcut to drop columns from a hive table.
Let’s say we have a hive table.
From this table I want to drop the column Dob. You can use the ALTER TABLE REPLACE statement to drop a column.
ALTER TABLE test_tbl REPLACE COLUMNS(ID STRING,NAME STRING,AGE STRING); you have to give the column names which you want to keep in the table
There isn't a drop column or delete column in Hive.
A SELECT statement can take regex-based column specification in Hive releases prior to 0.13.0, or in 0.13.0 and later releases if the configuration property hive.support.quoted.identifiers is set to none.
That being said you could create a new table or view using the following:
drop table if exists database.table_name;
create table if not exists database.table_name as
select `(column_to_remove_1|...|column_to_remove_N)?+.+`
from database.some_table
where
...
;
This will create a table that has all the columns from some_table except the columns named column_to_remove_1, ... , to column_to_remove_N. You can also choose to create a view instead.
ALTER TABLE table_name REPLACE COLUMNS ( c1 int, c2 String);
NOTE: eliminate column from column list. It will keep matched columns and removed unmentioned columns from table schema.
we can not delete column from hive table . But droping a table(if its external) in hive and the recreating table(with column excluded) ,wont delete ur data .
so what can u do is(if u dont have table structure) run this command :
show create table database_name.table_name;
Then you can copy it and edit it (with column eliminated).Afterwards you can do as per invoke the shell
table details are empid,name,dept,salary ,address. i want remove address column. Just write REPLACE COLUMNS like below query
jdbc:hive2://> alter table employee replace columns(empid int, name string,dept string,salary int);
As mentioned before, you can't drop table using an alter statement.
Alter - replace is not guaranteed to work in all the cases.
I found the best answer for this here:
https://stackoverflow.com/a/48921280/4385453

Postgresql: inserting value of a column from a file

For example, there is a table named 'testtable' that has following columns: testint (integer) and testtext (varchar(30)).
What i want to do is pretty much something like that:
INSERT INTO testtable VALUES(15, CONTENT_OF_FILE('file'));
While reading postgresql documentation, all I could find is COPY TO/FROM command, but that one's applied to tables, not single columns.
So, what shall I do?
If this SQL code is executed dynamically from your programming language, use the means of that language to read the file, and execute a plain INSERT statement.
However, if this SQL code is meant to be executed via the psql command line tool, you can use the following construct:
\set content `cat file`
INSERT INTO testtable VALUES(15, :'content');
Note that this syntax is specific to psql and makes use of the cat shell command.
It is explained in detail in the PostgreSQL manual:
psql / SQL Interpolation
psql / Meta-Commands
If I understand your question correctly, you could read the single string(s) into a temp table and use that for insert:
DROP SCHEMA str CASCADE;
CREATE SCHEMA str;
SET search_path='str';
CREATE TABLE strings
( string_id INTEGER PRIMARY KEY
, the_string varchar
);
CREATE TEMP TABLE string_only
( the_string varchar
);
COPY string_only(the_string)
FROM '/tmp/string'
;
INSERT INTO strings(string_id,the_string)
SELECT 5, t.the_string
FROM string_only t
;
SELECT * FROM strings;
Result:
NOTICE: drop cascades to table str.strings
DROP SCHEMA
CREATE SCHEMA
SET
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "strings_pkey" for table "strings"
CREATE TABLE
CREATE TABLE
COPY 1
INSERT 0 1
string_id | the_string
-----------+---------------------
5 | this is the content
(1 row)
Please note that the file is "seen" by the server as the server sees the filesystem. The "current directory" from that point of view is probably $PG_DATA, but you should assume nothing, and specify the complete pathname, which should be reacheable and readable by the server. That is why I used '/tmp', which is unsafe (but an excellent rendez-vous point ;-)