+ All Categories
Home > Education > SQL for interview

SQL for interview

Date post: 15-Apr-2017
Category:
Upload: aditya-kumar-tripathy
View: 221 times
Download: 0 times
Share this document with a friend
80
SQL Fundamentals MR. ADITYA KUMAR TRIPATHY
Transcript
Page 1: SQL for interview

SQL FundamentalsMR. ADITYA KUMAR TRIPATHY

Page 2: SQL for interview

SQL

What is Data? Any Useful information is a data. In simple words data can be facts related to any object in

consideration For example your name, age, height, weight, etc are some data related

to you. A picture , image , file , pdf etc can also be considered data

What is Database ?A database is a systematic collection of data. Databases support storage and manipulation of data. Databases make data management easy

Ex: An online telephone directoryelectricity service providerfacebook.

What is a Database Management System (DBMS)?Database Management System (DBMS) is a collection of programs which enables its users to access database, manipulate data, reporting / representation of data . It also helps to control access to the database

Page 3: SQL for interview

Database Management Systems are not a new concept and as such had been first implemented in 1960s. Charles Bachmen's Integrated Data Store(IDS) is said to be the first DBMS in history

Types of DBMS Hierarchical - this type of DBMS employs the "parent-child"

relationship of storing data. The windows registry used in Windows OS is an example of a hierarchical database.

Network DBMS - this type of DBMS supports many-to many relations.

Ex: RDM Server

Relational DBMS - this type of DBMS defines database relationships in form of tables, also known as relations

Ex: MySQL, Oracle and Microsoft SQL Server

A cell is an intersection of a row and a columnA column is also called as a field / attributeA record is also called as a row / tuple. A table is also called as an entity / relation.

Page 4: SQL for interview

Object Oriented Relation DBMS - this type supports storage of new data types. The data to be stored is in form of objects. The objects to be stored in the database have attributes (i.e. gender, age) and methods that define what to do with the data.EX: PostgreSQL.

Note :-If we install any of the database related software(s) – we can create our own database, we can create our own tables and we can store the data inside it.When we install any database s/w(s) – a part of hard disk will be designated / reserved to perform database related activitiesA database can also contain other database objects like views, indexes, stored procedures, functions, triggers etc, apart from tables.

Some of the database software(s) we have are,Oracle, SQL Server, DB2, Sybase, Informix, MySQL, MS – Access, Foxbase, FoxPro

Page 5: SQL for interview

The s/w which is widely used today is Oracle. The different versions of Oracle starting from the earliest to the latest are – Oracle 2, Oracle 3, Oracle 4, Oracle 5, Oracle 6, Oracle 7, Oracle 8i, Oracle 9i, Oracle 10g,11g and the latest to hit the market is Oracle 12c. here ‘i’ stands for Internet, ‘g’ stands for Grid / Grid computing and C for Cloud Computing .

Client Server Architecture:

Page 6: SQL for interview

What is Relational Database? It is the collection of relations or two dimensional tablesDr E.F Codd proposed the relational model for database

system in 1969Relational Model Consists of following• Collections of Objects or Relations• Set of Operators to act on the relations• Data integrity for accuracy and consistency.

( Data integrity is the one which contains correct data in the database)

• To restrict storing wrong data in database we use data integrity.To Preserve data integrity we have two types1.DataType:2.Constraints:Data Type is a type of data which you store in each column

Page 7: SQL for interview

ConstraintsCONSTRAINTSA constraint is a condition which restricts the invalid data in the table. A constraint can be provided for a column of a table.

Types of ConstraintsNOT NULLUNIQUEPrimary KeyForeign KeyCheck

NULLNULL is nothing, it is neither zero nor blank spaceIt will not occupy any space in the memoryTwo NULLS are never same in Oracle.NULL represents unknown valueAny arithmetic operation we perform on NULL will result in NULL itself. For ex, 100000 + NULL = NULL ; 100000 * NULL = NULL

Page 8: SQL for interview

NOT NULL- NOT NULL will ensure atleast some value should be present in a column UNIQUEIt will not allow any duplicates in a columnUNIQUE column can take multiple NULL (s)

Primary Key It is the combination of NOT NULL and UNIQUEOnly one PK is allowed in a tablePK identifies a record uniquely in a tableCreation of PK is not mandatory, but it is highly recommended to create

Page 9: SQL for interview

