Sql query writing best practises

HI forum,
Any body is having a tutorial on sql query writing best practises...pls share with me
Thanks

For example:
[url http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/toc.htm]Oracle Database Performance Tuning Guide 10g Release 2 (10.2)
[url http://people.aapt.net.au/roxsco/tuning/]Oracle SQL Tuning Guide
Gints Plivna
http://www.gplivna.eu

Similar Messages

  • SQL query writing limit exceeded.

    Hi,
    My query contains 1700 lines and the report builder query writen provide line maximum line limit is 1615. When i paste the query in SQL area of report builder, Its paste the 1615 lines and remaining lines cutoff.Its provide the facility to type the query but not to paste the query further. According to the Scenario i cant able to create the view.So please tell me how can i handle it.
    Thanks.

    Does the query really have to be that big?
    I suspect a query of that size would be almost impossible to maintain or debug, assuming the performance is ok.
    I would suggest that you review the query to see if there are some parts which could be separated out into formula columns, or possibly split the query up - maybe if the report has a number of groups you could break it up that way.
    Generally when you hit an issue of this sort it is best to make your code fit the tools rather that the other way round.

  • Optimalization, tunig pl/sql query, the best knowledge source.

    hello,
    I'm finding the best informaton about good practice in Oracle, all about Optimalization, tunig pl/sql. Can you help me?
    ths
    Edited by: adamkutera on 2010-04-21 12:11

    Dear adamkutera,
    The BEST documentation (including optimization, do&donts, tuning tips etc) is the Oracle documentation.
    No other documentation is as up-to-date and current as Oracle's documentation.
    They can be found at...
    http://www.oracle.com/technology/documentation/index.html
    and
    http://tahiti.oracle.com/
    Specifically for performance tuning...
    http://download.oracle.com/docs/cd/B14117_01/server.101/b10752/toc.htm
    vr
    Sudhakar B.

  • NEED SQL QUERY writing help

    oracle 10g.
    os : linux
    table data appears like this
    SQL> select * from test_grp;
    COL1 COL2
    aaa 111
    aaa 444
    aaa 222
    bbb 333
    bbb 555
    SQL> select * from test_grp order by 2;
    COL1 COL2
    aaa 111
    aaa 222
    bbb 333
    aaa 444
    bbb 555
    As per my application requirement I need to seggerage the data as
    follows
    aaa (2) ie --- 111,222
    bbb(1) is --- 333
    aaa(1) is --- 444
    bbb(1) is -- 555
    I am not able to frame this. Any help ?

    SQL> create table test_grp
      2  as
      3  select 'aaa' col1, 111 col2 from dual union all
      4  select 'aaa', 444 from dual union all
      5  select 'aaa', 222 from dual union all
      6  select 'bbb', 333 from dual union all
      7  select 'bbb', 555 from dual
      8  /
    Tabel is aangemaakt.
    SQL> select col1
      2       , col2s
      3    from ( select col1
      4                , rtrim(col2s,',') col2s
      5                , rn
      6                , sumn
      7             from ( select col1
      8                         , col2
      9                         , sum(n) over (order by col2) sumn
    10                      from ( select col1
    11                                  , col2
    12                                  , case when col1 = lag(col1) over (order by col2) then 0 else 1 end n
    13                               from test_grp
    14                           ) t
    15                  )
    16            model
    17                  partition by (sumn)
    18                  dimension by (row_number() over (partition by sumn order by col2) rn)
    19                  measures (col1, cast(col2 as varchar2(100)) col2s)
    20                  rules
    21                  ( col2s[any] order by rn desc = col2s[cv()] || ',' || col2s[cv()+1]
    22                  )
    23         )
    24   where rn = 1
    25   order by sumn
    26  /
    COL COL2S
    aaa 111,222
    bbb 333
    aaa 444
    bbb 555
    4 rijen zijn geselecteerd.Regards,
    Rob.

  • JComboBox or JList with SQL queries. Best practises.

    Hi!
    I'm wondering what you do in the following situation, providing you develop a hotel reservation application and you have a form where you enter room details: room number, number of rooms, description and type (JComboBox).
    So when executing an INSERT query what do you usually do? Do you store ID's of types or execute addtion SELECT query to get the if of the selected type?

    Thank you very much! I like your approach, but what if I should fill in a form automatically? I mean I have a section in my application where you can edit rooms, you choose a room from a JList and fter clicking on a particular room, the fields of the form get entered and if I have a JComboBox there what should I do?
    I use this approach:
    <code>
    public void valueChanged ( ListSelectionEvent e )
    Item item = ( Item ) lRooms.getSelectedValue();
    try {
    Db db = new Db ();
    ResultSet rs = db.executeQuery ( "SELECT * FROM rooms " +
    "WHERE id = " + item.getId () );
    rs.next ();
    pRoomsEdit.this.id = rs.getInt ( "id" );
    tfNo.setText ( item.getName () );
    ComboBoxModel cbm = cbType.getModel ();
    ResultSet rsType = db.executeQuery ( "SELECT name FROM types " +
    "WHERE id = " + rs.getString ( "type" ) );
    rsType.next ();
    cbm.setSelectedItem ( new Item ( rs.getInt ( "id" ), rsType.getString ( "name" ) ) );
    tfRoomNum.setText ( rs.getString ( "roomNum" ) );
    taDesc.setText ( rs.getString ( "description" ) );
    catch ( SQLException se ) {
    se.printStackTrace ();
    </code>

  • Best way to spool DYNAMIC SQL query to file from PL/SQL

    Best way to spool DYNAMIC SQL query to file from PL/SQL [Package], not SqlPlus
    I'm looking for suggestions on how to create an output file (fixed width and comma delimited) from a SELECT that is dynamically built. Basically, I've got some tables that are used to define the SELECT and to describe the output format. For instance, one table has the SELECT while another is used to defined the column "formats" (e.g., Column Order, Justification, FormatMask, Default value, min length, ...). The user has an app that they can use to customize the output...which leaving the gathering of the data untouched. I'm trying to keep this formatting and/or default logic out of the actual query. This lead me into a problem.
    Example query :
    SELECT CONTRACT_ID,PV_ID,START_DATE
    FROM CONTRACT
    WHERE CONTRACT_ID = <<value>>Customization Table:
    CONTRACT_ID : 2,Numeric,Right
    PV_ID : 1,Numeric,Mask(0000)
    START_DATE : 3,Date,Mask(mm/dd/yyyy)The first value is the kicker (ColumnOrder) as well as the fact that the number of columns is dynamic. Technically, if I could use SqlPlus...then I could just use SPOOL. However, I'm not.
    So basically, I'm trying to build a generic routine that can take a SQL string execute the SELECT and map the output using data from another table to a file.
    Any suggestions?
    Thanks,
    Jason

    You could build the select statement within PL/SQL and open it using a cursor variable. You could write it to a file using the package 'UTL_FILE'. If you want to display the output using SQL*Plus, you could have an out parameter as a ref cursor.

  • What is the best way to Optimize a SQL query : call a function or do a join?

    Hi, I want to know what is the best way to optimize a SQL query, call a function inside the SELECT statement or do a simple join?

    Hi,
    If you're even considering a join, then it will probably be faster.  As Justin said, it depends on lots of factors.
    A user-defined function is only necessary when you can't figure out how to do something in pure SQL, using joins and built-in functions.
    You might choose to have a user-defined function even though you could get the same result with a join.  That is, you realize that the function is slow, but you believe that the convenience of using a function is more important than better performance in that particular case.

  • Send SQL query or call stored procedure, which is best???

    hello experts!!
    i would like to ask what will be the best implementation on querying a database using Java, send a SQL query(insert into table values...) or call stored procedure(just pass parameters)?? and also in stored procedure does "autoCommit/rollback" applies/make sense??

    I searched google for this:
    Stored Procedures vs. SQL
    and found this useful link:
    http://www.karlkatzke.com/stored-procedures-vs-sql-calls/
    I thiink you should also read up on other articles based on such google searches
    to get other opinions. Also, read the links provided by that article.
    Personnally, I think stored procedures should be avoided unless there is a definite
    advantage as specified in the above article. Especially not used for CRUD operations.
    Also, no matter where you put the SQL, it should be documented. I've seen too many stored procedures that aren't documented.

  • Having trouble writing to a database although SQL query is correct

    Hi there. I am trying to write an sql query to a database but I am failing to understand what is going wrong in terms of executing the query.
    I have the following code.
    static public int writeToStockTable (String suppIn, String nameIn, String typeIn, float quantIn, float priceIn, String descIn, String styleIn, String finishIn)         {               // Temporary variable to hold the SQL query               String SQLString, SQLString2;               ResultSet rs = null;                                     // Build a string containing the SQL INSERT instruction to be used later             SQLString = "INSERT INTO "+typeIn+" VALUES ('1', '" + suppIn + "', '" + nameIn + "', " + quantIn + ", " + priceIn + ", '"+descIn+"', '"+styleIn+"', '"+finishIn+"')";             SQLString2 = "SELECT Name FROM Suppliers WHERE Name = '" + suppIn + "'";                                         try                   {                         // The createStatement() method creates a Statement object.  Object will be                         // attached to my reference variable (statement) defined at the top of class.                         statement = connectionToBellFiresDB.createStatement();                                                 // The executeUpdate() statement can be used here to execute an                         // SQL INSERT instruction.                         rs = statement.executeQuery (SQLString2);                         if ((rs == null))                         {                             System.out.println ("Trying to say no supplier");                             return (-2);                         }                                                 else                         {                             System.out.println (SQLString);                             statement.executeUpdate (SQLString);                         }                                           }                 catch (SQLException exception)                   {                       return (-1);    // Return -1 if problem writing record to file                   }                             return (0);  // Return with 0 if record successfully written                       }
    Please ignore the attributes not used, it is very much a work in progress. The command that prints SQLString prints
    INSERT INTO Fireplace VALUES ('1', 'a', 'a', 1.0, 1.0, 'a', 'a', 'a')
    which is correct, but will return the error code -1 when asked to execute the query. The database jdbc:odbc driver has been initialised in the control panel and the program has no other problems accessing the database as far as i am aware.
    Any help would be appreciated, i hate database connections :)

    Chrift wrote:
    Im sorry i dont know what you mean by eating the exception, im quite a noob at programming to be honest!
    How do i print it out and what is a stack trace?Do you know what an exception is? If not, then you should stay far away from JDBC/Database programming for the time being.
    Read [the Exception Tutorial|http://java.sun.com/docs/books/tutorial/essential/exceptions/] first.
    Then: an exception has quite a bit of useful information attached that tells you what went wrong.
    In your case you catch the exception and ignore everything it could tell you by simply returning -1. Returning 0 and -1 to indicate success/failure is a very bad idea and should not be used in Java code, it's a C-style convention for C-era programming languages. In Java you use exceptions instead.
    For starters you could simply add "exception.printStackTrace()" in your catch-block to get some more information out of the exception.

  • Best practise BW Query design for Crystal Reports integration

    Hi all,
    I am looking for a guide on best practices when designing a BW Query to be used as data foundation for a Crystal Report.
    The scenario is that I am responsible for developing the Crystal Reports part, but not the BW Query part, therefore I would like to provide a list of best practises to the person who is responsible for the Query, this way make sure that the integration will work as good as possible. The setup is of course using BO Integration Kit for SAP.
    An example is how to use authorization variables in the query to provide data security. This is just one example, there are problably a number of other things to be aware of. A document containing suggestions for best practices is what I am looking for, or if the document does not exist, input to what should be on such a list.
    Thank you in advance.
    Regards,
    Rasmus

    Hi Rasmus,
    in regards to the Best Practices for Crystal Reports you can leverage all the knowledge you have on the Query Design today already. if you not the person for designing the query I think it is important to make sure people designing the queries do understand how Crystal Reports is leveraging the elements from the BI Query.
    /people/ingo.hilgefort/blog/2008/02/19/businessobjects-and-sap-part-2
    You should try to put as much as possible into the BI query from the logic point of view.
    and you can also build common BI queries - there is no need to build a BI query for each report.
    ingo

  • SQL protection - best practises

    I need some help to understand the difference between Express full backup vs. syncronization for SQL protection. I have always thought that the SQL logs were truncated during a Express full backup, but have read several articles that claim the opposite.
    What is best practise in order to protect SQL DB's in general? And which recovery models should be used (full/simple)?
    /Amir

    Please read below
    Backing up SQL with DPM
    Why DPM 2010 and SQL are Better Together?
    SQL Logs not getting truncated ?
    (comments)
    SCDPM: Backup SQL and Truncate SQL Logs
    Have a nice day !!!
    DPM 2012 R2: Remove Recovery Points

  • Problem writing a sql query for a select list based on a static LOV

    Hi,
    I have the following table...
    VALIDATIONS
    ID          Number     (PK)
    APP_ID          Number     
    REQUESTED     Date          
    APPROVED     Date          
    VALID_TIL     Date
    DEPT_ID          Number     (FK)
    I have a search form with the following field item variables...
    P11_DEPT_ID (select list based on dynamic LOV from depts table)
    P11_VALID (select list based on static Yes/No LOV)
    A report on the columns of the Validations table is shown based on the values in the search form. So far, my sql query for the report is...
    SELECT v.APP_ID,
    v.REQUESTED,
    v.APPROVED,
    v.VALID_TIL,
    d.DEPT
    FROM DEPTS d, VALIDATIONS v
    WHERE d.DEPT_ID = v.DEPT_ID(+)
    AND (d.DEPT_ID = :P11_DEPT_ID OR :P11_DEPT_ID = -1)
    This query works so far. My problem is that I don't know how to do a search based on the P11_VALID item - if 'yes' is selected, then the VALID_TIL date is still valid. If 'no' is selected then the VALID_TIL date has passed.
    Can anyone help me to extend my query to include this situation?
    Thanks.

    Hello !
    Let's have a look at my example:create table test
    id        number
    ,valid_til date
    insert into test values( 1, sysdate-3 );
    insert into test values( 2, sysdate-2 );
    insert into test values( 3, sysdate-1 );
    insert into test values( 4, sysdate );
    insert into test values( 5, sysdate+1 );
    insert into test values( 6, sysdate+2 );
    commit;
    select * from test;
    def til=yes
    select *
      from test
      where decode(sign(trunc(valid_til)-trunc(sysdate)),1,1,0,1,-1)
           =decode('&til','yes',1,-1);
    def til=no
    select *                                                                               
      from test                                                                            
      where decode(sign(trunc(valid_til)-trunc(sysdate)),1,1,0,1,-1)
           =decode('&til','yes',1,-1);  
    drop table test;  It's working fine, I've tested it.
    The above changes to my first idea I did because of time portion of the DATE datatype in Oracle and therefore the wrong result for today.
    For understandings:
    1.) TRUNC removes the time part of DATE
    2.) The difference of to date-values is the number of days between.
    3.) SIGN is the mathematical function and gives -1,0 or +1 according to an negative, zero or positiv argument.
    4.) DECODE is like an IF.
    Inspect your LOV for the returning values. According to my example they shoul be 'yes' and 'no'. If your values are different, you may have to modify the DECODE.
    Good luck,
    Heinz

  • Writing a function to find whether a value is present in a sql query output

    Hi gurus,
    I would like to write a function to which i will pass a value and a sql query as parameters.
    Now the function needs to execute that sql query and find whether the given value is present in the output list
    when the query is executed. If it is present it should return 'T' otherwise 'F'
    My function will look like
    CREATE FUNCTION CHECK_VALUE(VALUE VARCHAR2,V_SQL VARCHAR2) RETURN VARCHAR2
    SELECT CHECK_VALUE('Dallas','SELECT LOCATION_CODE FROM HR_LOCATIONS')
    It should check whether the value 'Dallas' is present in the output list returned by the sql query.
    Any help will be appreciated.
    Thank you.

    CREATE OR REPLACE
      FUNCTION CHECK_VALUE(
                           VALUE VARCHAR2,
                           V_SQL VARCHAR2
        RETURN VARCHAR2
        IS
            RETVAL VARCHAR2(4000);
            REFCUR SYS_REFCURSOR;
        BEGIN
            OPEN REFCUR FOR V_SQL;
            LOOP
              FETCH REFCUR INTO RETVAL;
              EXIT WHEN REFCUR%NOTFOUND;
              IF RETVAL = VALUE
                THEN
                  CLOSE REFCUR;
                  RETURN 'T';
              END IF;
            END LOOP;
            CLOSE REFCUR;
            RETURN 'F';
    END;
    Function created.
    SQL> SET SERVEROUTPUT ON
    SQL> EXEC DBMS_OUTPUT.PUT_LINE(CHECK_VALUE('DALLAS','select loc from dept'));
    T
    PL/SQL procedure successfully completed.
    SQL> EXEC DBMS_OUTPUT.PUT_LINE(CHECK_VALUE('PARIS','select loc from dept'));
    F
    PL/SQL procedure successfully completed.
    SQL> SY.

  • Need help writing sql query

    i am trying to write sql query for a single recordset.
    I have an items table with all the standard item info and an item_colorID.
    i have a color_lookup table with 2 columns, item_colorID and color_ID
    i have a colors table with 2 columns, color_ID and color
    i want to join the tables and filter it so that a repeat region shows dynamic data of item name, description, thumb, price
    and also a list/menu dynamically populated by color
    filtered so that each item shows in the list/menu only the colors that the item has available.
    i have tried different variations of this sql
    SELECT * FROM items INNER JOIN color_lookup ON color_lookup.item_colorID = items.item_colorID INNER JOIN colors ON colors.color_ID = color_lookup.color_ID WHERE items.itemCatID = 3 ORDER BY items.itemName
    but the list/menu shows every color choice multiplied by the number of items in that color
    ie  White will show 80+ times.
    thanks for your help,
    jim balthrop

    bregent,
    thanks for your help.
    I am building a shopping cart and i have a recordset to list the items and a repeat region for that recordset
    i have a second recordset for the colors joined to the item_colorID nested inside the repeat region.
    the shopping cart software has a 'lookup from recordset' choice for the add to cart servior behavior
    and then i bind to the columns on the cart page.
    it produces this code
    if (isset($totalRows_rs_itemscat3) && $totalRows_rs_itemscat3 > 0)    {
        $row_rs_itemscat3 = WAEC_findRecordMySQL($rs_itemscat3, "item_ID", $ATC_itemID);
        if ($row_rs_itemscat3)    {
          $ATC_itemName = "".$row_rs_itemscat3['itemName']  ."";// column binding
          $ATC_itemDescription = "".$row_rs_itemscat3['itemShortDesc']  ."";// column binding
          $ATC_itemWeight = floatval("".$row_rs_itemscat3['itemWeight']  ."");// column binding
          $ATC_itemQuantity = "".$_POST["Farrington_1_Quantity_Add"]  ."";// column binding
          $ATC_itemPrice = floatval("".$row_rs_itemscat3['itemPrice']  ."");// column binding
          $ATC_itemThumbnail = "".$row_rs_itemscat3['itemThumb']  ."";// column binding
          $ATC_itemcolorchoice = "".$row_rs_colors['color']  ."";// column binding
          mysql_data_seek($rs_itemscat3, 0);
          $row_rs_itemscat3 = mysql_fetch_assoc($rs_itemscat3);
    the column binding for the colors is from a different recordset and when redirecting to the cart page the color info will not show.
    So my thinking is if i could get the color list/menu to populate from the same recordset as the item listing, it would solve my add to cart server behavior.
    Is it possible to do this with only one recordset?
    the products page and the cart page can be seen
    http://www.farrington-enterprises.com/rain-gutters.php
    add an item to the cart with any color choice and the color info does not carry to the cart.

  • Calculations Using SQL Query

    Hi All,
    I am using Oracle Database Version 11.2.
    I have a formula (A-B)/[(A-B)/10]. The tables that are holding the rows for this calculations are given below:
    ROWS_TAB
    ====== ===================
    Row          Amount
    ====== ===================
    A            5000
    B            -5000
    FORMULA_TAB
    ======== =========== ======== =============
    | ROW#  | Operator            | ROW        |   CONSTANT   |
    ======== =========== ======== =============
    | 10        |     E                   |      A       |                         |
    | 20        |     -                    |     B        |                         |
    | 30        |     E                   |      A       |                         |
    | 40        |     -                    |     B        |                         |
    | 50        |     /                    |               |      10                |
    | 60        |    /                     |               |                          |
    ======== =========== ======== =============
    The operator E starts a new calculation. The above formula has two sub-expressions thereby the table has two rows with E. Minus denoted by -, Plus denoted by +, Multiply denoted by *, and Division denoted by /.
    I want to write single SQL query to perform this calculation. Is it achievable in SQL?
    The scripts used to generate the tables are as below:
    create table ROWS_TAB
    (row_name VARCHAR2(1),
    amount NUMBER);
    create table FORMULA_TAB
    (row# NUMBER,
    operator VARCHAR2(1),
    row_name VARCHAR2(1),
    constant NUMBER);
    INSERT INTO ROWS_TAB VALUES('A', 5000);
    INSERT INTO ROWS_TAB VALUES('B', -5000);
    INSERT INTO FORMULA_TAB VALUES(10, 'E','A',null);
    INSERT INTO FORMULA_TAB VALUES(20, '-','B',null);
    INSERT INTO FORMULA_TAB VALUES(30, 'E','A',null);
    INSERT INTO FORMULA_TAB VALUES(40, '-','B',null);
    INSERT INTO FORMULA_TAB VALUES(50, '/','',10);
    INSERT INTO FORMULA_TAB VALUES(60, '/','','');
    Can anyone help in writing SQL query....
    Thanks in advance
    Best Regards
    Bilal

    As Frank said, it would be much easier to simply input the formula. Then, assuming you have OLAP option:
    variable formula varchar2(30)
    exec :formula := '(A-B)/((A-B)/10)';
    with t as (
               select  *
                 from  rows_tab
                 model
                   dimension by(row_number() over(order by row_name) r)
                   measures(
                            row_name,
                            amount,
                            count(*) over() cnt,
                            cast(:formula as varchar2(4000)) formula
                   rules(
                         formula[any] order by r = replace(nvl(formula[cv() - 1],formula[cv()]),row_name[cv()],amount[cv()])
    select  :formula || ' = ' || dbms_aw.eval_number(formula) result
      from  t
      where r = cnt
    RESULT
    (A-B)/((A-B)/10) = 10
    SQL>
    And if you do not have OLAP, you could use xquery:
    with t as (
               select  *
                 from  rows_tab
                 model
                   dimension by(row_number() over(order by row_name) r)
                   measures(
                            row_name,
                            amount,
                            count(*) over() cnt,
                            cast(:formula as varchar2(4000)) formula
                   rules(
                         formula[any] order by r = replace(nvl(formula[cv() - 1],formula[cv()]),row_name[cv()],amount[cv()])
    select  :formula || ' = ' || xmlquery(replace(formula,'/',' div ') returning content) result
      from  t
      where r = cnt
    RESULT
    (A-B)/((A-B)/10) = 10
    SQL>
    SY.

Maybe you are looking for

  • Doesn't seem to play podcasts after 1.02 update.

    My shuffle doesn't seem to be able to play podcasts after the 1.02 update. I drag songs onto the shuffle in iTunes and it loads. The playlist for the shuffle says the podcast file is on there. I disconnect the shuffle and hit play. The light blinks b

  • How to send a  mail to outlook   from iphone flex 4.5.1 app automatically..?

    HI folks,                  i have to send a mail to outlook for correpanding mailler id  with out  opeing  outlook  from my app(iphonoe flex 4.5.1 app.) with taking the input values what ever  we have given as input those values has to be send to out

  • How much HD space do I have left?

    According to "Macintosh HD Info" my PB's HD has a capacity of 93.04 GB, 75.22 GB of which is used. Problem is, I'm the only user and my home folder is listed as being 49.44 GB in size. That's a 25 GB desparity, which seems like a lot, no? When I add

  • SORT ARE SIZE

    SORT operations are performed in temporary segments, then why SORT_AREA_SIZE is required? regards wire

  • Images distorted on animation in Spry Sliding Panels

    I have a site here  using a set of sliding panels. It looks okay, but when the panels are animated the image on the left is momentarily stretched right across the panel covering the text, then snapping back into place once the animation stops. It's a