Find the minimum or maximum value across several columns?

SELECT max(c) FROM (SELECT col1 AS c FROM t1 UNION SELECT col2 AS c FROM t1) AS t2

case when Col1 < Col2 then Col1 else Col2 end as NewCol How can I selet rows which have 2 columns values cross equal?
SELECT, t1.a, t1.b FROM test t1, test t2 WHERE t1.a = t2.b AND t1.b = t2.a ORDER BY;

List all customers from table customers that haven't made any order during year 2005?
SELECT c.firstname, c.lastname, c.address FROM customers c WHERE NOT IN (SELECT o.customer_id FROM orders o WHERE year(o.order_date) = 2005)

List all customers who ordered products where price of the item is $100 greater than average order?
SELECT, c.firstname, c.lastname FROM customers c INNER JOIN orders o ON c.customer_id = c.customer_id WHERE o.price > (SELECT AVG(o.price) + 100 FROM orders o)

List all customers whose name is present more than once in the table?.SELECT count(*), name
FROM customers GROUP BY name HAVING (count(*)>=2)

Create a third row that make the sum of past row + current row (i.e. a running sum)?.

SELECT t2.week,, sum( FROM MY_TABLE T1, MY_TABLE T2 WHERE T1.WEEK <=t2.week GROUP BY t2.week, ORDER BY t2.week ASC

List all results except the biggest?

How to declare Composite Keys?
ALTER TABLE tablename ADD CONSTRAINT constraint_name PRIMARY KEY (attribute1,attribute2)

How to pull data from several tables that follows a pattern? Oracle provides Dynamic SQL facilities that would be the basis for a solution. The main points: 1. You create a "for ... loop ... end loop" to iterate over the table names that follow the pattern. 2. Inside the loop (for each table) you append a sql "select ..." text to form a union of the data in all tables. 3. At the end you execute the constructed sql text. There can be variations of this solution. You could use the "execute immediate .." construct or the dbms_sql facility. Or, instead of concatenating, inside the loop you could actually execute the single-table sql.
FOR t IN (SELECT object_name FROM user_objects WHERE object_type='TABLE' AND object_name LIKE 'ex_%') loop ... end loop

Query a table using data in another table?
SELECT * FROM table1 WHERE Salary=(SELECT salary FROM Salaries WHERE SalaryType="Manager")

Do two joins in a single query?
SELECT, (SELECT name FROM people WHERE id=projects.developer) AS "developer",

(SELECT name FROM people WHERE id=projects.requestor) AS "requestor" FROM projects

Columns to Rows

Transforming columns into rows is easily accomplished with the SELECT command's UNPIVOT clause, introduced in Oracle 11g.
select key, source, val from t UNPIVOT INCLUDE NULLS ( VAL FOR( SOURCE ) IN ( C1 AS 'C1', C2 AS 'C2', C3 AS 'C3' ) ) order by key, source ;

displaying a group by and grand total all on one line? Below is more conceptual than actual code since I'm in a big rush right now, but I believe the quickest way to obtain results for you would be a subselect. Using a subselect would allow you total without grouping by all the other columns that would force the group by. SELECT sum(TABLE1.COLUMN1), TABLE1.INDEXCOLUMN, TABLE1.SOMEOTHERDATA, TABLE2.GRANDTOTAL FROM TABLE1, ( SELECT sum(TABLE1.COLUMN1) AS "GRANDTOTAL", FROM TABLE1 ) TABLE2 WHERE... GROUP BY TABLE1.INDEXCOLUMN, TABLE1.SOMEOTHERDATA, null AS GRANDTOTAL
How to retrieve records which the date column should be 36 months older than the current date?
SELECT * FROM dates_table WHERE date_column < (current_date - interval 3 year)

How to find second highest value of a column in a table?
SELECT TOP 1 quantity FROM Trade WHERE quantity < (SELECT MAX(quantity) ORDER BY quantity DESC; FROM Trade)

SELECT quantity FROM Trade WHERE

FROM Trade WHERE quantity=(SELECT MAX(quantity) quantity<> (SELECT MAX(quantity) FROM Trade))

How to find second highest value of a column in a table? | SQL? Consider the following data: score player #1 100 Alex #2 100 Bob #3 98 Toto ... #9 20 Lilirtyry
SELECT score,player FROM scores WHERE score=(SELECT max(score) FROM scores WHERE score< (SELECT max(score) FROM scores));

How to find second highest value of a column in a table? | SQL?
SELECT min(empmarks ) FROM emp WHERE empmarks IN (SELECT top 3 empmarks FROM emp ORDER BY empmarks DESC)

How do I find out which columns are foreign keys in a table?
SELECT Parent.TABLE_NAME Parent_TABLE, Parent.CONSTRAINT_NAME Parent_CONSTRAINT, RTRIM(Child.TABLE_NAME) Child_TABLE, atc.comments AS Table_Desc, Child.CONSTRAINT_NAME Child_CONSTRAINT, RTRIM(col.COLUMN_NAME) AS Child_Col, col.POSITION AS Child_Col_Position ,CHILD.Delete_Rule, CHILD.STATUS FROM All_CONSTRAINTS Child, All_CONSTRAINTS Parent, sys.all_tab_comments atc, ALL_CONS_COLUMNS col WHERE Child.R_CONSTRAINT_NAME = Parent.CONSTRAINT_NAME AND Child.TABLE_NAME != Parent.TABLE_NAME AND Parent.TABLE_NAME = upper('&Parent_Table_Name') AND Child.owner = atc.Owner(+) AND Child.TABLE_NAME = atc.table_name(+) AND col.owner = child.owner AND Child.constraint_name = col.constraint_name ORDER BY Child.TABLE_NAME

Selecting Duplicate Entries in a table?
These are my 3 column headings TOrder_NO TPart_NO

Qty In 33 records TOrder_NO and TPart_NO are the same how can i run a query to just select these 33 records.
SELECT torder_no,tpart_no FROM orders GROUP BY torder_no,tpart_no HAVING count(*)>1;

How to perform aggregation (sum) on a computed column?

How to union two tables, and make one "override" the other for similar records?.
SELECT MktCode,Date,Price FROM tblStockPrices AS t1 LEFT JOIN tblOverridePrices AS t2 ON AND t1.mktcode=t2.mktcode WHERE T2.ID IS NULL UNION SELECT MktCode,Date,Price FROM tblOverridePrices ----------------------------------------------------------------------------SELECT DISTINCT t1.mktcode,, case when t2.mktcode IS NULL then t1.price else t2.price end FROM tblstockprices t1 LEFT JOIN tbloverrideprices t2 ON t1.mktcode=t2.mktcode AND

Find matches with no repeats?
can i wrire a query which sum up more than 2 columns in a single table?
SELECT sum(col1+col2+col3) FROM theTable SELECT sum(col) FROM (SELECT sum(c1) AS col FROM t union ALL SELECT sum(c2) AS col FROM t union ALL SELECT sum(c3) FROM t) AS theTable

how to find nth salary?
SELECT Sal FROM emp e WHERE (&n-1) = (SELECT DISTINCT(count(*)) FROM emp WHERE sal > e.sal)

Find maximum value between 2 columns of different table
select max(c) from ( select c from a union all select c from b ) u;

how do we delete redundant entries from a table ? suppose there is a table named "temp" having a column "col1" and "col2". col1 col2 ---- --abc 100 abc 100 abc 150 xyz 200 xyz 200 then the query would be as: "delete from temp t where t.col1 in(select t1.col1 from temp t1 where t.rowid< t1.rowid) and t.col2 in(select t1.col2 from temp t1 where t.rowid < t1.rowid);"

Update while keeping previous value
UPDATE ChecksA a JOIN ChecksB b ON a.Check_Num = b.CheckNo SET a.prevStatus = b.Curr_STS WHERE (a.Check_Num IN(SELECT CheckNo FROM ChecksB)) (a.prevStatus = null) OR (a.prevStatus != b.Curr_STS ));