Foreign KeyFK creates relationship between any two tablesFK is also called as referential integrity constraintsFK is created on the child tableFK can take both NULL and duplicate valuesTo create FK, the master table should have PK defined on the common column of the master tableWe can have more than 1 FK in a given table

CHECKIt is used to provide additional validations as per the customer requirements.

Page 10: SQL for interview

Troubleshooting OracleError 1The account is lockedSteps to rectify the error Login as username – ‘system’ & password – ‘manager’ or ‘password – ‘tiger’SQL > show user ;User is “SYSTEM” SQL > alter user scott account unlock ;User altered SQL > exit ;Error 2TNS : protocol adapter error How to troubleshoot thisCause is “oracle service has not started” How to go here, Settings – Control Panel – Administrative Tools – ServicesSort the listThere is an “Oracle Service ORCL” & “start the service”

Page 11: SQL for interview

Sql is developed by IBMSQL – Structured Query Language. The first name of sql is SEQUEL(Simple or Structured english query language)SQL – it is a language to talk to the database / to access the database To work on SQL , a DB software (RDBMS) is required.SQL is not case sensitive

What is SQL?Structured Query language (SQL) pronounced as "S-Q-L" or sometimes as "See-Quel"is actually the standard language for dealing with Relational Databases. SQL can be effectively used to insert, search, update, delete database records.

SQL

Page 12: SQL for interview

SQL Statements1 Select Data retrieval language

2 Insert Data manipulation Language

Update

Delete

3 Create Data definition language

Alter

Drop

Rename

Truncate

4 Commit Transaction Control Language

Rollback

Save Point Data transaction Language

5 Grant, Revoke Data Control language

Page 13: SQL for interview

DQLSELECT:It is the statement used to read data from the table.

Capabilities of Select Statement1. Projection:2. Selection:3. Join

Projection:

Syntax:Select * | {[Distinct] Column| Expression [Aliase],…}From table

Page 14: SQL for interview

Column Alias

Defining a Columns AliasA Column Alias:Rename a column headingIs useful with calculationImmediately follows the column name – there can also be the optional as keyword between the column name and aliasRequires double quotation marks if it contains spaces or special characters or is case sensitive.

Literal characters.SQL> Select 'hello',ename from emp;Literal Character String

A literal is a character, a number, or a date included in the select listDate and character literals values must be enclosed within single quotation markEach character string is output once for each row returned.

Page 15: SQL for interview

|| is a concatenation operation used concatenate columnsSQL> Select ename||job||sal from emp;

Eliminating Duplicate Rows:Eliminating duplicate rows by using the DISTINCT keyword in the select clause.Q. Display department which has atleast 1 employeeSelect DISTINCT deptno from emp;Example Problems:1. Select Salary increase of 300 for all the employees and display both old and new

salary.2. Display ename, his monthly salary and his annual salary3. Display employee name, monthly sal, and his annual salary with monthly bonus of

Rs 300

Page 16: SQL for interview

Assignments:1. Display all rows and all columns of employee table2. Display any 2 columns of employee table4. Display the distinct salary of all the employee5. Display the output of the following employee “Hello smith your salary is 800” 6 is the following statement is correct.Select ename,deptno from emp;Select *,ename from emp;Select ename deptno from emp;

Page 17: SQL for interview

1. Select * From emp/2. List command is used to know the last execution command.SQL> List Or SQL>l Or SQL>;

3.To set page size and line size in a single line.SQL>Set lines 200 pages 100;

4. To execute the previously executed statement we use / (forward slash)SQL>/

5.To edit the previously executed statement we use edit

Sql>edit C:\xyz.txt

6. To save the previously executed statement SQL> Save C:\xyz.txt

7. To save multiple statement in same file or to add statement to the already saved file we use append.SQL>Save C:\xyz.txt append

Page 18: SQL for interview

9. To execute all the statement from file we use @SQL>@ c:\xyz.txt

10. To set the time we use SQL> Set time on

11. Timing is used to display the execution time of the statementSQL>Set timing on

12. To record the output that is taking place in sql plus we use ‘SPOOL’SQL> Spool

13. To see all the parametersSQL>Show all

14. To know about any command go to helpSQL>HelpSQL>? @

Page 19: SQL for interview

SL No. SQL Statement SQL*Plus

1 A Language An Environment

2 ANSI Standard Oracle Proprietary

3 Keywords Cannot be abbreviated Keywords can be abbreviated

4 Statement manipulate data and table definitions in the database

Commands do not allow manipulation of values in database

