Adding a UNIQUE CONSTRAINT to an existing column with duplicate values

Oracle Forums Hello, I have a table that contains rows 11 901. I tried to define the UNIQUE constraint on the column of xcode, but encountered an error: the column already contain duplicates! I rescued following SQL 'SELECT COUNT (*) FROM States;' the result is 11 901 and 'SELECT COUNT (DISTINCT (xcode)) FROM States;' the result is 11 680. So to enforce this unique key I have to remove the 221 lines. Please how can I do this?

REMOVE duplicates...

For example, as

delete from your_table t
where rowid <
   (
   select max(rowid)
   from your_table r
   where t.unique_column = r.unique_column);

Thne create the constraint.

Tags: Database

Similar Questions

  • I have a column with two values, separated by a space, in each line. How to create 2 new columns with the first value in a column, and the second value in another column?

    I have a column with two values, separated by a space, in each line. How do I create 2 new columns with the first value in one column and the second value in another column?

    Add two new columns after than the original with space separated values column.

    Select cell B1 and type (or copy and paste it here) the formula:

    = IF (Len (a1) > 0, LEFT (A1, FIND ("", A1) −1), ' ')

    shortcut for this is:

    B1 = if (Len (a1) > 0, LEFT (A1, FIND ("", A1) −1), ' ')

    C1 = if (Len (a1) > 0, Member SUBSTITUTE (A1, B1 & "", ""), "")

    or

    the formula of the C1 could also be:

    = IF (Len (a1) > 0, RIGHT (A1, LEN (A1) −FIND ("", A1)), "")

    Select cells B1 and C1, copy

    Select cells B1 at the end of the C column, paste

  • update of NULL in the column with the values of the adjacent column

    Examples of data

    with test_data as
    (select 1 as one, null as two, 2 as three,5 as four, 6 as five, null as six from dual
    union all
    select 1 as one, null as two, 2 as three,5 as four, 6 as five, null as six from dual)
    select * from test_data;
    

    This is one of those cases, the case may be where any value of a column can be null

    or two similar columns can be null. If the column is null then I want to update the adjacent column

    average value of the column, if the first column is null so I want to take the next non-null column and update, if the last column is null

    so I want to take prev not zero column and to update.

    In this case would be my expected output

    Un Two Three Four Five Six
    11.52566
    123566

    Prospects for the future the suggesion or advice.

    Or, using Analytics:

    SQL> with test_data (id, one, two, three, four, five, six) as (
      2    select 1, 1   , null, 2   , 5, 6, null  from dual union all
      3    select 2, 1   , null, 3   , 5, 6, null  from dual union all
      4    select 3, 1   , null, null, 5, 6, null  from dual union all
      5    select 4, null, null, null, 5, 6, null  from dual
      6  )
      7  select *
      8  from (
      9    select id
     10         , cell
     11         , case when next_nn is not null and prev_nn is not null
     12             then (next_nn + prev_nn)/2
     13             else nvl(next_nn, prev_nn)
     14           end val
     15    from (
     16      select id
     17           , cell
     18           , val
     19           , last_value(val) ignore nulls over(partition by id order by cell) as prev_nn
     20           , first_value(val) ignore nulls over(partition by id order by cell range between current row and unbounded following) as next_nn
     21      from test_data
     22      unpivot include nulls (val for cell in (one as 1, two as 2, three as 3, four as 4, five as 5, six as 6) )
     23    )
     24  )
     25  pivot ( min(val) for cell in (1 as "ONE", 2 as "TWO", 3 as "THREE", 4 as "FOUR", 5 as "FIVE", 6 as "SIX") )
     26  ;
    
            ID        ONE        TWO      THREE       FOUR       FIVE        SIX
    ---------- ---------- ---------- ---------- ---------- ---------- ----------
             1          1        1,5          2          5          6          6
             2          1          2          3          5          6          6
             3          1          3          3          5          6          6
             4          5          5          5          5          6          6
    
  • How to update columns with the value of other lines in the same table

    Hello

    I use Oracle 11.2, I'd use SQL statements to update a column based on values in other rows in the same table. Here are the details:

    create table TB_test (number 4 myId, crtTs date, date of MDPU);

    insert into tb_test (1, to_date ('20110101', 'YYYYMMDD'), null);
    insert into tb_test (1, to_date ('20110201', 'YYYYMMDD'), null);
    insert into tb_test (1, to_date ('20110301', 'YYYYMMDD'), null);
    insert into tb_test (2, to_date ('20110901', 'YYYYMMDD'), null);
    insert into tb_test (2, to_date ('20110902', 'YYYYMMDD'), null);

    After you run the SQL code, I would like to have the following result:

    1, 20110101, 20110201
    1, 20110201, 20110301
    1, 20110301, null
    2, 20110901, 20110902
    2, 20110902, null

    Thanks for your suggestion.

    I guess you need this, otherwise please explain logic correctly:

    SQL> merge into tb_test t
      2  using (
      3    select rowid as rid
      4         , lead(crtts) over(partition by myid order by crtts) as updts
      5    from tb_test
      6  ) v
      7  on (t.rowid = v.rid)
      8  when matched then update
      9   set t.updts = v.updts
     10  ;
    
    5 rows merged.
    
    SQL> select * from tb_test order by 1,2;
    
          MYID CRTTS     UPDTS
    ---------- --------- ---------
             1 01-JAN-11 01-FEB-11
             1 01-FEB-11 01-MAR-11
             1 01-MAR-11
             2 01-SEP-11 02-SEP-11
             2 02-SEP-11
    
  • Return only the columns with different values.

    Hi all

    I am trying to solve a seemingly trivial problem but can't seem to get any clear answer anywhere in any forum. Consider a single table with 5 columns and only two lines:
    row_id           first_name         last_name        age            gender
    1                    John                  doe               27             M
    1                    Jane                  doe               27              F  
    Assume that there is no primary key or any other constraint. Also assume that there are only and only two lines of this table. So I need basically a query that, overall above lines, would return first name and sex, because they are only different columns in two lines, as well as their values. Even if I can get sort of column names that are different and that would be enough that I can easily access the values later. It is also important to remember that I may not know the names of the columns in the columns, so basically, somehow, I use user_tab_columns in the process.

    Any help appreciated.

    Published by: 894302 on May 1, 2013 10:35

    Hello

    894302 wrote:
    The exact release could be just a varchar variable that lists all the columns that have different values with each column name separated by commas. We'll call the query you want as a QUERY. So, if I do something like

    Select the REQUEST of double; Output should be: 'first_name, equality of the sexes. Is this possible?

    In this case:

    SELECT     RTRIM ( DECODE (a.row_id,     b.row_id,     NULL, 'row_id,')     ||
                    DECODE (a.first_name, b.first_name, NULL, 'first_name,') ||
              DECODE (a.last_name,  b.last_name,  NULL, 'last_name,')  ||
              DECODE (a.age,        b.age,          NULL, 'age,')      ||
              DECODE (a.gender,     b.gender,     NULL, 'gender,')
               , ','
               )          AS different_columns
    FROM     rhit_table_x  a
    JOIN     rhit_table_x  b  ON  a.ROWID     < b.ROWID
    ;
    

    Output:

    DIFFERENT_COLUMNS
    ---------------------------------------
    first_name,gender
    

    This assumes that you have really a table, then you can use ROWID to distinguish the lines, since there is no primary key.
    If this isn't the case, you first assign ROW_NUMBER in a subquery.

  • column with the value of inputText update

    Hello

    I use jdev 11g

    I have table with salary of name of column and I called bonus text field entry

    I want to create button when clicking on it

    record everything in the table update (add) salary of which the value in the input text filed

    If you use ADF BC, generate a class of Application Module and to write the code needed to update the View object which is bound to the table.

    public void updateSalary() {}

    creating lines iterator to iterate through your point of view
    Employees of RowSetIterator = this.getEmployees () .createRowSetIterator (null);
    Employees.Reset ();

    iterate through your point of view
    While (employees.hasNext ()) {}
    Retrieves the line
    Employee of EmployeesRowImpl = (EmployeesRowImpl) employees.next ();
    update the salary by adding the bonus
    employee.setSalary (employee.getSalary () .add (employee.getBonus ()));
    }

    cleaning
    employees.closeRowSetIterator ();
    }

    There is the customer service of AOS to interface and create a method to it link in your page links.

    These two steps are declarative in JDeveloper.

    Finally build a listener for the action button and call the AM method you linked in the previous step.

    public static DCBindingContainer getBindingContainer() {}
    return (DCBindingContainer) JSFUtils.resolveExpression("#{bindings}");
    }

    It's the listener of the action that is performed when you click the button
    {} public void updateSalary (ActionEvent actionEvent)
    OperationBinding = operation
    getDCBindingContainer () .getOperationBinding ("updateSalary");
    Operation.Execute ();
    }

  • not able to see the column with missing values

    Hello world. For a few days, I'm not able to view column that only have missing values in excel using smartview. I checked the deleted column values are all Unflagged, as to remove the missing blocks in the smartview options.
    Maybe there's something else I have installation?

    Thank you

    After unflagging "Delete column" refreshing sheet wasn't enough. To make the active sheet active options must be closed. Options then work correctly in the new worksheet (in the same excel file).

  • The sum of a column with 2 values using Forms 6i

    Hello world
    I have 2 blocks, a main block and the other is
    my block of retail and my block of retail element is a list item
    When I have 2 options to choose, we're for described video and the
    Another is for delay.
    My question is:
    How can I add an item in my form where I will summarize the
    amount of A and L is inserted on this column?

    I forgot about it. DECODE cannot be used in SQL. This time I tried the solution myself in Forms 6i, so I know it works. Set the formulas

    InStr(:Item,'A')

    This returns 1 if the value is A, 0 otherwise. Ditto for the L value of course.

  • Fill two empty columns with the values in a column (all in the same table)

    Can someone point me in the right direction? I want to fill the column prefix and suffix with the AcctNum data.

    "Prefix is the part of the number before the '-' and the suffix is everything after the '-'. '. Write a SQL command to fill the column prefix and suffix.
    *Accounts* 
    
    AcctNum   Prefix   Suffix
    -------   ------   -------
    123-0097
    X089-056
    123-0097
    123-0098
    F3377-D
    X089-057
    X089-058
    3-009712
    It is supposed to look like this:
    *Accounts* 
    
    AcctNum   Prefix   Suffix
    -------   ------   -------
    123-0097    123     0097
    X089-056
    123-0097
    123-0098
    F3377-D
    X089-057
    X089-058
    3-009712
    That's what I came with, but it does not work because it is basically putting multiple values into a single cell:
    update accounts
         set prefix=(select substr(acctnum, 1, instr(acctnum,'-')-1) from accounts),
         suffix=(select substr(acctnum, instr(acctnum, '-')+1) from accounts)
         where acctnum=(select prefix||'-'||suffix from accounts);
    I want this query is incredibly easy and I have forget something. Any help is greatly appreciated.

    Published by: 885913 on September 18, 2011 12:53
    UPDATE accounts a
    SET    ( prefix, suffix ) = (SELECT Substr(acctnum, 1, Instr(acctnum, '-') - 1),
                                        Substr(acctnum, Instr(acctnum, '-') + 1)
                                 FROM   accounts b
                                 WHERE  a.acctnum = b.acctnum);
    
  • ORDER BY a column with NULL values only

    Hello

    The order of column has all null values for the results of my query set.

    Ex:

    Select a, b, c from table1 where type = 'type1' and ID = "id1" order by column1

    In the above query, "column1" contains nulls for 'type1 '. The order of the records in the result set is different for different ID values if the values of a, b and c are always the same.
    What is happening in the 10g database.

    I have also observed that the order of the records for the same query conforms in the 9i database.

    (1) is the difference due to the difference in versions of database?
    (2) is there a way to get the order even records independently entry ID?
    (3) I cannot in the same order in 10 g DB too as the order in 9i DB?

    Thank you.

    Hello

    Madhuri says:
    Hello

    The order of column has all null values for the results of my query set.

    Ex:

    Select a, b, c from table1 where type = 'type1' and ID = "id1" order by column1

    In the above query, "column1" contains nulls for 'type1 '. The order of the records in the result set is different for different ID values if the values of a, b and c are always the same.
    What is happening in the 10g database.

    I have also observed that the order of the records for the same query conforms in the 9i database.

    If two or more rows have the same values (or NULL) for each ORDER BY expressions, then you may not be sure what order they will be. The system is free to do whatever he finds convenient. What the system identifies Dresser can vary depending on many factors, including the version, the size of the table, the conditions in the WHERE clause, there is a GROUP BY clause, or not... In all cases, it is not something that you can depend on. If you want the output in a certain order, to specify the order in the ORDER BY clause.

    (1) is the difference due to the difference in versions of database?

    Could be. In all versions, Oracle said that you cannot count on the order being compatible, except if the ORDER BY clause, it is consistent.

    (2) is there a way to get the order even records independently entry ID?

    Add more expressions at the end of the ORDER BY clause, as tie-breakers.
    For example:

    ORDER BY  column1
    ,         a
    ,         b
    ,         c
    

    If table1 is really a table (not a view), you can add a ROWID.
    In most cases, you can ORDER BY expressions that are not in the SELECT clause. So if you have a primary key, you can usually ORDER BY it, even if you don't see it.

    (3) I cannot in the same order in 10 g DB too as the order in 9i DB?

    Of course, ORDER BY works the same in all versions. If you have an ORDER BY clause to unambiguously, the output will be exactly the same order in any version.
    Remember that the absence of ORDER BY has no effect in all versions. If you have an ORDER BY of ambiguous clause, you can not count on the coming out in a particular order in any version.

  • Filter a column with the value of another

    Hello. Hope someone can help with this... On my search page, I want to use the value of the first list/drop-down menu to filter the values of the second list/menu. I use PHP and DW 8.0.2.

    Example: The first column has each of the 50 States. second column has 3 000 counties. If a user selects New Jersey, I want to just 21 NJ counties to appear as options in the second menu downwards rather than 3 000 counties.

    First Recordset works very well for the States. But in my second recordset, I say 'select distinct County of the said County WHERE AS var1'... and var1 is $recordset1 [County]. But the 2 column is empty. How can I actively pass the value of the first column in the second while the user is still on the same page?

    Sandman

    >>
    Assuming that your table has a field named "State":
    «select County of States WHERE state = "var1""
    >>

    You can use this solution when the first menu page 1 and the second menu on page 2 (IE passing the value of a query on page 2), but as assumingly, you need to have this functionality within a single page, basic need based on a javascript solution 'drop-down menus of dynamic load' to load the menu2 - options "in situs.

    There is an extension for Dreamweaver stand alone for this on the site of Tecnorama , that also wants to work without the relationships between the tables, in other words, with the data in a table, which matches your scenario.

  • LINES in COLUMNS with different values for each column (after division)

    Hello
    I have a table called summary where I produced, month, value,.

    When I used select * tab, I get months jan, Feb, mar, Apr. I wrote a query to get the months(jan,feb,...) columns

    SELECTmax (DECODE(ROWNUM,1,month)) Column1
    + Max (decode(rowNum,2,month)) table Column2 +.

    as this up to 12 months
    After that, I want to get the NEWVALUE for each month.
    I wrote a query to get the value, but I get the value only for the first month, and for the rest, I get NULL values.

    Select max (DECODE(ROWNUM,2,vallue)) Column1, Column2 of max table (DECODE(ROWNUM,3,vallue))



    Is it possible to get the newvalues for each month (in sql only) if so, please help me

    Thank you
    Chand
  • Replace the empty column with ZERO values

    Hi experts,

    I'm building a report to display the number of orders per channel / day / hour.

    Since a few days one or several channels may not all orders placed against them in which case my report shows empty values in the report.

    Ideally, I would have zero in these columns rather than an empty cell.

    Sample Qry: -.

    Select
    Channel,
    Count (order_num) County
    Of
    SALES_ORDER

    Pls help!


    Thanks in advance.

    Count always returns 0 if no line found or the actual number based on the found rows. You don't even have to NVL them. I think so
    the problem is in your report layout, in my opinion.

    You run query sqlplus, or Toad or sqldevloper and you can see for yourself that the count is 0.

    See you soon.
    VIN.

  • Concatenate columns with distinct values from oracle

    Hello gurus,

    My gaze of structure of table as follows:

    TankListUS TankListCanada TankListIndia

    ----------           --------------              -------------

    T111 | T222 T444 | T222 T555

    Now when I run the query:

    Select (TL. TankListUS | '||'  || WLM TankListCanada | '||'  || WLM TankListIndia) as "OverallSummary" of TankListTL

    I get the output voltage

    T111 | T222 | T444 | T222 | T555

    But I do not need to duplicate tanks. I need my output like:

    T111 | T222 | T444 | T555

    Is this possible?

    Hello

    Try this

    with t1 as (select ' T111 | ") T222 | T444 | T222 | T555' double collar).

    T2 as (SELECT rownum, REGEXP_SUBSTR (col, ' [^ |] +', 1, RN) SPLIT)

    from t1

    cross join

    (SELECT ROWNUM RN

    FROM (SELECT (length (REGEXP_REPLACE (col, ' [^ |] +')) / 2) + 1 MAX_VALUE)

    from t1)

    connect by level<=>

    T3 as (select distinct split as the t2 dis_col)

    Select

    RTrim (xmlagg (xmlelement (e, dis_col |))) '||')). extract ('/ / text()'), ' |') d_col

    Of

    T3;

    Kind regards

    Mohan.

  • How to avoid duplicates on a column with condition

    Hi all

    I need some advice here. At work, we have an Oracle APEX application that allow the user to add new records with the decision of the increment automatic number based on the year and the group name.

    Said that if they add the first record, group name AA, for 2012, they get the decision number AA 1 2013 as their record casein displayed page of the report.

    The second record of AA in 2013 will be AA 2 2013.

    If we add about 20 records, it will be AA 20 2013.

    The first record for 2014 will be AA 1 2014.

    However, recently, we get a claim of the user on two files of the same name of group have the same number of the decision.

    When I looked in the history table and find that the time gap between 2 record is about 0.1 seconds.

    In addition, we have the correspondence table which allows the user admin update the sequence number start with the restraint that it must be greater than the maximum number of the current name of the current year.

    This boot sequence number and the name of the group is stored together in a table.

    And in some other case, the user can add a decision duplicate for related record number. (this is a new feature)

    The current logic of the procedure to add the new record on the application are

    _Get max record table with selected group name (decision_number) and the current year.

    _INSERT in the folder table the new record came with the decision to number + 1

    _ update sequence number of the number of the decision just added.

    So instead of utitlising the process of editing the built-in automatic table of the APEX, I write a procedure that combine all three processes.

    I have run some loop for continually perform this procedure, and it seems that it can generate autotically new decision unique number with time about 0.1 second difference.

    However, when I increase the number of entry to 200 and let two users run 100 each.

    If the time gap is about 0.01 second, double decision numbers are displayed.

    What can I do to prevent duplicate?

    I can't just apply a unique constraint here for three columns with condition because it can be duplicated in some special conditions. I don't know much about the use of lock and its impact.

    This is the content of my procedure

    create or replace

    PROCEDURE add_new_case)

    -ID just use the trigger

    p_case_title IN varchar2,

    p_year IN varchar2,

    p_group_name IN VARCHAR2,

    -decisionnumber here

    p_case_file_number IN VARCHAR2,

    -active

    p_user in VARCHAR2

    )

    AS

    NUMBER default_value;

    caseCount NUMBER;

    seqNumber NUMBER;

    previousDecisionNumber NUMBER;

    BEGIN

    -execution immediate q '[alter session set nls_date_format = "dd/mm/yyyy"]';

    SELECT count (*)

    IN caseCount

    OF CASE_RECORD

    WHERE GROUP_ABBR = p_group_name

    AND to_number (to_char (create_date, "yyyy")) = to_number (to_char (date_utils.get_current_date, "yyyy"));

    SELECT max (decision_number)

    IN previousDecisionNumber

    OF CASE_RECORD

    WHERE GROUP_ABBR = p_group_name

    AND to_number (to_char (create_date, "yyyy")) = to_number (to_char (date_utils.get_current_date, "yyyy"));

    IF p_group_name IS NULL

    THEN seqNumber: = 0;

    ON THE OTHER

    SELECT Seq_number INTO seqNumber FROM GROUP_LOOKUP WHERE ABBREVIATION = p_group_name;

    END IF;

    IF caseCount > 0 THEN

    default_value: largest = (seqNumber, previousdecisionnumber) + 1;

    ON THE OTHER

    default_value: = 1;

    END IF;

    INSERT INTO CASE_RECORD (case_title, decision_year, GROUP_ABBR, decision_number, case_file_number, active_yn, created_by, create_date)

    VALUES (p_case_title, p_year, p_group_name, default_value, p_case_file_number, 'Y', p_user, sysdate);

    -Need to update the sequence here also

    UPDATE GROUP_LOOKUP

    SET SEQ_NUMBER = default_value

    WHERE the ABBREVIATION = p_group_name;

    COMMIT;

    EXCEPTION

    WHILE OTHERS THEN

    Logger.Error (p_message_text = > SQLERRM)

    , p_message_code = > SQLCODE

    , p_stack_trace = > dbms_utility.format_error_backtrace

    );

    LIFT;

    END;

    Many thanks in advance,

    Ann

    It's easier to solve for the case, while p_group_name is not null. In this case, you update a GROUP_LOOKUP line, so that you can select to update this line at the beginning, to prevent cases of two for the same group added at the same time. To do this, change the selection of GROUP_LOOKUP to:

    SELECT Seq_number INTO seqNumber FROM GROUP_LOOKUP WHERE ABBREVIATION = p_group_name for an updated VERSION OF the SEQ_NUMBER;

    and move this to be the first thing that did the procedure - before it has CASE_RECORD lines.

    In the case when p_group_name is set to null, you have some object to be locked. I think the best you can do is to lock the entire table GROUP_LOOKUP:

    the table lock in exclusive mode GROUP_LOOKUP wait 100;

    The '100 expectation' means that he will wait until 100 seconds before giving up and trigger an error. in practice, that is expected to only wait a moment.

    Exclusive mode allows others to read, but not to update the table.

    UPDATES and the LOCK of the TABLE will be updates of other sessions wait for this transaction to validate. Queries from other sessions are not affected.

    The locks are released when you commit or roll back.

Maybe you are looking for

  • Access point: access to personal data?

    Hello everyone. I have a question: if I share my hotspot iphone with someone, that person has access to my data?

  • Cannot sync the playlist to watch

    I have a Apple Watch and an iphone 6 more and I know that you can sync a playlist to your watch, so you can listen to music without your phone. Having music Bluetooth headset and apple, but when I follow the steps and get to the "music > playlist syn

  • Presentation settings is missing from the Windows Mobility Center

    Satellite L 300 with Vista Home Basic Recently installed everything, but have run windows update etc. Since then. Presentation settings does not appear in the Windows Mobility Center, and I can not find presentationsettings.exe anywhere on the comput

  • My Sony grand wega tv led flashes green continuously

    I came home yesterday and turned on my Sony Grand Wega and the fan to start on but there is no sound or picture. The power/standby light flashes green continuously

  • loading of vi with operator interface

    When I load a movie file with my operator interface, I always get a message that the vi is already in memory. When I close LV in taskmanager and load the sequence once again, the error has disappeared also. Is this a configuration problem? Because my