Tuesday, 30 August 2016

SQL Important Queries

>I have a table with duplicate items in it. Write me a query which returns only duplicate rows with number of times they are repeating.

    select item,count(*) from tab group by item having count(*)>1;

>How to find the 2nd max sal from the table.

  To get 2nd highest salary.
  select max(salary) from employee where salary < (select max(salary) from employee);
  select max(salary) from employee where salary not in(select max(salary) from employee);

  To get 5th highest salary.
  select * from tab a where 5 =(select count(distinct salary) from tab b where a.salary<=b.salary);
 
> What command is used to create a table by copying the structure of another table?
   without data:
   CREATE TABLE new_table AS SELECT * FROM old_table WHERE 1=2;

   with data:
   CREATE TABLE new_table AS SELECT * FROM old_table ;

> How to copy all data from tab1 to tab2 ,where tab1 and tab2 having same table structure.

   INSERT INTO emp_details1 SELECT * from emp_details where emp_id >1000;

> What operator tests column for the absence of data?
    NULL operator is used to check the absence of data in a column.
    Example:
    SELECT * FROM emp WHERE sal is NULL;
  
> How can we delete records in a table using update table?
  update tab set name=null where id=2;
 
>Identify error in following SQL:
    SELECT EMPNO, SUM(SAL)
    FROM EMP
    GROUP BY EMPNO
    HAVING ENAME= ?KENT?
a) Syntax Error
b) SUM() is not an aggregate function
c) HAVING can not be used with GROUP BY
d) The Having condition has to be based on some column that appears in the select list.
 
>How to remove the duplicate records from table which havting same id? Consider following table which having 2 rows with id=100.
  #select * from tab;
     id  |    name    |
    -----+------------+
     100 | mukesh     |
     101 | shivam     |
     102 | smrati     |
     100 | mukesh     |
     --in above table need to remove mukesh
--step1
  add one column num
  --ALTER TABLE tab2 ADD column num character varying;
--Step2
  Create sequence num_seq;
--Step3
  UPDATE TABLE tab set num=nextval('num_seq');
--Step4
  DELETE FROM tab where num in(SELECT MAX(num) from tab group by name having count(*)>1;
--Step5
  Check if still duplicate is there.
  Select count(*),name from tab group by name having count(*)>1;
  if above query returns any records ,repete step4.
 
 --Method 2 :

      acc_no |  name  | joint_account
    --------+--------+---------------
     100    | mukesh | 101
     200    | shivam | 102
     300    | smrati | 200
     400    | rity   | 100
     100    | mukesh | 122
     401    | rity   | 122
     402    | rity   | 122
  
--delete from emp_details1 where acc_no not in(select min(acc_no)from emp_details1 group by name);

    mydb=# select * from emp_details1;
     acc_no |  name  | joint_account
    --------+--------+---------------
     100    | mukesh | 101
     200    | shivam | 102
     300    | smrati | 200
     400    | rity   | 100
     100    | mukesh | 122

SQL Theory Questions & Answers

> How many kinds of statement SQL have?

SQL have 3 kind of statements as following.
DDL (Data Definition Language)
    CREATE – To create objects in the database
    ALTER  – To alter the structure of the database
    DROP   – To delete objects from the database
    TRUNCATE – To remove all records from a table. The  space allocated for the records is also removed

DML (Data Manipulation Language):
    SELECT – To retrieve data from the database
    INSERT – To insert data into a table
    UPDATE – To update existing data within a table
    DELETE – To delete all records from a table. Delete statement does not release space.

DCL (Data Control Language ):
    GRANT     – To give user access privileges to database objects
    REVOKE  – To withdraw access privileges given with the GRANT command
    COMMIT  – To save the work done
    ROLLBACK – To restore database to original since the last COMMIT

> How many types of constraints are in SQL ?

Constraints are the rule that restricts the values in a database.
  1.   PRIMARY KEY
  2.   NOT NULL
  3.   UNIQUE
  4.   CHECK
  5.   FOREIGN KEY
> What is the difference between primary key and unique key?
 
Primary Key:
i  ) Can be only one in a table.
ii ) It never allows null values.
iii) Primary Key is unique key identifier and can not be null and must be unique.

Unique Key:
i  ) Can be more than one unique key in one table.
ii ) Unique key can have one or multiple null but value can not duplicate.
iii) It can’t be candidate key
iv ) Unique key can be null and may not be unique.
 