5 Runs on client and needs to be install in each machine

SQL* Plus/SQL PlusClient tool to access the databaseInstalled along with databaseHas specific set of commands Interface user and data base

Difference between SQL Statement and SQL* Plus command

Page 20: SQL for interview

OperatorsOperators are classified into,Arithmetic Operators ( +, - , * , / )Relational Operators ( > , < , >= , <= , = , < > or != - not equals to )Logical Operators ( NOT, AND, OR )Special Operators ( IN , LIKE , BETWEEN , IS )

Order Evaluated Operator

1 Arithmetic Operator

2 Concatenation

3 Comparison

4 Is, Like, In

5 Between

6 Not

7 AND

8 OR

Rules of Precedence:

Page 21: SQL for interview

SELECTION:Limiting the Rows SelectedSelect *|{[Distinct ] column|expression [aliase]…}From tableWhere condition(s)]

SQL> Select * 2 from emp 3 where ename='ALLEN';

where’ clause is used to restrict the number of records displayed. It gives only the records of the specified condition.

Ex: Select *From empWhere job=‘MANAGER’

Page 22: SQL for interview

1. List all the employees in dept 20.2. List the employee earning more than Rs 2500;3. Display all the salesmen

IN: it is used for evaluating multiple values.

4. List the employees in department 10 and 20.5. List all the clerks and analyst.

LIKE – used for pattern matching % (percentage) - matches 0 or ‘n’ characters_ (underscore) - matches exactly one character

6. List all the employee whose name starts with ‘S’7. List all the employee whose name is having letter ‘L’ as Second character8. List all the employees whose name is having at least 2 L’s in it 4) List the employees whose name is having letter ‘E’ as the last but one character5) List all the employees whose name is having letter ‘R’ in the 3rd position6) List all the employees who are having exactly 5 characters in their jobs

Page 23: SQL for interview

BETWEEN operator – used for searching based on range of values.

Ex – 1) List the employees whose salary is between 200 and 300

IS operator – it is used to compare nulls

Ex – 1) List all the employees whose commission is null

1) List all the employees who don’t have a reporting manager

2) List all the salesmen in dept 30

2) List all the salesmen in dept number 30 and having salary greater than 15003)List all the employees whose name starts with ‘s’ or ‘a’

4) List all the employees except those who are working in dept 10 & 20.

5) List the employees whose name does not start with ‘S’

6) List all the employees who are having reporting managers in dept 10

Page 24: SQL for interview

Assignments.

1) List the employees who are not working as managers and clerks in dept 10 and 20 with a salary in the range of 1000 to 3000

2) List the employees whose salary not in the range of 1000 to 2000 in dept 10,20,30 except all salesmen

3) List the department names which are having letter ‘O’ in their locations as well as their department names

4) Display all the employees whose job has string ‘MAN’ in it.

Page 25: SQL for interview

SORTINGIt arranges the data either in ascending / descending orderAscending – ASC / Descending – DESCWe can sort the data using ORDER BY By default, the data is always arranged in ASC order

NOTE :- 1.ORDER BY should be used always as the last statement in the SQL query.2. You can sort by a column that is not in the select case. 3. Entire row will be ordered not only selected columns will be displayed in order.

1)Arrange all the employees by their salary2) Arrange all the employees by their salary in the descending order3) Arrange ename, sal, job, empno and sort by descending order of salary

Page 26: SQL for interview

FunctionsFunction is a Reusable program that returns a valueThere are 2 types of functions 1. Pre-defined or Built in functions.2. User defined functions.

These are used both in SQL and PL/SQL. PL – Procedural Language (it’s a extension to SQL, can contain IF statements, loops, exceptions, OOPs, etc .. )

Functions are very powerful features of sql and can be used to do the following • Perform Calculation on data• Modify individual data items• Manipulate output for group of rows

Page 27: SQL for interview

In SQL functions are classified into 1. Single row function: Which returns one results per row.2. Multiple row function: Returns one result per group

Single row functions1. Character Functions:

Character functions are classified into case manipulation functionAnd character manipulation function

Case manipulation Functions:1) Lower2) Upper3) INITCAP

Character Manipulation Functions:1)CONCAT2)SUBSTR3)LENGTH4)INSTR5)REPLACE

Page 28: SQL for interview

Case manipulation Functions:

SQL> select upper('Qspiders'),lower('QSPiders'),initcap('qspiders') from dual;

