how to re-insert all of the existing fields but only change one field data in postgresql? - sql

I have bunch of data in one table, for example lets say I have a table with four columns.
id,name,age,address.
id stays the same but all the other fields changes. i.e it will look something like this.
id name age address
1 steve 20 test address 1
1 mark 21 test address 2
and now I want to have the same data set but only change the id, for example everything will stay the same but only the id changes to look something like this:
id name age address
1 steve 20 test address 1
1 mark 21 test address 2
2 steve 20 test address 1
2 mark 21 test address 2
but I don't want to insert it one field at a time, because I have 100's of fields and to do it like that will waste so much time.
so my question is how can i do this as easily as possible in Postgres?
I forgot to mention the other fields are not set by default and I want to copy the data from a specific field id, so in general it should be like. first I want to grab all the fields from a specific id, then insert these fields again but now with the new id which is 2 for example.

insert into table(id,name,age,address) select 2,name,age,address from table

create table list (id int,name text,age int,address text);
insert into list values (1,'steve',20,'AAAAAAAAA');
insert into list values (1,'mark',21,'BBBBBBBBB');
Now create a function for the INSERT Operation:
create or replace function ins_list(_updateID int ,_getID int) returns void as
$$
-- _updateID : - the new ID that you want to insert(ex. 2)
-- _getID : - the ID that you need to search to get values from name,age,address (ex.1)
insert into list (id,name,age,address) select _updateID,name,age,address from list where id = _getID
$$
language sql
to Insert you just need to call like
select ins_list(2,1);

Related

Adding column to sqlite database and distribute rows based on primary key

I have some data elements containing a timestamp and information about Item X sales related to this timestamp.
e.g.
timestamp | items X sold
------------------------
1 | 10
4 | 40
7 | 20
I store this data in an SQLite table. Now I want to add to this table. Especially if I get data about another item Y.
The item Y data might or might not have different timestamps but I want to insert this data into the existing table so that it looks like this:
timestamp | items X sold | items Y sold
------------------------------------------
1 | 10 | 5
2 | NULL | 10
4 | 40 | NULL
5 | NULL | 3
7 | 20 | NULL
Later on additional sales data (columns) must be added with the same scheme.
Is there an easy way to accomplish this with SQLite?
In the end I want to fetch data by timestamp and get an overview which items were sold at this time. Most examples consider the usecase to add a complete row (one record) or a complete column if it perfectly matches to the other columns.
Or is sqlite the wrong tool at all? And I should rather use csv or excel?
(Using pythons sqlite3 package to create and manipulate the DB)
Thanks!
Dynamically adding columns is not a good design. You could add them using
ALTER TABLE your_table ADD COLUMN the_column_name TEXT
the column, for existing rows would be populated with nulls, although you could specify a DEFAULT value and the existing rows would then be populated with that value.
e.g. the following demonstrates the above :-
DROP TABLE IF EXISTS soldv1;
CREATE TABLE IF NOT EXISTS soldv1 (timestamp INTEGER PRIAMRY KEY, items_sold_x INTEGER);
INSERT INTO soldv1 VALUES(1,10),(4,40),(7,20);
SELECT * FROM soldv1 ORDER BY timestamp;
ALTER TABLE soldv1 ADD COLUMN items_sold_y INTEGER;
UPDATE soldv1 SET items_sold_y = 5 WHERE timestamp = 1;
INSERT INTO soldv1 VALUES(2,null,10),(5,null,3);
SELECT * FROM soldv1 ORDER BY timestamp;
resulting in the first query returning :-
and the second query returning :-
However, as stated, the above is not considered a good design as the schema is dynamic.
You could alternately manage an equivalent of the above with the addition of either a new column (to also be part of the primary key) or by prefixing/suffixing the timestamp with a type.
Consider, as an example, the following :-
DROP TABLE IF EXISTS soldv2;
CREATE TABLE IF NOT EXISTS soldv2 (type TEXT, timestamp INTEGER, items_sold INTEGER, PRIMARY KEY(timestamp,type));
INSERT INTO soldv2 VALUES('x',1,10),('x',4,40),('x',7,20);
INSERT INTO soldv2 VALUES('y',1,5),('y',2,10),('y',5,3);
INSERT INTO soldv2 VALUES('z',1,15),('z',2,5),('z',9,25);
SELECT * FROM soldv2 ORDER BY timestamp;
This has replicated, data-wise, your original data and additionally added another type (column items_sold_z) without having to change the table's schema (nor having the additional complication of needing to update rather than insert as per when applying timestamp 1 items_sold_y 5).
The result from the query being :-
Or is sqlite the wrong tool at all? And I should rather use csv or excel?
SQLite is a valid tool. What you then do with the data can probably be done as easy as in excel (perhaps simpler) and probably much simpler than trying to process the data in csv format.
For example, say you wanted the total items sold per timestamp and how many types were sold then :-
SELECT timestamp, count(items_sold) AS number_of_item_types_sold, sum(items_sold) AS total_sold FROM soldv2 GROUP by timestamp ORDER BY timestamp;
would result in :-