> What is the difference between TRUNCATE and DELETE commands?
  •   DELETE is a DML command whereas TRUNCATE is a DDL command.Hence DELETE operation can be rolled back but TRUNCATE can not.
  •   DELETE does not release the memory occupied by the records of the table .TRUNCATE releases the memory occupied by the records of the table
  •   WHERE clause can be used with DELETE and not with TRUNCATE.
> Explain UNION, MINUS, UNION ALL and INTERSECT?

    INTERSECT - Return all distinct rows but conman records exist in both queries.
    Union     - Return all distinct rows from both queries.
    Union All - Returns all rows of both queries.
    MINUS     - Returns all distinct rows selected by the first query but not by the second

Example:
SELECT new_id from tab1 INTERSECT SELECT new_id FROM TAB2;

> How many types of join explain with example.
1) Cartesian join
2) Inner join
3) Outer join
    -Left-outer join
    -Right-outer join
4) Self join

1) Cartesian join:
    A Cartesian join occurs when data is selected from two or more tables and there is no common relation specified in the WHERE clause.
    If the first table has 3 rows and the second table has 4 rows, the result will have 12 rows.
    Example:
    SELECT * FROM Table1,Table2;
  
2) Inner join:
    Inner join is the cartesian product between 2 or more tables which satisfies the join condition in the WHERE clause .
    Example:
    SELECT Table1.Emp_ID, Table1.City, Table2.Cust_ID, Table2.City
    FROM Table1, Table2
        WHERE Table1.City = Table2.City;

3) Outer join
    -Left-outer join :
    A left outer join will return all the rows that an inner join returns and also return those rows from left table which does not have match in right side table.

    -Right-outer join
    A right outer join will return all the rows that an inner join returns and also return those rows from right table which does not have match in lest side table.

4) Self join:
    When you wish to join a table with itself based on some criteria then treat the table as two different tables by giving synonyms.
    Example:
    Consider a table Employee_Manager with column Emp_id,Emp_name and Mgr_id
    SELECT     Emp.Employee_ID , Emp.Employee_Name ,
    Emp.Mgr_id , Manager.Employee_Name
     FROM employee_Manager  Emp, employee_Manager  Manager
        WHERE Emp.Mgr_id  =  Manager.Employee_ID;
      
> What is difference between Stored Procedure and Trigger?
  • For executing SP(Stored Procedure) we have to call Stored Procedure. But in case of Trigger it is call whenever there is an action takenon table or column(Insert, Update ,Delete).
  • Stored procedure can take input parameters, but we can not pass parameters as input to a trigger.
  • Stored procedure returns value but trigger cannot returns value.
  • Stored procedures can be scheduled through a job to execute on a predefined time, but we can not schedule a trigger.
  • We can use Print commands inside a stored procedure for debugging purposes but we can not use print commands inside a trigger.
  • Stored procedures are used for performing tasks while Triggers used for auditing work.
> What is difference between procedure and function?
  • Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
  • Functions can have only input parameters for it whereas Procedures can have input/output parameters .
  • Functions can be called from Procedure whereas Procedures cannot be called from Function.
> How to add constraints while creating table
  CREATE TABLE Customer1(
    customerid varchar2(4) CONSTRAINT cust1_pkey PRIMARY KEY CHECK (customerid like 'C%'),
    customername varchar2(20) CONSTRAINT custname_nnull NOT NULL,-- DEFAULT 'XXX',
    emailid varchar2(20) CONSTRAINT email_unique UNIQUE,
    accountno NUMBER CONSTRAINT acc_fkey REFERENCES accounts(accno)
);