UPPER('Q LOWER('Q INITCAP(-------- -------- --------QSPIDERS qspiders Qspiders

Dual – is a dummy table which is used for performing some independent operations which will not depend on any of the existing tables.

SQL> select upper(ename),lower(ename),initcap(ename) from emp;

UPPER(ENAM LOWER(ENAM INITCAP(EN---------- ---------- ----------SMITH smith SmithALLEN allen Allen

Page 29: SQL for interview

Character Manipulation Functions:Concat: It concatenates any two values or columns.It is represented by ||Ex:SQL> select ename,job, concat(ename,job) from emp;

ENAME JOB CONCAT(ENAME,JOB)---------- --------- -------------------SMITH CLERK SMITHCLERKALLEN SALESMAN ALLENSALESMAN

1. Write a sql statement to display ‘SMITH is a clerk’

Note: Exactly 2 arguments can be given to concat function.

Page 30: SQL for interview

SUBSTRThe Substring function in SQL is used to return a portion of stringSyntax:SUBSTR (str, position, [length])where position and length are both integers. This syntax means the following: Start with the position-th character in string str, select the next length characters.

1. Display 1st and last character of all the employees.

Page 31: SQL for interview

Length: Length is used to find the length of the given string.Syntax: Length(Str)

EX: Select Length(‘Qspiders’) from dual;

1. Display all the employees whose name has exactly 6 character.

INSTR: Find the staring location of the nth occurrence of pattern beginning in the starting position-th position in string str.

INSTR (str, pattern, [starting position, [nth location]])

Ex: Instr(‘Qspiders’, ‘s’ , ‘1’ , ‘1’) from dual;

1. Display all the employees whose name start with ‘S’

Page 32: SQL for interview

Replace:The Replace function in SQL is used to update the content of a string. The syntax of the Replace function is: Replace (str1, str2, str3)

In str1, find where str2 occurs, and replace it with str3.Ex:SQL> Select Replace('qspiders','s','*') from dual;

Trim: Is used to remove the spaces present in the given string.Ltrim(Str): LTRIM Removes all white spaces from the beginning of the string. Rtrim(Str):RTRIM Removes all white spaces at the end of the string.

1. Write a sql statement to display the number of spaces present in the given string

Page 33: SQL for interview

2. NUMBER FUNCTIONS:

Round: Round the Value to specified decimalEx: Round(23.34) 23

Trunc: Truncate the values to specified decimal.Ex: Trunc(34.6554) --- 34

Mod: Returns Reminder of division.Ex: Mod(10,3) 1

Ex:SQL> SELECT * FROM EMP WHERE MOD(SAL,2)=1;

Page 34: SQL for interview

1. Display all the employees whose job has string ‘MAN’2. Display all the employees whose name has ‘L’ as third

character.3. Display the result in the following format, first

character in lower case rest in uppercase.4. Display all the employees which has at lest 2L’s in it.5. Display the number of occurrence of substring in a

string.Display the number of L’s in each name

6. Display all the employees whose name is palindrome

Page 35: SQL for interview

Working with Dates: Oracle database stores dates in an internal numeric format: Century, Year, Month, day, hours, minutes, Seconds. The default date display format is DD-MM-YY

Ex: Select ename, hiredate from emp

• Sysdate: It is a function that returns date

• Systimestamp: It is a function that returns date, time including milliseconds and time zone

Arithmetic With dates:• Add or subtract a number to or from a date for a resultant date value• Subtract two dates to find the number of days between those date.Ex : To get future or past dateSelect sysdate+100 , sysdate-70 from dual;

Ex: Experience with years;Select ename,hiredate, round((sysdate-hiredate)/360) from emp;

Page 36: SQL for interview

Group Functions/Multi row functions

Group Functions operate on sets of rows to give one row result per group.We have 5 GROUP functions,SumMaxMinAvgCount Sum – returns total valueMax – returns maximum valueMin – returns minimum valueAvg – returns average valueCount – returns number of records

Page 37: SQL for interview

Ex – 1) display the maximum salary, minimum salary and total salary from employee2)Write a query to display total number of employees

3. Display the number of employee who has commission

4) List the number of employees in department 30

5) Display the total salary in department 30

6) List the number of clerks in department 20

7) List the highest and lowest salary earned by salesmen

Page 38: SQL for interview

GROUPINGIt is the process of computing the aggregates by segregating based on one or more columns. Grouping is done by using ‘group by’ clause. Syntax:SELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_name; For ex – 1) Display the total salary of all departments

