Wednesday, 25 November 2015

Synchronize Threads- Multi-threading

(Synchronize threads) Write a program that launches 1,000 threads. Each thread
adds 1 to a variable sum that initially is 0. You need to pass sum by reference to
each thread. In order to pass it by reference, define an Integer wrapper object to

hold sum. Run the program with and without synchronization to see its effect.

import java.util.concurrent.*;

public class threads {
  private Integer sum = new Integer(0);

  public static void main(String[] args) {
    threads test = new threads();
    System.out.println("What is sum ? " + test.sum);
  }

  public threads() {
    ExecutorService executor = Executors.newFixedThreadPool(1000);

    for (int i = 0; i < 1000; i++) {
      executor.execute(new SumTask());
    }

    executor.shutdown();

    while(!executor.isTerminated()) {
    }
  }

  class SumTask implements Runnable {
    public void run() {
      int value = sum.intValue() + 1;
      sum = new Integer(value);
    }
  }
}

Monday, 23 November 2015

SQL Queries on Views, Complex View, Insert, update views.

                                                              
1 Q1)Create your own EMP and DEPT by using CREATE TABLE EMP AS syntax
Sol: Create table emp(empno number,ename varchar2(15),job varchar2(15),mgr number,hiredate date, sal number,comm number,deptno number);

Create table dept(deptno number, deptname varchar2(15), loc varchar2(15));


Q2)Add PK on both tables and FK as necessary.
                Sol: alter table employee add primary key(emp_no);
Alter table employee add foreign key(dept_no) references dept(dept_no);

Q3)Add NOT NULL constraint on Deptno in EMP table
Sol: alter table dept modify dept_no constraint dept_no_nn NOT NULL;

Q4)Add constraint on ENAME to ensure all records inserted will have ENAME in UPPERCASE.  ALTER TABLE table_name add CONSTRAINT constraint_name CHECK (column_name condition)
Sol:  alter table S_12345_EMP add constraint NAME_UPPER_CK check(FIRST_NAME = upper(FIRST_NAME));

Q5)Write a query to display all constraints for table EMP.
Sol: SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,STATUS,DEFERRABLE,DEFERRED FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'S_12345_EMP';



Q6)Create a view that display only the empno/ename/deptno in SALES dept. (deptno=30). Describe the structure of the view (combined 6 and 7)
Sol: create view emp_details AS select emp_no, emp_name, dept_no from employee where dept_no = 14;

Q7)Describe the structure of the view CREATE OR REPLACE VIEW sales_dept_emp_vw (emp_num,emp_name,dept_no) AS SELECT empno employee_number, ename, deptno FROM emp WHERE deptno = 30;

Q8)SELECT/INSERT/UPDATE/DELETE on this view.
SOL:
Sol8: UPDATE EMP_DETAINLS2_VIEW SET FIRST_NAME = ‘VIEW_NAME’ WHERE DEPT_ID =50;
Q9)Create a view With CHECK Option CREATE OR REPLACE VIEW sales_dept_emp_vw_1 (emp_num,emp_name,dept_no) AS SELECT empno employee_number, ename, deptno FROM emp WHERE deptno = 30 WITH CHECK OPTION;
Sol: CREATE VIEW EMP_CHECK_VIEW AS SELECT * FROM S_12345_EMP WHERE DEPT_ID>30 WITH CHECK OPTION CONSTRAINT EMP_CHECK_VIEW_FIRST_NAME;
Q10. Try inserting a record with deptno !=30.
SOL10)
INSERT INTO EMP_CHECK_VIEW(ID,LAST_NAME,FIRST_NAME,USERID,START_DATE,COMMENTS,MANAGER_ID,TITLE,DEPT_ID,SALARY,COMMISSION_PCT) VALUES (123,’TYAGI’,’BHAVI’,’BHAVI123’,’16-NOV-14’,’NO_COMMENTS’,124,’MANAGER’,29,20000,10);
INSERT INTO EMP_CKECK_VIEW (
*
ERROR at line 1:
ORA-01402: view WITH CHECK OPTION where-clause violation

Q11. Create a view with READ ONLY CREATE OR REPLACE VIEW sales_dept_emp_vw_2(emp_num,emp_name,dept_no) AS SELECT empno employee_number, ename, deptno FROM emp WHERE deptno = 30 WITH READ ONLY;
SOL11) CREATE VIEW EMP_DETAILS2_VIEW AS SELECT * FROM S_12345_EMP WHERE DEPT_ID < 15 WITH READ ONLY CONSTRAINT EMP_DETAILS2_VIEW_READ_ONLY;