OR Database/Type in Oracle Express/SQL Developer

I try to do some stuff wie object relational Databases. I have Oracle Express and the SQL Developer. Everything works fine.
I can create my own, custom types and insert some rows. The problem is that it would not be display right. I think it is normally because they should be display object/types in a column...
Is there a solution to display the objects in the columns?
This is my code.
p.s. i am from germany. ANSCHRIFT_T is a type for an address with name of the tress (Strasse) and house number (Hausnr).
CREATE OR REPLACE TYPE ANSCHRIFT_T AS OBJECT (STRASSE CHAR(12), HAUSNR CHAR(3));
CREATE TABLE VERTRETER(V_NR NUMBER(4) PRIMARY KEY, ANSCHRIFT ANSCHRIFT_T);
INSERT INTO VERTRETER VALUES (1, ANSCHRIFT_T('TESTWEG','14'));
INSERT INTO VERTRETER VALUES (2, ANSCHRIFT_T('BLA BLA WEG', '25'));
SELECT V_NR, ANSCHRIFT FROM VERTRETER;
But the output its just this:
Double click on the value. You'll see your data.
Or, you can tell SQL Developer to show those values by default.
Preferences > Advanced, display structures
And then run your query again.
[
You need to add an alias for the table name and then you can select the values from the object column using table_alias.object_column.object_attribute. Like this:
Query:
SELECT V_NR,
v.ANSCHRIFT.STRASSE,
v.ANSCHRIFT.HAUSNR
FROM VERTRETER v;
Output:
V_NR ANSCHRIFT.STRASSE ANSCHRIFT.HAUSNR
---------- ----------------- ----------------
1 TESTWEG 14
2 BLA BLA WEG 25

sql query to display unavailable number?

i have some list of numbers with me, i want to check that numbers in a specified table available or not, if any number is not available in the table from the list of given numbers, then that unavailable number need to be display
I didnt sure that i understad your query correctly,
but it seems you mean somthing like this:
select *
from TABLE_NAME t
where t.COLUMN_NAME not in (1,2,3.... (#your list values#))
save the list of number first:
Create table list(id int);
insert into list(id)values(1);
insert into list(id)values(2);
insert into list(id)values(3);
insert into list(id)values(4);
Create sample table
Create table chck_list(id int,name varchar2(10));
insert into chck_list(id,name)values(1,'Micheal');
insert into chck_list(id,name)values(2,'John');
insert into chck_list(id,name)values(8,'Jack');
Query to check if there are id in list not showed in chck_list
select list.id
from list lst
where not exists(select 1 from chck_list chck where chck.id=lst.id)
Result
=========================
id
=========================
3
4

SQL - keep values with UPDATE statement

I have a table "news" with 10 rows and cols (uid, id, registered_users, ....) Now i have users that can log in to my website (every registered user has a user id). The user can subscribe to a news on my website.
In SQL that means: I need to select the table "news" and the row with the uid (from the news) and insert the user id (from the current user) to the column "registered_users".
INSERT INTO news (registered_users)
VALUES (user_id)
The INSERT statement has NO WHERE clause so i need the UPDATE clause.
UPDATE news
SET registered_users=user_id
WHERE uid=post_news_uid
But if more than one users subscribe to the same news the old user id in "registered_users" is lost....
Is there a way to keep the current values after an sql UPDATE statement?
I use PHP (mysql). The goal is this:
table "news" row 5 (uid) column "registered_users" (22,33,45)
--- 3 users have subscribed to the news with the uid 5
table "news" row 7 (uid) column "registered_users" (21,39)
--- 2 users have subscribed to the news with the uid 7
It sounds like you are asking to insert a new user, to change a row in news from:
5 22,33
and then user 45 signs up, and you get:
5 22,33,45
If I don't understand, let me know. The rest of this solution is an excoriation of this approach.
This is a bad, bad, bad way to store data. Relational databases are designed around tables that have rows and columns. Lists should be represented as multiple rows in a table, and not as string concatenated values. This is all the worse, when you have an integer id and the data structure has to convert the integer to a string.
The right way is to introduce a table, say NewsUsers, such as:
create table NewsUsers (
NewsUserId int identity(1, 1) primary key,
NewsId int not null,
UserId int not null,
CreatedAt datetime default getdaete(),
CreatedBy varchar(255) default sysname
);
I showed this syntax using SQL Server. The column NewsUserId is an auto-incrementing primary key for this table. The columns NewsId is the news item (5 in your first example). The column UserId is the user id that signed up. The columns CreatedAt and CreatedBy are handy columns that I put in almost all my tables.
With this structure, you would handle your problem by doing:
insert into NewsUsers
select 5, <userid>;
You should create an additional table to map users to news they have registeres on
like:
create table user_news (user_id int, news_id int);
that looks like
----------------
| News | Users|
----------------
| 5 | 22 |
| 5 | 33 |
| 5 | 45 |
| 7 | 21 |
| ... | ... |
----------------
Then you can use multiple queries to first retrieve the news_id and the user_id and store them inside variables depending on what language you use and then insert them into the user_news.
The advantage is, that finding all users of a news is much faster, because you don't have to parse every single idstring "(22, 33, 45)"
It sounds like you want to INSERT with a SELECT statement - INSERT with SELECT
Example:
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1
WHERE tbl_temp1.fld_order_id > 100;

Retrieve inserted row ID in SQL

How do I retrieve the ID of an inserted row in SQL?
Users Table:
Column | Type
--------|--------------------------------
ID | * Auto-incrementing primary key
Name |
Age |
Query Sample:
insert into users (Name, Age) values ('charuka',12)
In MySQL:
SELECT LAST_INSERT_ID();
In SQL Server:
SELECT SCOPE_IDENTITY();
In Oracle:
SELECT SEQNAME.CURRVAL FROM DUAL;
In PostgreSQL:
SELECT lastval();
(edited: lastval is any, currval requires a named sequence)
Note: lastval() returns the latest sequence value assigned by your session, independently of what is happening in other sessions.
In SQL Server, you can do (in addition to the other solutions already present):
INSERT INTO dbo.Users(Name, Age)
OUTPUT INSERTED.ID AS 'New User ID'
VALUES('charuka', 12)
The OUTPUT clause is very handy when doing inserts, updates, deletes, and you can return any of the columns - not just the auto-incremented ID column.
Read more about the OUTPUT clause in the SQL Server Books Online.
In Oracle and PostgreSQL you can do this:
INSERT INTO some_table (name, age)
VALUES
('charuka', 12)
RETURNING ID
When doing this through JDBC you can also do that in a cross-DBMS manner (without the need for RETURNING) by calling getGeneratedKeys() after running the INSERT
I had the same need and found this answer ..
This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.
===========================
CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]
#comp_name varchar(55) = 'Big Company',
#comp_regno nchar(8) = '12345678',
#comp_email nvarchar(50) = 'no1#home.com',
#recID INT OUTPUT
-- The '#recID' is used to hold the Company auto generated ID number that we are about to grab
AS
Begin
SET NOCOUNT ON
DECLARE #tableVar TABLE (tempID INT)
-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '#recID'.
INSERT INTO comp(comp_name, comp_regno, comp_email)
OUTPUT inserted.comp_id INTO #tableVar
-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.
VALUES (#comp_name, #comp_regno, #comp_email)
SET #recID = (SELECT tempID FROM #tableVar)
-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '#recID'. '#recID' now has the ID number you want and you can use it how you want like i have used it below.
INSERT INTO staff(Staff_comp_id)
VALUES (#recID)
End
-- So there you go. I was looking for something like this for ages, with this detailed break down, I hope this helps.