2) Display the maximum of each job

HAVING‘Having’ is used to filter the grouped data.‘Where’ is used to filter the non grouped data. ‘Having’ should be used after group by clause‘Where’ should be used before group by clause

1) Display job-wise highest salary only if the highest salary is more than Rs1500

Page 39: SQL for interview

2) Display job-wise highest salary only if the highest salary is more than 1500 excluding department 30. Sort the data based on highest salary in the ascending order.

RESTRICTIONS ON GROUPINGNote 1- we can select only the columns that are part of ‘group by’ statementIf we try selecting other columns, we will get an error

Note 2:Whatever is there in the select statement must be there in the group by statement. But, whatever is there in the group by statement need not be present in the select statement. This is shown in the above two corrected queries.

1) Display the department numbers along with the number of employees in it2) Display the department numbers which are having more than 4 employees in them3) Display the maximum salary for each of the job excluding all the employees whose

name ends with ‘S’4) Display the department numbers which are having more than 9000 as their

departmental total salary

Page 40: SQL for interview

SUB - QUERIESA sub-query is also called as a nested query. Syntax of a sub-query OUTER QUERY

Select …From …Where … ( select …

From … Where …)

INNER QUERY Here, the inner query will be executed first. The output of inner query is passed as input to the outer query. To write a sub-query, atleast 1 common column should be existing between the tables.

Page 41: SQL for interview

1) List the employees who has salary greater than Allen2) List the employees working in ‘Research’ department.3) List the department names that are having analysts4) List the employees in Research and Sales department5) List the department names which are having salesmen in it. 6) Display the employees whose location is having at least one ‘O’ in it.7) List the department names that are having at least 1 employee in it.8) List the department names that are having at least 4 employees in it9) Display the department names which are having at least 2clerks in it10) List the department names that are having no employees at all11) Display all the employees whose job is same as scott12) Display scott manager’s manager’s department name13) List employees whose job is same as scott and their salary greater than smith’s

salary14) Display all the employees whose job is same as scott and allen15) Display all the employees who are actual managers16) Display who are all the employees reporting to scott17) Display all the employees who are not manager

Page 42: SQL for interview

1. Display the 2nd maximum salary2. Display the 3rd maximum salary3. Display all the employees who are earning more than all the managers.4. Display all the employees who are earning more than any of the manager5. Select empno, job and salary of all the analyst who are earning MORE THAN any

of the manager6. Select the department name and location of all the employees working for clerk.7. Select all the employees working for dallas8. Display all the employees whose salary is greater than avg sal of department 20

Page 43: SQL for interview

JOINSJoins are used when we need to fetch the data from multiple tablesTypes of JOIN(s)Cartesian Join (product)Inner (Equi) JoinOuter Join - Left Outer Join, Right Outer Join, Full Outer JoinSelf Join

CARTESIAN JOIN- It is based on Cartesian product theory. Display employee name along with the department name

INNER JOINInner join are also called as equijoins. They return the matching records between the tables.In the real time scenarios, this is the most frequently used Join.

Display employee name along with the department nameNote:JOIN condition is mandatory for removing the Cartesian output.

Page 44: SQL for interview

ANSI style JOINS

This was introduced from Oracle 9i. It is another way of writing inner joins with a few modifications. ,(comma) has been replaced by the word ‘join’where’ has been replaced with ‘on’

OUTER JOINIt returns both matching and non-matching records Outer join = inner join + non-matching records Non-matching records means data present in one table, but absent in another table w.r.to common columns. For ex, 40 is there in deptno of dept table, but not there in deptno of emp table.

Page 45: SQL for interview

1) Display employee name and his department name for the employees whose name starts with ‘S’

2) Display employee name and his department name who is earning 1st maximum salary

3) Display ename and grade in 1 and 24) Write a query to display number of employees in each department.

SELF JOINJoining a table to itself is called self join5) Display employee name along with their manager name6) Display the employees who are getting the same salary

Page 46: SQL for interview

Equijoin:1. Display all the managers and clerks who work in accounts and

marketing departments.2. Display all the salesman who are not located at DALLAS3. Select all the employees who work in DALLAS

OUTER JOIN4. Get matching as well as non matching records from both the

table

Page 47: SQL for interview

SELF JOIN:1. Get all the employees who work in the same department as of scott SELECT A.ENAME,B.ENAME FROM EMP A, EMP B WHERE A.DEPTNO=B.DEPTNO AND A.ENAME='SCOTT‘