Q12. Try inserting a record to sales_dept_emp_vw _2
INSERT INTO EMP_DETAILS2_VIEW  (ID, LAST_NAME, FIRST_NAME,USERID) VALUES (123,’TEST’,’TEST1’,’3ABC’);

Q13. Create a Complex View Create or replace view sales_dept_emp_vw_3 as SELECT a.empno, a.ename, a.deptno, b.dname, b.loc FROM emp a, dept b WHERE a.deptno = b.deptno AND b.dname='SALES';
SOL13)
Complex views contain subqueries that
A)Retrieve rows from multiple base tables.
B)Group rows using a GROUP BY or DISTINCT clause.
C)Contain a function call.
CREATE VIEW EMP_DETAILS_VIEW3 AS SELECT FIRST_NAME, AVG(SALARY) AVERAGE_SALARY FROM S_12345_EMP WHERE SALARY > 10000 GROUP BY DEPT_ID,FIRST_NAME HAVING AVG(SALARY) > 5000 ORDER BY DEPT_ID;

Q14. Try inserting a record to sales_dept_emp_vw_3.
SOL14)
INSERT INTO EMP_DETAILS_VIEW3(FIRST_NAME) VALUES (‘BHAVISHYA’);





Sunday, 22 November 2015

Practice set of question on SQL.


1.   
Find the details of highest paid employee?
select ename, job, sal, deptno from emp where sal = (select max(sal) from emp);

2.  List the employees  whose job is same as ‘ALLEN’,Or,‘SMITH’?

SELECT * FROM EMPLOYEE WHERE JOB = (SELECT JOB FROM EMPLOYEE WHERE ENAME =  'ALLEN') OR JOB =(SELECT JOB FROM EMPLOYEE WHERE ENAME = 'SMITH');


Q3 get the employees with the top salary with department = 20 and job = clerk.
SELECT * FROM EMPLOYEE  WHERE DEPTNO = '20' AND JOB = 'CLERK' ORDER BY SAL DESC;


Q4. List the employees who are senior to most recently hired employee and is working under manager,‘KING’.

select * from employee where hiredate < (select max(hiredate) from employee where mgr in (select empno from employee where ename = 'KING')) ;


Q5. Show all the different department id along with number of employee work in that department. Display only department in which more than four employee are present.

select deptno, count(empno) from employee group by deptno having count(*) >= 4;
  
Q6. List,job,`title,and,number,of,employee,who,are,doing,that,job.,

select  deptno ,job ,count(*)  from emp group by  deptno,job;


Q7. Determine,the,highest,paid,employee,under,each,job,`tle.,
select * from emp where sal in (select max(sal) from emp group by job) order by sal desc;




Q8. Display the ename,job,sal for the employees whose sal is greater than the maximum,avg(sal) by deptno.

SELECT ENAME,JOB,SAL FROM EMPLOYEE WHERE SAL>(SELECT MAX(SAL)FROM EMPLOYEE);





9. Find,the,employee,whose,salary,is,greater,than,average,salary.