/* Update Statements to be run, handling all of the possible incoming status codes */ UPDATE ChecksB SET Curr_STS = '04' WHERE (CheckNo IN(SELECT Check_Num FROM ChecksA WHERE Status_Code = 'R')) AND (Curr_STS != '04');

complex sql
create table tab1(sid number, num number,flag varchar2(1),link_sid number,t_id number) create table main_t(sid number, num number,flag varchar2(1),link_sid number,t_id number) insert into tab1 values (1,100,'N',2,2); insert into main_t values (2,200,'Y',1,2); insert into main_t values (3,200,'N',43,23); The data is like this: sid, and link_sid is a pair Eg: sid 1 in tab1 = link_sid 1 in main_t The t_id value is the flag 'Y' sid value for both the records Eg: 2 is the t_id for the pair ('N' and 'Y') Now I need to join tab1 and main_t in such a way that if flag is N in tab1, get the corresponding Y from main_t AND vice versa
1.SELECT * -- or whatever FROM main_table m JOIN tabl t ON m.link_sid WHERE m.flag || t.flag IN ( 'NY', 2. SELECT * -- or whatever FROM main_table m JOIN tabl t ON m.link_sid WHERE ( m.flag = 'N; AND t.flag = 'Y') OR ( m.flag = 'Y; AND t.flag columns you want = t.sid 'YN'); columns you want = t.sid = 'N');