2. List all the employees earning more than there managerSELECT A.ENAME,A.SAL,B.ENAME,B.SALFROM EMP A,EMP BWHERE A.MGR=B.EMPNOAND A.SAL>B.SAL3. Fetch all the employees who are earning same salary

4. Select all the employees who are earning same as ‘SMITH’SELECT A.ENAME,A.SAL,B.ENAME,B.SALFROM EMP A, EMP BWHERE A.SAL=B.SALAND A.EMPNO<>B.EMPNOAND A.ENAME='SMITH'

Page 48: SQL for interview

Co – related Queries : They are special type of sub – queriesHere, both outer & inner queries are inter-dependentFor each & every record of outer query, the entire inner query will be executedThey work on the principles of both sub – queries & JOIN(s). For ex, Display the employee who is earning the highest salarySQL> select * from emp A 2 where 0=(Select count(distinct(sal)) from emp B where A.Sal<B.Sal);

Page 49: SQL for interview

1) Display the least salary from the employee table.

2) Display top 3 person’s salaries from the employee table. 3) Write a query to display bottom 3 salaries

4) Display 1st and 4th maximum salary

5) Display 1st, 4th & 6th highest salaries in a single query

Page 50: SQL for interview

DDL – Data Definition Language the various commands in DDL are :- Create, Drop, Truncate, Alter, Rename

CREATE – It creates the table. Before we study the Create command, let us first study the some of the basic datatypes we use in SQL.1) CHAR :-It stores the fixed length character data. It can store the alphanumeric data (i.e, numbers and characters). 2) VARCHARIt stores the variable length character dataIt can store alphanumeric data.

Another difference is : -In char, maximum value we can store is 2000 charactersIn varchar, maximum value we can store is 4000 characters.

Page 51: SQL for interview

3) NUMBER- it stores numeric data. For ex – 1) sal number(4) ;

Here the maximum possible value is 9999.

2) sal number (6, 2) ;Here, 2 – scale (total number of decimal places) 6 – precision (total number of digits including decimal places)Maximum value is 9999.99sal number (4, 3) ;maximum value is 9.999sal number (2, 2)maximum value is .99

4) DATE- it stores date and time- no need to specify any length for this type. Date is always displayed in the default format :- dd – month – yy

Page 52: SQL for interview

5) BLOBStands for – Binary Large ObjectIt stores binary data (images, movies, music files) within the database. It stores upto 4GB. 6) CLOBStands for – Character Large ObjectIt stores plain character data like varchar field upto 4GB.

NOTE :-varchar2 – from 10g, varchar & varchar2 are the same. Earlier, varchar was supporting upto 2000 characters and varchar2 was supporting upto 4000 characters.

Page 53: SQL for interview

Create the following tables PRODUCTS

ProdID ( PK )ProdName ( Not Null )Qty ( Chk > 0 )Description ORDERS

ProdID ( FK from products )OrderID ( PK )Qty_sold ( chk > 0 )Price Order_Date

Page 54: SQL for interview

CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ));

Page 55: SQL for interview

create table Products(prodid number(4) Primary key, prodname varchar(10) Not null, qty number(3) check (qty>0), description Varchar(20))

Create table Orders ( prodid number(4) references Products(prodid), orderid number(4) Primary key, qty_sold number(3) check (qty_sold>0), price Number(8,2), Order_dt date )

The new table orders has been created. We can see from the above query how to reference a child table to the parent table using the references keyword.

Page 56: SQL for interview

Creating a table from another table :- Now, we will see how to create a table from another table – i.e, it duplicates all the records and the characterstics of another table. The SQL query for it is as follows,

SQL> create table test3 as 2 select * from dept; Thus we can see that we have created another table temp from the table dept.

Thus, we can see that the table temp has copied the structure of the table dept. Here, we must observe that temp copies all the columns, rows and NOT NULL constraints only from the table dept. It never copies PK, FK, Check constraints. Thus, when in the interview somebody asks you “I have a table which has about 1million records. How do I duplicate it into another table without using Insert keyword and without inserting it individually all the records into the duplicated table ?Answer is - Use the above query of creating a table from another table and explain it.

Page 57: SQL for interview

TRUNCATE It removes all the data permanently, but the structure of the table remains as it is. Ex – SQL > TRUNCATE TABLE test ; DROP It removes both data and the structure of the table permanently from the database. Ex – SQL > DROP TABLE test ;