SELECT ENAME FROM EMPLOYEE WHERE SAL> (SELECT AVG(SAL)FROM EMPLOYEE;







Forms of Normalization. NF1,NF2,NF3. Detailed.

Database normalization:

Normalization involves decomposing a table into less redundant (and smaller) tables without losing information; defining foreign keys in the old table referencing the primary keys of the new ones.
                       The objective is to isolate data so that additions, deletions, and modifications of an attribute can be made in just one table and then propagated through the rest of the database using the defined foreign keys.

Problem Without Normalization
S_id
S_Name
S_Address
Subject_opted
401
Adam
Noida
Bio
402
Alex
Panipat
Maths
403
Stuart
Jammu
Maths
404
Adam
Noida
Physics
Without Normalization, it becomes difficult to handle and update the database, without facing data loss. Insertion, Updation and Deletion Anamolies are very frequent if Database is not Normalized. To understand these anomalies let us take an example of Student table.

   Updation Anamoly : To update address of a student who occurs twice or more than twice in a table, we will have to update S_Address column in all the rows, else data will become inconsistent.
   Insertion Anamoly : Suppose for a new admission, we have a Student id(S_id), name and address of a student but if student has not opted for any subjects yet then we have to insert NULL there, leading to Insertion Anamoly.
   Deletion Anamoly : If (S_id) 401 has only one subject and temporarily he drops it, when we delete that row, entire student record will be deleted along with it.


Edgar F. Codd, the inventor of the relational model (RM), introduced the concept of normalization and what we now know as the First normal form (1NF) in 1970. Codd went on to define the Second normal form (2NF) and Third normal form (3NF) in 1971, and Codd and Raymond F. Boyce defined the Boyce-Codd Normal Form (BCNF) in 1974.[3] Informally, a relational database table is often described as "normalized" if it


First normal form (1NF) is a property of a relation in a relational database. A relation is in first normal form if the domain of each attribute contains only atomic values, and the value of each attribute contains only a single value from that domain.
Edgar Codd, in a 1971 conference paper, defined a relation in first normal form to be one such that none of the domains of that relation should have elements which are themselves sets.
First normal form enforces these criteria:
   Eliminate repeating groups in individual tables.
   Create a separate table for each set of related data.
   Identify each set of related data with a primary key


Student Table :
Student
Age
Subject
Adam
15
Biology, Maths
Alex
14
Maths
Stuart
17
Maths
In First Normal Form, any row must not have a column in which more than one value is saved, like separated with commas. Rather than that, we must separate such data into multiple rows.


Student Table following 1NF will be :

Student
Age
Subject
Adam
15
Biology
Adam
15
Maths
Alex
14
Maths
Stuart
17
Maths
Using the First Normal Form, data redundancy increases, as there will be many columns with same data in multiple rows but each row as a whole will be unique.


Second normal form:
A table that is in first normal form (1NF) must meet additional criteria if it is to qualify for second normal form.
Specifically: a table is in 2NF if it is in 1NF and no non-prime attribute is dependent on any proper subset of any candidate key of the table. A non-prime attribute of a table is an attribute that is not a part of any candidate key of the table.
Put simply, a table is in 2NF if it is in 1NF and every non-prime attribute of the table is dependent on the whole of every candidate key.
Tournament Winners
Tournament
Year
Winner
Winner Date of Birth
Des Moines Masters
1998
Chip Masterson
14 March 1977
Indiana Invitational
1998
Al Fredrickson
21 July 1975
Cleveland Open
1999
Bob Albertson
28 September 1968
Des Moines Masters
1999
Al Fredrickson
21 July 1975
Indiana Invitational
1999
Chip Masterson
14 March 1977

Even though Winner and Winner Date of Birth are determined by the whole key {Tournament, Year} and not part of it, particular Winner / Winner Date of Birth combinations are shown redundantly on multiple records. This leads to an update anomaly: if updates are not carried out consistently, a particular winner could be shown as having two different dates of birth.
KEY POINT: THE TABLE ABOVE IS IN 2ND NORMAL FORM AND IT STILL HAS UPDATE ANOMALY.
The underlying problem is the transitive dependency to which the Winner Date of Birth attribute is subject. Winner Date of Birth actually depends on Winner, which in turn depends on the key Tournament / Year.
This problem of transitive dependency is addressed by third normal form (3NF).

Third normal form:
Third normal form is a normal form used in normalizing a database design to reduce the duplication of data and ensure referential integrity by ensuring that
   the entity is in second normal form and
   all the attributes in a table are determined only by the candidate keys of that table and not by any non-prime attributes.

An example of a 2NF table that fails to meet the requirements of 3NF is:
Tournament Winners
Tournament
Year
Winner
Winner Date of Birth
Indiana Invitational
1998
Al Fredrickson
21 July 1975
Cleveland Open
1999
Bob Albertson
28 September 1968
Des Moines Masters
1999
Al Fredrickson
21 July 1975
Indiana Invitational
1999
Chip Masterson
14 March 1977


Because each row in the table needs to tell us who won a particular Tournament in a particular Year, the composite key {Tournament, Year} is a minimal set of attributes guaranteed to uniquely identify a row. That is, {Tournament, Year} is a candidate key for the table.
The breach of 3NF occurs because the non-prime attribute Winner Date of Birth is transitively dependent on the candidate key {Tournament, Year} via the non-prime attribute Winner. The fact that Winner Date of Birth is functionally dependent on Winner makes the table vulnerable to logical inconsistencies, as there is nothing to stop the same person from being shown with different dates of birth on different records.

In order to express the same facts without violating 3NF, it is necessary to split the table into two:

1)   The Tournament winners { tournament, year , winner }
2)   Winner dates of birth { winner, date of birth }

Tournament Winners
Tournament
Year
Winner
Indiana Invitational
1998
Al Fredrickson
Cleveland Open
1999
Bob Albertson
Des Moines Masters
1999
Al Fredrickson
Indiana Invitational
1999
Chip Masterson

Dates of Birth
Winner
Date of Birth
Chip Masterson
14 March 1977
Al Fredrickson
21 July 1975
Bob Albertson
28 September 1968


Note: Tables used in the examples have been taken from various open sources.