--MySQL DB
CREATE TABLE `staging`.`DailyCheck` (
   `date` date NOT NULL DEFAULT '0000-00-00',
   `campaignid` varchar(255) NOT NULL DEFAULT '',
   `campaign` varchar(255) NOT NULL,
   `imps` int(11) NOT NULL DEFAULT '0',
   `clicks` int(11) NOT NULL DEFAULT '0',
   `cost` double NOT NULL DEFAULT '0',
   PRIMARY KEY (`campaignid`,`date`),
   KEY `datidx` (`date`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 CREATE TABLE CUSTOMER(
    customerid varchar(4) NOT NULL,
    customername varchar(20) NOT NULL,-- DEFAULT 'XXX',
    emailid varchar(20)  UNIQUE,
    accountno int(11)
    );
  
> How to use AAD,DROP and MODIFY on column.
    DROP TABLE TAB1;

    ALTER TABLE tab ADD phone_no char(10);
    ALTER TABLE tab MODIFY phone_no char(12); --not working in postgres.
    ALTER TABLE tab1 MODIFY phone_no CONSTRAINT ph_nnull NOT NULL;
    ALTER TABLE tab ADD CONSTRAINT tab_uniqe UNIQUE(phone_no);

--modifying column in postgresql
    ALTER TABLE "MY_TABLE" ALTER COLUMN "MyColumn" TYPE varchar(8) USING substr("MyColumn", 1, 8)

    ALTER TABLE tab DROP CONSTRAINT ph_unique;
--droping a column
    ALTER TABLE TAB DROP column phone_no;
--rename a column
    ALTER TABLE TAB1 RENAME COLUMN id to new_id;

    ALTER TABLE TAB ADD CONSTRAINT tab_pkey PRIMARY KEY (ID);
    alter TABLE tab add CONSTRAINT tab_pkey PRIMARY KEY (ID,NAME);
    ALTER TABLE TAB ADD CONSTRAINTS c_check CHECK(ID BETWEEN 101 AND 120);

    ALTER TABLE tab DROP constraint tab_pkey;
    ALTER TABLE TAB DROP PRIMARY KEY; --Not supporting in postgres

    ALTER TABLE employee ADD FOREIGN KEY (dno) REFERENCES department(dnumber)

> In subqueries, which is efficient ,the IN clause or EXISTS clause? Does they produce the same result?

  EXISTS is efficient because,
  1.Exists is faster than IN clause.
  2.IN check returns values to main query where as EXISTS returns Boolean (T or F).
 
> Explain normalization with examples.

Normalization is a process of eleminating the redundancy and increasing the integrity.
Normal Forms: Review : -
Unnormalized ? There are multivalued attributes or repeating groups
    1 NF ? No multivalued attributes or repeating groups.
    2 NF ? 1 NF plus no partial dependencies
    3 NF ? 2 NF plus no transitive dependencies

Option 1: Make a determinant of the repeating group (or the multivalued attribute) a part of the primary key.

Option 2: Remove the entire repeating group from the relation. Create another relation which would contain all the attributes of the repeating group, plus the primary key from the first relation. In this new relation, the primary key from the original relation and the determinant of the repeating group will comprise a primary key.

Remove the attributes, which are dependent on a non-key attribute, from the original relation. For each transitive dependency, create a new relation with the non-key attribute which is a determinant in the transitive dependency as a primary key, and the dependent non-key attribute as a dependent.
        
> What is De-normalization and difference between normalization and De-normalization?
  • De-normalization is the process of attempting to optimize the performance of a database by adding redundant data or by grouping data.
  • Normalization is the process of De-composing a relation with anomalies into a well structured relation.
> What is difference between Co-related sub query and nested sub query?
  •   Correlated sub query runs once for each row selected by the outer query. It contains a reference to a value from the row selected by the outer query.
  •   Nested sub query runs only once for the entire nesting (outer) query. It does not contain any reference to the outer query row.
  For example,
  Correlated Subquery:
    select e1.empname, e1.basicsal, e1.deptno from emp e1 where e1.basicsal = (select max(basicsal) from emp e2 where e2.deptno = e1.deptno);

  Nested Subquery:
    select empname, basicsal, deptno from emp where (deptno, basicsal) in (select deptno, max(basicsal) from emp group by deptno);
  
> What is the main difference between the IN and EXISTS clause in sub queries?
The main difference between the IN and EXISTS predicate in subquery is the way in which the query gets executed.

IN : The inner query is executed first and the list of values obtained as its result is used by the outer query.The inner query is executed for only once.

EXISTS : The first row from the outer query is selected ,then the inner query is executed and , the outer query output uses this result for checking.This process of inner query execution repeats as many no.of times as there are outer query rows. That is, if there are ten rows that can result from outer query, the inner query is executed that many no.of times.

> what is the ACID property in database. 
ATOMICITY-- Atomicity requires that each transaction is "all or nothing": if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged
CONSISTENCY -- The consistency property ensures that any transaction will bring the database from one valid state to another
ISOLATION -- Isolation refers to the requirement that other operations cannot access or see the data in an intermediate state during a transaction
DURABILITY --Durability refers to the guarantee that once the user has been notified of success, the transaction will persist, and not be undone.

> How to find out the database name(schema name) and tables from SQL*PLUS command prompt?
  select * from information_schema.tables
 
> What is output of following query? "Select 2 from employee";
   It depends upon number of rows in table. This query will print 2 as many times as rows in table.
 
> What is the use of CASCADE CONSTRAINTS?
1)-Cascade constraint is used with drop column clause.
2)-Cascade constraint drops all referential integrity constraint primary key and unique key from a multi column table.
3)-Cascade constraint also drop multi column constraint.

    Alter table Emp Drop (PK) cascade constraint;