The functionality of Recycle Bin was introduced in Oracle 10G version only. Thus even though the table has been dropped, we can still restore it using flashback command or we can permanently remove it using the purge command. This concept of Recycle bin was not there in the earlier versions of Oracle.

Recovering Drop Tables (Undo Drop Table)To recover this dropped table a user can type the commandSQL> Flashback table tablename to before drop;

You can also restore the dropped table by giving it a different name like thisSQL> Flashback table emp to before drop rename to emp2;

Page 58: SQL for interview

Permanently deleting table after dropPurge table tableName

Permanently Dropping TablesIf you want to permanently drop tables without putting it into Recycle Bin drop tables with purge command like thisSQL> drop table tablename purge;This will drop the table permanently and it cannot be restored.

Rename Table:It renames a table. Syntax:Rename table_name to new_table_name

Page 59: SQL for interview

ALTER - this query alters / changes the structure of the table (i.e, - adding columns, removing columns, renaming columns etc ).

1. Rename table namealter table table_namerename to new_table_name;2. ) Let us add a new column ‘model_no’ to the table. Alter table table_Name add Column_Name [Constraints]

3.Now let us drop the column model_no from products. Alter table table_Name Drop column Column_Name3) Let us rename the column qty to qty_available. Alter table table_Namerename column Column_Name to New_Column_Name

Page 60: SQL for interview

Assignments1) Create the following tables a) Table name :- STUDENTSregno (PK)name (NN)semesterDOBPhone b) Table name :- BOOKSbookno (PK)bnameauthor c) Table name :- LIBRARYregno (FK from students)bookno (FK from books)DOI –date of issueDOR – date of return

Page 61: SQL for interview

DMLINSERT - insert data into a table UPDATE - updates existing data within a table DELETE - deletes all records from a table.

INSERT: Insert into table_Name Values(v1,v2,v2…)Or Insert into table_Name (column1,column2,…)Values (v1,v1,….)Note:This is how we insert values into a table. All characters and alpha-numeric characters(ex – 10023sdf78) must be enclosed in single quotes (‘ ‘ ) and each value must be separated by comma. Also we must be careful in entering the data without violating the primary key, foreign key , unique constraints.

Page 62: SQL for interview

During an abnormal exit – i.e, shutdown or if the SQL window is closed by mouse click – then all the DML’s will be rolled back automatically. During a normal exit – exit ; - all the DML’s will be auto-committed – and there will be no rollback.

Delete and Truncatea) Delete – deletes whichever records we want to delete from the table

Truncate – deletes all the records whether we want it or not b) Delete – can be undone

Truncate – cannot be undone.

Page 63: SQL for interview

UPDATE :- It updates one or more records. Update Table_Name Set Expression…..For ex – 1) Let us update salary by increasing it by Rs200 and also give commission of Rs100 where empno = 7369. 2) Increase all salary by 10%

DELETEIt deletes one / some / all the records. Ex: Delete from table

Page 64: SQL for interview

TCL (Transaction Control Language)

Any DML change on a table is not a permanent one. We need to save the DML changes in order to make it permanentWe can also undo (ignore) the same DML changes on a table. The DDL changes cannot be undone as they are implicitly saved. ROLLBACK It undoes the DML changes performed on a table. Let us see in the below example how rollback works,

COMMIT It saves the DML changes permanently to the database. Committing after rollback & vice versa will not have any effect

Page 65: SQL for interview

Data transaction Language(DTL)SavePoint

Rollback to savepoint

Data Control language(DCL)

Grant: grant select on emp to hr;

Login as HR

Execute the Bellow queryselect * from scott.emp;

Revoke:Login as Scott revoke select on emp from hr;Login as HR

Page 66: SQL for interview

Difference Between Oracle and SQL Server

SL No Oracle SQL Server

1 Oracle Server is developed by oracle SQL Server is developed by Microsoft

2 It is available in multiple OS’s It is available under only windows

3 Null != Null Null=Null

Page 67: SQL for interview

NORMALIZATION:Normalization is a database design technique which organizes tables in a manner that reduces redundancy and dependency of data.

It divides larger tables to smaller tables and link them using relationships.

The inventor of the relational model Edgar Codd proposed the theory of normalization with the introduction of FirstNormal Form and he continued to extend theory with Second and Third Normal Form. Later he joined with Raymond F. Boyce to develop the theory of Boyce-Codd Normal Form

