How to do an insert with a select statement, with unique values
Hi,
I have an insert statement like this
INSERT INTO TABLEA (ID, zzz
SELECT sequence.nextval, zzz FROM TABLEB
The problem is TABLEA won't allow any duplicates and TABLEB will return duplicates. Yet I can't use the distinct keyword since I am using a sequence.
Thanks.
Samuel411 wrote:
Hi,
I have an insert statement like this
INSERT INTO TABLEA (ID, zzz
SELECT sequence.nextval, zzz FROM TABLEB
The problem is TABLEA won't allow any duplicates and TABLEB will return duplicates. Yet I can't use the distinct keyword since I am using a sequence.
Thanks.Why not?
drop sequence s
create sequence s;
create table distincting (col1 number, object_owner varchar2(30));
TUBBY_TUBBZ?
insert into distincting
select s.nextval, object_owner
from
select
distinct
owner as object_owner
from dba_objects
9 );
37 rows created.
TUBBY_TUBBZ?
Similar Messages
-
How to avoid data repetation when using select statements with innerjoin
how to avoid data repetation when using select statements with innerjoin.
thanks in advance,
satheeshyou can use a query like this...
SELECT DISTINCT
frg~prc_group1 "Product Group 1
frg~prc_group2 "Product Group 2
frg~prc_group3 "Product Group 3
frg~prc_group4 "Product Group 4
frg~prc_group5 "Product Group 5
prc~product_id "Product ID
txt~short_text "Product Description
UP TO 10 ROWS
INTO TABLE l_i_data
FROM
Joining CRMM_PR_SALESG and
COMM_PR_FRG_ROD
crmm_pr_salesg AS frg
INNER JOIN comm_pr_frg_rod AS prd
ON frgfrg_guid = prdfragment_guid
Joining COMM_PRODUCT and
COMM_PR_FRG_ROD
INNER JOIN comm_product AS prc
ON prdproduct_guid = prcproduct_guid
Joining COMM_PRSHTEXT and
COMM_PR_FRG_ROD
INNER JOIN comm_prshtext AS txt
ON prdproduct_guid = txtproduct_guid
WHERE frg~prc_group1 IN r_zprc_group1
AND frg~prc_group2 IN r_zprc_group2
AND frg~prc_group3 IN r_zprc_group3
AND frg~prc_group4 IN r_zprc_group4
AND frg~prc_group5 IN r_zprc_group5.
reward it it helps
Edited by: Apan Kumar Motilal on Jun 24, 2008 1:57 PM -
How to create a matrix with constant values and multiply it with the output of adc
How to create a matrix with constant values and multiply it with the output of adc
nitinkajay wrote:
How to create a matrix with constant values and multiply it with the output of adc
Place array constant on diagram, drag a double to it, r-click "add dimension". There, a constant 2D double array, a matrix.
/Y
LabVIEW 8.2 - 2014
"Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
G# - Free award winning reference based OOP for LV -
Behaviour of insert ... select statement
Hi,
If we use insert ... select statement like
insert into TableA
Select
from TableB;
and if TableB have 250000 rows then what will be the action for it..
will all 250000 rows fetched to database buffer and if index scans are performed on it and then all rows inserted into TableA
or
it will do it parallel
We are loading large data and facing performance problems for delaying index scans.
Just Curious :)
Rushang.it's not a secret. oracle will perform the select, using indexes if it decides to (depends on source table size, stats, optimizer mode, etc, etc). rows may be pulled back to memory be written to temp space (e.g., if you were returning many, many rows which needed to be grouped). the rows will then be inserted.
so, if you have an index on tableb.col1, then oracle may use the index. or it may do a FTS. either way, it will only select the needed rows to be inserted.
the insert does not prevent the select from working as it would normally. -
How to compile the hint to force selection statement to use index
Hello expert,
will you please tell me how to compile the hint to force selection statement to use index?
Many Thanks,Not sure what you mean by compile, but hint is enclosed in /*+ hint */. Index hint is INDEX(table_name,index_name). For example:
SQL> explain plan for
2 select * from emp
3 /
Explained.
SQL> @?\rdbms\admin\utlxpls
PLAN_TABLE_OUTPUT
Plan hash value: 3956160932
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 14 | 546 | 3 (0)| 00:00:01 |
| 1 | TABLE ACCESS FULL| EMP | 14 | 546 | 3 (0)| 00:00:01 |
8 rows selected.
SQL> explain plan for
2 select /*+ index(emp,pk_emp) */ *
3 from emp
4 /
Explained.
SQL> @?\rdbms\admin\utlxpls
PLAN_TABLE_OUTPUT
Plan hash value: 4170700152
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 14 | 546 | 2 (0)| 00:00:01 |
| 1 | TABLE ACCESS BY INDEX ROWID| EMP | 14 | 546 | 2 (0)| 00:00:01 |
| 2 | INDEX FULL SCAN | PK_EMP | 14 | | 1 (0)| 00:00:01 |
9 rows selected.
SQL> Hint in the above example is forcing optimizer to use index which resul;ts in a bad execution plan. Most of the time optimizer does not need hints and chooses an optimal plan. In most cases sub-optimal plan is result of stale or incomplete statistics.
SY. -
Select statement on unique key consraint
I have a table 'PO' in which 'ID' is primary key and 'PO_NUM' is unique key. I am using a select statement on unique key 'PO_NUM' to get the 'ID'.
select id from po where po_num= '3266';
it says, 'no data found'
But the exists in the database. Can anyone help me with this one.
Thanks
-LavanyaIs "no data found" an "in-house" error message, i.e. one you put out in a print statement in a catch block? If so, change that catch block to include a stacktrace so we can see what the actual error message is, if there is one, or if it is actually returning an empty result set.
-
How to change stored procedure with Table Valued Parameter
I am not sure how to change the normal stored procedure with Table Value Parameter.Do I have to create a separate Table or do I have to create a datatype. Can you please help me with this
ALTER PROCEDURE [dbo].[uspInsertorUpdateINF]
@dp_id char(32),
@dv_id char(32),
@em_number char(12),
@email varchar(50),
@emergency_relation char(32),
@option1 char(16),
@status char(20),
@em_id char(35),
@em_title varchar(64),
@date_hired datetime
AS
BEGIN
SET NOCOUNT ON;
MERGE [dbo].[em] AS [Targ]
USING (VALUES (@dp_id, @dv_id , @em_number, @email, @emergency_relation, @option1, @status, @em_id, @em_title, @date_hired))
AS [Sourc] (dp_id, dv_id, em_number, email, emergency_relation, option1, status, em_id, em_title, date_hired)
ON [Targ].em_id = [Sourc].em_id
WHEN MATCHED THEN
UPDATE
SET dp_id = [Sourc].dp_id,
dv_id = [Sourc].dv_id,
em_number = [Sourc].em_number,
email = [Sourc].email,
emergency_relation = [Sourc].emergency_relation,
option1 = [Sourc].option1,
status = [Sourc].status,
em_title = [Sourc].em_title,
date_hired = [Sourc].date_hired
WHEN NOT MATCHED BY TARGET THEN
INSERT (dp_id, dv_id, em_number, email, emergency_relation, option1, status, em_id, em_title,date_hired)
VALUES ([Sourc].dp_id, [Sourc].dv_id, [Sourc].em_number, [Sourc].email, [Sourc].emergency_relation, [Sourc].option1, [Sourc].status, [Sourc].em_id, [Sourc].em_title, [Sourc].date_hired);
END;It's not clear how you would change the procedure. But assuming that you want to replace the existing scalar parameters with tabular input, this is how you would do it. You first create a table type:
CREATE TYPE Insertor_type AS TABLE
(dp_id char(32),
dv_id char(32),
em_number char(12),
email varchar(50),
emergency_relation char(32),
option1 char(16),
status char(20),
em_id char(35),
em_title varchar(64),
date_hired datetime)
Then you change the procedure header:
ALTER PROCEDURE [dbo].[uspInsertorUpdateINF] @tvp Insertor_type READONLY AS
And finally you change the USING clause:
USING (SELECT dp_id, dv_id , em_number, email, emergency_relation, option1, status, em_id, em_title, date_hired
FROM @tvp) AS [Sourc] ON [Targ].em_id = [Sourc].em_id
The rest is fine as it is.
Erland Sommarskog, SQL Server MVP, [email protected] -
In how many ways we can filter this select statement to improve performance
Hi Experts,
This select statement taking 2.5 hrs in production, Can we filter the where condition, to improve the performance.Plz suggest with coding ASAP.
select * from dfkkop into table t_dfkkop
where vtref like 'EPC%' and
( ( augbd = '00000000' and
xragl = 'X' )
or
( augbd between w_clrfr and w_clrto ) ) and
augrd ne '03' and
zwage_type in s_wtype .
Regards,
Sam.if it really takes 2.5 hours, try the followingtry to run the SQL trace and
select *
into table t_dfkkop
from dfkkop
where vtref like 'EPC%'
and augbd = '00000000' and xragl
and augrd ne '03'
and zwage_type in s_wtype .
select *
appending table t_dfkkop
from dfkkop
where vtref like 'EPC%'
and augbd between w_clrfr and w_clrto
and augrd ne '03'
and zwage_type in s_wtype .
Do a DESCRIBE TABLE after the first SELECT and after the second,
or run an SQL Trace.
What is time needed for both parts, how many records come back, which index is used.
Siegfried -
How do you include static text in select statement in Dynamic pl/sql
I want to include some atatic text and get the output of 4 columns joined with a ":" delimiter within them in a select statement built using Dynamic PL/SQL. How do I build it.
e.g.
Normal select statement would be
select 'MY SKU IS : ', col1||':'||col2||':'||col3||':'||col4 from table1 where ....where condition
and output looks like :
MY SKU IS A:B:C:D
MY SKU IS a:b:c:d
Dynamically I have -
SQL_Stmt := 'select 'MY SKU IS : ', col1||':'||col2||':'||col3||':'||col4 from table1 where '|| wherecondition;
I understand that this does not work because the single quote terminates the string. But my question is how do I achieve the same result with dynamic PL/SQL ? How do I include the static strings and the delimiters. I have tried using double quote, '\'....
????SQL_Stmt := 'select ''MY SKU is ' || col1 || '':'' ||
col2 || '':'' ||
col3 || '':'' ||
col4 ||
' from table1 where ' || wherecondition; -
How to create MIN/MAX limitations in SELECT statement ??
Hey,
I have a table which rank90 (city population ranked from 1>*) and state_abrv which has the corresponding state for each city rank.
Is there a way to select only the maximum AND minimum ranks for each state ??
I realise there is a max and min function, but i need to do it for EACH state_abrv.
An example say Los Angeles is ranked 2, San Diego is ranked 6, and San Fransico is ranked 14 (All of these citys are in california (CA)). How do i display a table which lists only Los Angeles (Highest rank) and San Fransico (lowest rank) but DOESNT list San diego ??
Thanks, you guys are helping me heaps and im starting to learn a lot more :P
Message was edited by:
user495524SQL> create table t (state varchar2(2), city varchar2(20), n number);
Table created.
SQL> insert into t values ('CA','San Francisco',14);
1 row created.
SQL> insert into t values ('CA','San Diego',6);
1 row created.
SQL> insert into t values ('CA','Los Angeles',2);
1 row created.
SQL> insert into t values ('NY','Buffalo',4);
1 row created.
SQL> insert into t values ('NY','Syracuse',7);
1 row created.
SQL> insert into t values ('NY','Mt Kisco',2);
1 row created.
SQL> insert into t values ('NY','Albany',5);
1 row created.
SQL> select * from t order by state, n desc;
ST CITY N
CA San Francisco 14
CA San Diego 6
CA Los Angeles 2
NY Syracuse 7
NY Albany 5
NY Buffalo 4
NY Mt Kisco 2
7 rows selected.
SQL> select state, city, n from
2 (
3 select t.*, min(n) over (partition by state) min_n,
4 max(n) over (partition by state) max_n from t
5 )
6 where n in (min_n, max_n) order by state, n desc;
ST CITY N
CA San Francisco 14
CA Los Angeles 2
NY Syracuse 7
NY Mt Kisco 2
SQL> -
How to create a mapping for a select statement containing DENSE_RANK( )?
Hi,
I want help with a select statement that I want to make a mapping of in OWB 11.1 g. Can anyone please tell me how is code can be incorporated in a mapping?
SELECT DISTINCT MAX (dimension_key) KEEP (DENSE_RANK FIRST ORDER BY day DESC) OVER (PARTITION BY calendar_week_name),
MAX (day) KEEP (DENSE_RANK FIRST ORDER BY DAY DESC) OVER (PARTITION BY calendar_week_name), calendar_week_end_date, calendar_week_number
FROM time_dim;I have been trying to use the Aggregator operator but I am not entirely sure how to go about it. Any help will be highly appreciated.
Thanks in advance,
Ann.Hi Ann
You can just use an EXPRESSION operator. Configure the mapping to be set based only code generation and operating mode.
You will have an expression output attribute for each one of your projected columns;
MAX (dimension_key) KEEP (DENSE_RANK FIRST ORDER BY day DESC) OVER (PARTITION BY calendar_week_name),
MAX (day) KEEP (DENSE_RANK FIRST ORDER BY DAY DESC) OVER (PARTITION BY calendar_week_name),
calendar_week_end_date,
calendar_week_number
Cheers
David -
Insert with unique index slow in 10g
Hi,
We are experiencing very slow response when a dup key is inserted into a table with unique index under 10g. the scenario can be demonstrated in sqlplus with 'timing on':
CREATE TABLE yyy (Col_1 VARCHAR2(5 BYTE) NOT NULL, Col_2 VARCHAR2(10 BYTE) NOT NULL);
CREATE UNIQUE INDEX yyy on yyy(col_1,col_2);
insert into yyy values ('1','1');
insert into yyy values ('1','1');
the 2nd insert results in "unique constraint" error, but under our 10g the response time is consistently in the range of 00:00:00.64. The 1st insert only took 00:00:00.01. BTW, if no index or non-unique index then you can insert many times and all of them return fast. Under our 9.2 DB the response time is always under 00:00:00.01 with no-, unique- and non-unique index.
We are on AIX 5.3 & 10g Enterprise Edition Release 10.2.0.2.0 - 64bit Production.
Has anybody seen this scenario?
Thanks,
DavidIt seems that in 10g Oracle simply is doing something more.
I used your example and run following script on 9.2 and 10.2. Hardware is the same i.e. these are two instances on the same box.
begin
for i in 1..10000 loop
begin
insert into yyy values ('1','1');
exception when others then null;
end;
end loop;
end;
/on 10g it took 01:15.08 and on 9i 00:47.06
Running trace showed that in 9i there was difference in plan of following recursive sql:
9i plan:
select c.name, u.name
from
con$ c, cdef$ cd, user$ u where c.con# = cd.con# and cd.enabled = :1 and
c.owner# = u.user#
call count cpu elapsed disk query current rows
Parse 10000 0.43 0.43 0 0 0 0
Execute 10000 1.09 1.07 0 0 0 0
Fetch 10000 0.23 0.19 0 20000 0 0
total 30000 1.76 1.70 0 20000 0 0
Misses in library cache during parse: 1
Optimizer mode: CHOOSE
Parsing user id: SYS (recursive depth: 2)
Rows Row Source Operation
0 NESTED LOOPS
0 NESTED LOOPS
0 TABLE ACCESS BY INDEX ROWID CDEF$
0 INDEX RANGE SCAN I_CDEF4 (object id 53)
0 TABLE ACCESS BY INDEX ROWID CON$
0 INDEX UNIQUE SCAN I_CON2 (object id 49)
0 TABLE ACCESS CLUSTER USER$
0 INDEX UNIQUE SCAN I_USER# (object id 11)10g plan
select c.name, u.name
from
con$ c, cdef$ cd, user$ u where c.con# = cd.con# and cd.enabled = :1 and
c.owner# = u.user#
call count cpu elapsed disk query current rows
Parse 10000 0.21 0.20 0 0 0 0
Execute 10000 1.20 1.31 0 0 0 0
Fetch 10000 2.37 2.59 0 20000 0 0
total 30000 3.79 4.11 0 20000 0 0
Misses in library cache during parse: 1
Misses in library cache during execute: 1
Optimizer mode: CHOOSE
Parsing user id: SYS (recursive depth: 2)
Rows Row Source Operation
0 HASH JOIN (cr=2 pr=0 pw=0 time=301 us)
0 NESTED LOOPS (cr=2 pr=0 pw=0 time=44 us)
0 TABLE ACCESS BY INDEX ROWID CDEF$ (cr=2 pr=0 pw=0 time=40 us)
0 INDEX RANGE SCAN I_CDEF4 (cr=2 pr=0 pw=0 time=27 us)(object id 53)
0 TABLE ACCESS BY INDEX ROWID CON$ (cr=0 pr=0 pw=0 time=0 us)
0 INDEX UNIQUE SCAN I_CON2 (cr=0 pr=0 pw=0 time=0 us)(object id 49)
0 TABLE ACCESS FULL USER$ (cr=0 pr=0 pw=0 time=0 us)So in 10g it had hash join instead of nested loop join at least for this particular select. Probably time to gather stats on sys tables?
The difference in time wasn't so big though 4.11 vs 1.70 so it doesn't explain all the time taken.
But you can probably check whether you haven't more difference.
Also you can download Thomas Kyte runstats_pkg and run it on both environments to compare whether some stats or latches haven't very big difference.
Gints Plivna
http://www.gplivna.eu -
How to force readObejct query with PK value to go to DB?
The default behaviour for read-object queries with a PK value is to use the cache and not go to the database. How can we change this behaviour?
We have cases that a row was deleted by some other process not through toplink, but the corresponding object still in the cache and if you use the readObject query with PK value, the object will be returned as result.
Thanks in advance,There are several mechanisms to disable caching in TopLink. Note that disabling caching will affect your performance.
In 9.0.4 you can use:
- You can configure you cache type to use a WeakIdentityMap to ensure that only referenced objects are cached.
- On descriptor you can call disableCacheHits() and alwaysRefreshCache() in code or click these options on the Caching/Identity tab in the Mapping Workbench.
- Or to explicitly remove a deleted object from the cache uses session.removeFromIdentityMap(), but you must ensure there are no other objects referencing it.
In 10.1.3 you can also use:
- On descriptor you can call setIsIsolated(true) in code, or select isolated in the Caching tab in the Mapping Workbench.
- Alternatively you can set a CacheInvalidationPolicy on your descriptor to ensure objects are not cached for longer than a specified time, or invalidated daily.
- Or to explicitly invalidate a deleted object use, session.getIdentityMapAccessor().invalidateObject() -
Apex 3.2 SVG Chart - How to plot Stacked Bar With Negative Values ?
Currently Apex 3.2 Flash Chart (AnyChart 3.x) does not support Stacked bars with negative values.
I try with SVG Stacked bars with positive values only, chart ploting works fine. When I add a new series with negative values (i.e -1) and I get a blank Chart region with no error.
Based on this statement from Apex's documentation:
*"AxisLine Indicates zero on charts that have negative values."*
I appreciate your help on how to translate this statement into action ?
(i.e how to override .Axisline class in CSS section ?)
Thank you very much for your time.User614143,
try to add the minumm negative value (but positive) to the parameter for the axis.
e.g. show value+3000 (assuming -3000 is the minimum value)
If you don't have a limitation for the negative values, it doesn't work. (or try to calculate first the most negative value in a before header process)
hope this helps.
Leo -
How to use bind variable in this select statement
Hi,
I have created this procedure where table name and fieldname is variable as they vary, therefore i passed them as parameter. This procedure will trim leading (.) if first five char is '.THE''. The procedure performs the required task. I want to make select statement with bind variable is there any possibility to use a bind variable in this select statement.
the procedure is given below:
create or replace procedure test(tablename in varchar2, fieldname IN varchar2)
authid current_user
is
type poicurtype is ref cursor;
poi_cur poicurtype;
sqlst varchar2(250);
THEVALUE NUMBER;
begin
sqlst:='SELECT EMPNO FROM '||TABLENAME||' WHERE SUBSTR('||FIELDNAME||',1,5)=''.THE ''';
DBMS_OUTPUT.PUT_LINE(SQLST);
OPEN POI_CUR FOR SQLST ;
LOOP
FETCH POI_CUR INTO THEVALUE;
EXIT WHEN POI_CUR%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(THEVALUE);
SQLST:='UPDATE '||TABLENAME|| ' SET '||FIELDNAME||'=LTRIM('||FIELDNAME||',''.'')';
SQLST:=SQLST|| ' WHERE EMPNO=:X';
DBMS_OUTPUT.PUT_LINE(SQLST);
EXECUTE IMMEDIATE SQLST USING THEVALUE;
END LOOP;
COMMIT;
END TEST;
Best Regards,So you want to amend each row individually? Is there some reason you're trying to make this procedure run as slow as possible?
create or replace procedure test (tablename in varchar2, fieldname in varchar2)
authid current_user
is
sqlst varchar2 (250);
thevalue number := 1234;
begin
sqlst := 'update ' || tablename || ' set ' || fieldname || '= ltrim(' || fieldname || ',''.'') where substr(' || fieldname
|| ',1,5) = ''.THE ''';
dbms_output.put_line (sqlst);
execute immediate sqlst;
end test;will update every row that satisfies the criteria in a single statement. If there are 10 rows that start with '.THE ' then it will update 10 rows.
Maybe you are looking for
-
Multiple Comboboxes with single instance of Array Collection
First off - thanks to everyone for their contributions. This forum provides a lot of good information. I'm stuck on a particular problem and I suspect I'm not thinking about the issue correctly. I'm developing a dynamic module that instantiates comp
-
How to find out what is the name of table/view is being maintained in IMG?
Gurus, Any general trick to find out what is the name of table/view is being maintained by a given IMG item while configuring? Thanks,
-
How do I created a transparent frosted glass look in InDesign CC?
I have a text box over an image and I set the fill to be black and 50% transparent but I would like to add a frosted glass look to it as well. I assumed there would be a gaussian blur effect under the FX menu but alas, there is none. So how else wou
-
Compiler error. Ivrt patch out of range: ofst=0xC547
Compiler error occured during full ATE run.
-
Dreamviewer cs4 code colouring not working
Hi.. All code colour in the source code looks as"black colour". i tried to fix it by changing the edit>preference>code colouring. but not working. can anybody help me thanks