> What is a default TCP/IP socket assigned for SQL Server?
   1433 is default tcp/ip socket sql server.
   5432 in case of postgresql.
   3306 in case of mysql

> How can i hide a particular table name of our schema.
    We can create in two ways:
    1) using synonym
    2) by using views.

synonym : an alternative name for a table, view, sequence, procedure, stored function, package, materialized view, Java class schema object, user-defined object type, or another synonym.

> What are two methods of retrieving SQL?
   1-select
   2-using cursor
   stored procedures

Python Question & Answers SET-02

Ques 21 : consider the following function and tell What does the * in *args do?
def print_two(*args):
    arg1, arg2 = args
    print "arg1: %r, arg2: %r" % (arg1, arg2)

    That tells Python to take all the arguments to the function and then put them in args as a list. It's like argv that you've been using, but for functions. It's not normally used too often unless specifically needed.

Ques 22 : what does seek(0) ?
 seek() function is dealing in bytes, not lines. The code seek(0) moves the file to the 0 byte (first byte) in the file.

Ques 23 : How does readline() know where each line is?
Inside readline() is code that scans each byte of the file until it finds a \n character, then stops reading the file to return what it found so far. The file f is responsible for maintaining the current position in the file after each readline() call, so that it will keep reading each line.

Ques 24 : How can the words.pop function change the words variable?
That's a complicated question, but in this case words is a list, and because of that you can give it commands and it'll retain the results of those commands. This is similar to how files and many other things worked when you were working with them.
def print_first_word(words):
    """Prints the first word after popping it off."""
    word = words.pop(0)
    print word
def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)
    print word
def sort_words(words):
    """Sorts the words."""
    return sorted(words)

Ques 25 : Why does "test" and "test" return "test" or 1 and 1 return 1 instead of True?
Python and many languages like to return one of the operands to their boolean expressions rather than just True or False. This means that if you did False and 1 you get the first operand (False) but if you do True and 1 your get the second (1). Play with this a bit.

Ques 26 : Is there any difference between != and <>?
Python has deprecated <> in favor of !=, so use !=. Other than that there should be no difference.

Ques 27 : What does += mean?
The code x += 1 is the same as doing x = x + 1 but involves less typing. You can call this the "increment by" operator. The same goes for -= and many other expressions you'll learn later.'

Ques 28 : What happens if multiple elif blocks are True?
Python starts and the top runs the first block that is True, so it will run only the first one.

Ques 29 : How do I tell if a number is between a range of numbers?
You have two options: Use 0 < x < 10 or 1 <= x < 10, which is classic notation, or use x in range(1, 10).

Ques 30 : How do you make a 2-dimensional (2D) list?
That's a list in a list like this: [[1,2,3],[4,5,6]]

Ques 31 : Why does for i in range(1, 3): only loop two times instead of three times?'
The range() function only does numbers from the first to the last, not including the last. So it stops at two, not three in the above. This turns out to be the most common way to do this kind of loop.

Ques 32 : What's' the difference between a for-loop and a while-loop?
A for-loop can only iterate (loop) "over" collections of things. A while-loop can do any kind of iteration (looping) you want. However, while-loops are harder to get right and you normally can get many things done with for-loops.