to get the year you could use Oracle's Extract function as follows: SELECT extract (Year From to_Date('07/31/2010','MM/DD/YYYY')) Year FROM DUAL; With Oracle Extract, you can extract day, month and year. --PL/SQL Function to check user name and password procedure check_pass(p_user varchar2, p_pass varchar2) is pragma autonomous_transaction; v_passwd varchar2(200); begin select passwd into v_passwd from password_table where user_name=p_user;

if v_passwd!=p_pass then update password_table set last_unsucc_logon=sysdate ,unsucc_logon_n=nvl(unsucc_logon_n,0)+1 where user_name=p_user; commit; raise_application_error(-20101,'Invalid username/password!'); end if; exception when no_data_found then raise_application_error(-20101,'Invalid username/password!'); end;
declare 2 function digest( p_username in varchar2, p_password in varchar2 ) return varchar2 3 is 4 begin 5 return ltrim( to_char( dbms_utility.get_hash_value( upper(p_username)||'/'||upper(p_password), 6 1000000000, power(2,30) ), 7 rpad( 'X',29,'X')||'X' ) ); 8 end digest; 9 begin 10 for x in ( select username from all_users where rownum < 20 ) 11 loop 12 dbms_output.put_line( 'User: ' || rpad( x.username , 30 ) || 13 ' digest: ' || digest( x.username, 'TIGER' ) ); 14 end loop; 15 end;

first day of year and next monday of the year
select trunc(to_date('2011','yy')) first_day_of_year, next_day(trunc(to_date('2011','yy')), 'MON') next_monday from dual

find department with max duplicate salaries
SELECT deptno,salary,cnt FROM 2 (select deptno, salary,COUNT(*) cnt,MAX(COUNT(*)) OVER() mx 3 FROM emp 4 group by deptno,salary) 5* where cnt = mx

Find 3rd highest salary without using rowid,rownum and rank

select max(sal) from emp where sal < (select max(sal) from emp where sal < (select max(sal) from emp));

How to create a temporary table [A] 8i or later create global temporary tablename (column list) on commit preserve rows; - to submit a session temporary table to hold data on commit delete rows; - submitted to delete the temporary table temporary table data transaction is relative to the session, other sessions can not see the session data. how to run samples in ORACLE stored procedure in the timing [A] can be used dbms_job package to run the job from time to time, such as the implementation of the stored procedure, a simple example, to submit a job: VARIABLE jobno number; BEGIN DBMS_JOB.SUBMIT (: jobno, 'ur_procedure;', SYSDATE, 'SYSDATE + 1'); commit; END; After, you can query with the following statement has been submitted to the operation select * from user_jobs;

Sign up to vote on this title
UsefulNot useful