Let's learn Normalization with practical example –Assume a video library maintains a database of movies rented out. Without any normalization all information is stored in one table as shown below.

Page 68: SQL for interview

1NF RulesEach table cell should contain single value.Each record needs to be unique.

Page 69: SQL for interview

2NF RulesRule 1- Be in 1NFRule 2- Single Column Primary KeyIt is clear that we can't move forward to make our simple database in 2nd Normalization form unless we partition the table above

We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains member information. Table 2 contains information on movies rented.

Page 70: SQL for interview

3NF RulesRule 1- Be in 2NFRule 2- Has no transitive functional dependenciesTo move our 2NF table into 3NF we again need to need divide our table.

Page 71: SQL for interview
Page 72: SQL for interview

Conversion Functions:Conversion function s are used to convert one data type into another data typeThere are two type of conversion Functions 1. Implicit conversion FunctionEx: Select 10+’20’ from dual;

2. Explicit conversion functionEx: Select 10+Ascii(‘A’) from dual;

TO_DATE: Is used to convert into date data typeTO_CHAR: Is used to convert into character data typeTO_NUMBER: is used to convert into number data type

Page 73: SQL for interview

Using TO_CHAR function with dates

TO_CHAR(date, ‘Format model’)

The format model:• It must enclosed with single quotation mark and is case sensitive• Is separated from the date value of a comma

Element of date format:YYYY Full year in numberYEAR year spelled outMM Two digit value for monthMONTH Full name of monthMON Three letter abbreviation of monthDY Three letter abbreviation of dayDAY Full name of dayDD Numeric day of month

Page 74: SQL for interview

Ex: select sysdate,to_char(sysdate,'yyyy year mm month mon dy day dd') from dual/

NVL Functions:

1> NVL(arg1,arg2)• If agr1 is null it returns arg2 • If arg1 is not null then it returns itself

Converts a null to actual values:Data types that can be used are date, character and numbers

Ex:

1.select ename,sal,comm,nvl(comm,0) from emp

2. SQL> select ename,sal,comm,sal+comm, sal+nvl(comm,0) totalsalary from emp;

Page 75: SQL for interview

Accessing tables of other usersProvided that a user has the privilege to access tables of other users also she/he can refer to these tables in her/his queries. Let <user> be a user in the Oracle system and <table> a table of this user. This table can be accessed by other (privileged) users using thecommandselect from <user>.<table>;In case that one often refers to tables of other users, it is useful to use a synonym instead of <user>.<table>. In Oracle-SQL a synonym can be created using the commandcreate synonym <name> for <user>.<table> ;It is then possible to use simply <name> in a from clause. Synonyms can also be created for one's own tables.

Page 76: SQL for interview

Modifying Table- and Column DefinitionsIt is possible to modify the structure of a table (the relation schema) even if rows have alreadybeen inserted into this table. A column can be added using the alter table command

alter table <table> add(<column> <data type> [default <value>] [<column constraint>]);

If more than only one column should be added at one time, respective add clauses need to beseparated by colons. A table constraint can be added to a table usingalter table <table> add (<table constraint>);

Page 77: SQL for interview

The syntax of the command for modifying a column is

alter table <table> modify(<column> [<data type>] [default <value>] [<column constraint>]);

Page 78: SQL for interview

ViewsIn Oracle the SQL command to create a view (virtual table) has the formcreate [or replace] view <view-name> [(<column(s)>)] as<select-statement> [with check option [constraint <name>]];

The optional clause or replace re-creates the view if it already exists. <column(s)> namesthe columns of the view. If <column(s)> is not specified in the view definition, the columns ofthe view get the same names as the attributes listed in the select statement (if possible).

Page 79: SQL for interview

Example: The following view contains the name, job title and the annual salary of employees working in the department 20:create view DEPT20 asselect ENAME, JOB, SAL12 ANNUAL SALARY from EMPwhere DEPTNO = 20;

(or)create view DEPT20 (ENAME, JOB, ANNUAL SALARY) asselect ENAME, JOB, SAL 12 from EMPwhere DEPTNO = 20;

Page 80: SQL for interview

RESUME: Good understanding of RDBMS concepts like constraints, Normalization, Tables

etc. Excellent knowledge of writing SQL queries. Good understanding of SQL concepts like Grouping, Sub queries, Functions etc. Solid understand of SQL Joins (Inner joins, Left join and Right joins and full Joins). Good knowledge of DDL, DML and TCL.


Recommended