Ques 33 : What does exit(0) do?
On many operating systems a program can abort with exit(0), and the number passed in will indicate an error or not. If you do exit(1) then it will be an error, but exit(0) will be a good exit. The reason its backward from normal boolean logic (with 0==False is that you can use different numbers to indicate different error results. You can do exit(100) for a different error result than exit(2) or exit(1).

Ques 34 : What does stuff[3:5] do?
That extracts a "slice" from the stuff list that is from element 3 to element 4, meaning it does not include element 5. It's similar to how range(3,5) would work.

Ques 35 : What is the difference between a list and a dictionary?'
A list is for an ordered list of items. A dictionary (or dict) is for matching some items (called "keys") to other items (called "values").

Ques 36 : What would I use a dictionary for?
When you have to take one value and "look up" another value. In fact you could call dictionaries "look up tables."

Ques 37 : What would I use a list for?
Use a list for any sequence of things that need to be in order, and you only need to look them up by a numeric index.

Ques 38 : What if I need a dictionary, but I need it to be in order?
Take a look at the collections.OrderedDict data structure in Python. Search for it online to find the documentation.

Python Question & Answers SET-01

Ques 1 : What does #!/usr/bin/python mean?
You've probably already seen one of the following lines:
#!/bin/sh
#!/usr/bin/python
#!/usr/bin/python3
#!/usr/bin/env python
#!/usr/bin/perl
#!/usr/bin/php
#!/usr/bin/ruby

This is a shebang. It's a directive for your command line interpreter how it should execute a script.
For example, you have a file with this content:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
print(sys.version_info)
Now you can execute it via python3 yourFile.py. But alternatively, you can make it executable and simply type ./yourFile.py

By the way, you should use #!/usr/bin/env python for some reasons.

Ques 2 : Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?
When do you

#!/usr/local/bin/python
You are specifying the location to the python executable in your machine, that rest of the script needs to be interpreted with.
You are pointing to python is located at /usr/local/bin/python

Consider the possiblities that in a different machine, python may be installed at /usr/bin/python or /bin/python in those cases, the above #! will fail.
For those cases, we get to call the env executable with argument which will determine the arguments path by searching in the $PATH and use it correctly.

Thus,
#/usr/bin/env python
Will figure out the correct location of python ( /usr/bin/python or /bin/python from $PATH) and make that as the interpreter for rest of the script.
- ( env is almost always located in /usr/bin/ so one need not worry what is env is not present at /usr/bin)

Ques 3 : How do I get my country's language characters into my file?
Just add at top of you file # -*- coding: utf-8 -*-

Ques 4 : If # is for comments, then how come # -*- coding: utf-8 -*- works?
Python still ignores that as code, but it's used as a kind of "hack" or workaround for problems with setting and detecting the format of a file. You also find a similar kind of comment for editor settings.

Ques 5 : How do I comment out multiple lines?
Put a # in front of each one.
 or use tripple quote as following:
 '''
    This is the multiple line
    comments
'''


Ques 6 : How to get results in decimal points using '/'?
use either following expression:
10/3.0 or 10.0/3 or 10.0/3.0

Ques 7 : What is the difference between %r and %s ?
Use the %r for debugging, since it displays the "raw" data of the variable, but the others are used for displaying to users.

Ques 8 : what will do the folowing code ?
print "." * 10
it will print "." 10 times.

Ques 9 : what will be output of following script?
#!/usr/bin/python

print "mukesh"
print "kumar"
############
print "mukesh",
print "kumar"

Ques 10 : I tried putting Chinese (or some other non-ASCII characters) into these strings, but %r prints out weird symbols.
Use %s to print that instead and it'll work.

Ques 11 : Why do the \n newlines not work when I use %r?
That's how %r formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging.

Ques 12 : What's the difference between input() and raw_input()?
The input() function will try to convert things you enter as if they were Python code, but it has security problems so you should avoid it.

Ques 13 : When my strings print out there's a u in front of them, as in u'35'.
That's how Python tells you that the string is Unicode. Use a %s format instead and you'll see it printed like normal.

Ques 14 : pydoc command ?
In Terminal where you normally run python to run your scripts, type pydoc raw_input. Read what it says. If you're on Windows try python -m pydoc raw_input instead.
exp: pydoc sys

Ques 15 : output of the command print "How old are you?" , raw_input()
>>> print "How old are you?" , raw_input()
How old are you? 12
12
>>>

Ques 16 : Are the command line arguments strings?
Yes, they come in as strings, even if you typed numbers on the command line. Use int() to convert them just like with int(raw_input()).

Ques 17 : What does mean the following file reading and writing related commmands.
close -- Closes the file. Like File->Save.. in your editor.
read -- Reads the contents of the file. You can assign the result to a variable.
readline -- Reads just one line of a text file.
truncate -- Empties the file. Watch out if you care about the file.
write('stuff') -- Writes "stuff" to the file.

Ques 18 : What does 'w' mean?
It's really just a string with a character in it for the kind of mode for the file. If you use 'w' then you're saying "open this file in 'write' mode," thus the 'w' character. There's also 'r' for "read," 'a' for append, and modifiers on these.'

Ques 19 : What modifiers to the file modes can I use?
The most important one to know for now is the + modifier, so you can do 'w+', 'r+', and 'a+'. This will open the file in both read and write mode, and depending on the character use position the file in different ways.

Ques 20 : Does just doing open(filename) open it in 'r' (read) mode?
Yes, that's the default for the open() function.
Related Posts Plugin for WordPress, Blogger...