Sie sind auf Seite 1von 21

SQL Interview Questions and Answers

Q. What is SQL? Structured Query Language, an ANSI (American National Standards Institute) standard language for accessing databases. Using SQL we can Access Oracle, Sybase, DB2, SQL Server, MySQL, DB/400 and other Database Management Systems Q. When SQL was appeared? Structured Query Language appeared in 1974. Q. What are the Usages of SQL? Creating new databases Creating new tables in a database Inserting records in a database Updating records in a database Deleting records from a database Retrieving data from a database Executing queries against a database Creating stored procedures in a database Creating views in a database Setting permissions on tables, procedures, and views Etc Q. What is SQL Process? When we are executing an SQL command for any RDBMS, the system determines the best way to carry out our request and SQL engine figures out how to interpret the task. There are various components included in the process. These components are Query Dispatcher, Optimization engines, Classic Query Engine and SQL query engine etc. Classic query engine handles all non-SQL queries but SQL query engine won't handle logical files. Q. Is SQL supports Programming? No, SQL doesnt have Conditional and Loop statements, using SQL Commands we can access databases. Q. What are the sub sets of SQL?

Q.

Data Manipulation Language Data Definition Language Data Control Language What is Data Manipulation Language?

DML is a language which enables users to access and manipulate data. Data Manipulation Language is used to Perform below Operations: Insertion of data into the database Retrieval of data from the database Updating data in the database Deletion of data in the database Q. What is Data Definition Language? Data Definition Language (DDL) allows us to create, alter, and delete database objects such as schemas, tables, views, sequences, catalogs, indexes, and aliases. Q. What is Data Control Language? Data Control Language (DCL) allows us to control access to the database. 'DCL' commands include'GRANT' to allow specific users to perform specified tasks 'REVOKE' to cancel previously denied or granted permissions Q. What is MS Access? MS Access was launched in 1992 by Microsoft Corporation as part of MS Office. Microsoft Access is entry-level database management software. It is not only an inexpensive but also powerful database for small-scale projects. MS Access uses the Jet database engine which utilizes a specific SQL language dialect (sometimes referred to as Jet SQL). MS Access comes with the professional edition of MS Office package. MS Access is user friendly database management system. Q. What is Oracle? Oracle is a relational database management system developed by 'Oracle Corporation and launched in 1977. Oracle supports all major Operating systems includes, MS Windows. NetWare, UnixWare, OS/2 and most UNIX flavors. Q. What is MS SQL Server? MS SQL Server is a Relational Database Management System developed by Microsoft Inc. Its primary query languages are T-SQL and ANSI SQL. Q. What is Sybase?

Sybase is a computer software company , their primary product is Sybase DBMS, which is a relational database management system based upon structured query language. Q. What is MySQL? MySQL is open source Database Management System, developed by Swedish company MySQL AB. MySQL Supports many different platforms including Microsoft Windows, the major Linux distributions, UNIX, and Mac OS X. MySQL has free and paid versions, depending on its usage (noncommercial/commercial) and features. MySQL comes with a very fast, multithreaded, multi-user, and robust SQL database server. Q. What is DB2? DB2 is the short name used for DATABASE 2. It is relational database product developed by IBM. in 1983 Q. What is DB/400? It is one of the flavors of IBM DB2 Q. What are the categories of operators available in SQL? Arithmetic operators Comparison operators Logical operators

Q. What are Arithmetic operators in SQL?

Operator + (Addition ) - (Subtraction) * (Multiplication) / (Division) % (Modulus)

Description Adds values Subtracts Right side value from Left side value Multiplies values on either side of the operator Divides left hand operand by right hand operand Divides left hand operand by right hand operand and returns remainder

Q. What are Comparison operators in SQL? For example x = 1, y= 2 Operator Example = (x = y) is False != (x != y) is True.

<> > < >= <= !< !>

(x <> y) is true. (x > y) is False (x < y) is True (x >= y) is False (x <= y) is True (x !< y) is False (x !> y) is True.

Note: Comparison Operators return Logical Results Q. What are Logical operators in SQL? Operator Description -----------------NOT Returns TRUE if the following condition is FALSE. Returns FALSE if it is TRUE. AND Returns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE OR Returns TRUE if either component condition is TRUE. Returns FALSE if both are FALSE. Q. What is a Data Relationship and What are they? Database Relationship is the connection between the tables in a database. There are 4 types of relationships, and they are: One to One Relationship One to Many Relationship Many to One Relationship Many to Many Relationship

Q. What are Important Data Types in SQL?

Data Type character integer numeric decimal float date time

Syntax char(x) integer numeric(p,s) decimal(p,s) float(p) date time

character varying bit real smallint

varchar2(x) bit(x) real smallint

Q. How to Create a Database? The SQL CREATE DATABASE statement is used to create new SQL database. Syntax: CREATE DATABASE DatabaseName; Example: SQL> CREATE DATABASE TestData; Q. How to delete a Database? Using DROP DATABASE statement we can delete any existing Database Syntax: DROP DATABASE DatabaseName; Example: SQL> DROP DATABASE TestData; Q. How to Select a Database? USE statement is used to select any existing database in SQL Syntax: USE DatabaseName; Example: SQL> USE TestData; Q. How to view all existing Databases list? SQL> SHOW DATABASES; Q. How to create a Table? CREATE TABLE table_name( column1 datatype, column2 datatype,

column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) ); Q. How to delete a Table? Using Drop Table we can delete a Table Syntax: DROP TABLE table_name; Q. How to add new record into a Table? Using INSERT INTO statement, we can insert new rows Syntax: INSERT INTO TABLE_NAME (column1, column2, column3,...columnN) VALUES (value1, value2, value3,...valueN) Q. How to fetch data from a Database Table? Using SELECT Statement, we can fetch data from a Database Table Syntax: SELECT column1, column2, columnN FROM table_name; Or SELECT * FROM table_name;

SQL Interview Questions and Answers


Structured Query Language (SQL) developed by IBM in 1970s, It is used to communicate with Databases. Most of the Databases Management Systems like Oracle, Sybase, MS SQL Server, MySQL, IBM-DB2 etc... using SQL for communication databases. SQL knowledge is mandatory for Database developers as well as Testers. 1) What are most important DDL Commands in SQL?

CREATE TABLE - creates a new database table ALTER TABLE - alters (changes) a database table DROP TABLE - deletes a database table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index 2) What are the Operators used in SELECT statements? = Equal <> or != Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern

3) How to INSERT Values into Tables? INSERT INTO table_name VALUES (value1, value2,....) INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....) 4) How to Update a Column Name? UPDATE table_name SET column_name = new_value WHERE column_name = some_value 5) How to Delete Columns, Rows? Delete a particular column: DELETE FROM table_name WHERE column_name = some_value Delete All Rows:

DELETE FROM table_name or DELETE * FROM table_name

6) Give an usage for BETWEEN ... AND? SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2 The values can be numbers, text, or dates. 7) What is the use of CASCADE CONSTRAINTS? When this clause is used with the DROP command, a parent table can be dropped even when a child table exists. 8) Why does the following command give a compilation error? DROP TABLE &TABLE NAME; Variable names should start with an alphabet. Here the table name starts with an '&' symbol. 9) Which system tables contain information on privileges granted and privileges obtained? USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD 10) Which system table contains information on constraints on all the tables created?obtained? USER_CONSTRAINTS.

11) State true or false. EXISTS, SOME, ANY are operators in SQL? True.

12) What does the following query do? SELECT SAL + NVL(COMM,0) FROM EMP;? This displays the total salary of all employees. The null values in the commission column will be replaced by 0 and added to salary.

13) What is the advantage of specifying WITH GRANT OPTION in the GRANT command? The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user. 14) Which command executes the contents of a specified file? START or @. 15) Which command displays the SQL command in the SQL buffer, and then executes it? RUN. 16) What command is used to get back the privileges offered by the GRANT command? REVOKE. 17) Which date function is used to find the difference between two dates? MONTHS_BETWEEN. 18) What operator performs pattern matching? LIKE operator. 19) What is the use of the DROP option in the ALTER TABLE command? It is used to drop constraints specified on the table. 20) What operator tests column for the absence of data? IS NULL operator. 21) What are the privileges that can be granted on a table by a user to others? Insert, update, delete, select, references, index, execute, alter, all. 22) Which function is used to find the largest integer less than or equal to a specific value?

FLOOR. 23) Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables? Data Definition Language (DDL). 24) What is the use of DESC in SQL? DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order. Explanation : The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order. 25) What command is used to create a table by copying the structure of another table? CREATE TABLE .. AS SELECTcommand Explanation: To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as in the following. CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2; If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table.

26) What is the output of the following query SELECT TRUNC(1234.5678,-2) FROM DUAL;? 1200. 27) What are the wildcards used for pattern matching.? _ for single character substitution % for multi-character substitution.

28) What's an SQL injection? SQL Injection is when form data contains an SQL escape sequence and injects a new SQL query to be run. 29) What is difference between TRUNCATE & DELETE? TRUNCATE commits after deleting entire table i.e., cannot be rolled back. Database triggers do not fire on TRUNCATE DELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire on DELETE. 30) What is a join? Explain the different types of joins? Join is a query, which retrieves related columns or rows from multiple tables.

Self Join - Joining the table with itself. Equi Join - Joining two tables by equating two common columns. Non-Equi Join Joining two tables by equating two common columns. Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table. 31) What is the sub-query? Sub-query is a query whose return values are used in filtering conditions of the main query. 32) What is correlated sub-query? Correlated sub-query is a sub-query, which has reference to the main query. 33) Explain CONNECT BY PRIOR? Retrieves rows in hierarchical order eg. select empno, ename from emp where. 34) Difference between SUBSTR and INSTR? INSTR (String1, String2 (n, (m)), INSTR returns the position of the m-th occurrence of the string 2 in string1. The

search begins from nth position of string1. SUBSTR (String1 n, m) SUBSTR returns a character string of size m in string1, starting from n-th position of string1. 35) Explain UNION, MINUS, UNION ALL and INTERSECT? INTERSECT - returns all distinct rows selected by both queries. MINUS - returns all distinct rows selected by the first query but not by the second. UNION - returns all distinct rows selected by either query UNION ALL - returns all rows selected by either query,including all duplicates. 36) What is ROWID? ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, rownumber are the components of ROWID. 37) What is the fastest way of accessing a row in a table? Using ROWID. CONSTRAINTS 38) What is an integrity constraint? Integrity constraint is a rule that restricts values to a column in a table. 39) What is referential integrity constraint? Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table.

SQL Queries
Create the following Tables:

LOCATION Location_ID Regional_Group 122 NEW YORK 123 DALLAS 124 CHICAGO 167 BOSTON DEPARTMENT Name ACCOUNTING RESEARCH SALES OPERATIONS

Department_ID 10 20 30 40

Location_ID 122 124 123 167

JOB Job_ID 667 668 669 670 671 672 Function CLERK STAFF ANALYST SALESPERSON MANAGER PRESIDENT

EMPLOYEE
EMPLOYEE_ID 7369 7499 7505 7506 7507 7521 LAST_NAME SMITH ALLEN DOYLE DENNIS BAKER WARK FIRST_NAME JOHN KEVIN JEAN LYNN LESLIE CYNTHIA MIDDLE_NAME Q J K S D D JOB_ID 667 670 671 671 671 670 MANAGER_ID 7902 7698 7839 7839 7839 7698 HIREDATE 17-DEC-84 20-FEB-85 04-APR-85 15-MAY-85 10-JUN-85 22-FEB-85

SAL

8 16 28 27 22 12

Queries based on the above tables:


Simple Queries:

1. List all the employee details 2. List all the department details 3. List all job details 4. List all the locations 5. List out first name,last name,salary, commission for all employees 6. List out employee_id,last name,department id for all employees and rename employee id as ID of the employee, last name as Name of the employee, department id as department ID 7. List out the employees anuual salary with their names only.

Where Conditions:

8. List the details about SMITH 9. List out the employees who are working in department 20 10. List out the employees who are earning salary between 3000 and 4500 11. List out the employees who are working in department 10 or 20 12. Find out the employees who are not working in department 10 or 30 13. List out the employees whose name starts with S 14. List out the employees whose name start with S and end with H 15. List out the employees whose name length is 4 and start with S 16. List out the employees who are working in department 10 and draw the salaries more than 3500 17. list out the employees who are not receiving commission.

Order By Clause:

18. List out the employee id, last name in ascending order based on the employee id. 19. List out the employee id, name in descending order based on salary column 20. list out the employee details according to their last_name in ascending order and salaries in descending order

21. list out the employee details according to their last_name in ascending order and then on department_id in descending order.

Group By & Having Clause:

22. How many employees who are working in different departments wise in the organization 23. List out the department wise maximum salary, minimum salary, average salary of the employees 24. List out the job wise maximum salary, minimum salary, average salaries of the employees. 25. List out the no.of employees joined in every month in ascending order. 26. List out the no.of employees for each month and year, in the ascending order based on the year, month. 27. List out the department id having atleast four employees. 28. How many employees in January month. 29. How many employees who are joined in January or September month. 30. How many employees who are joined in 1985. 31. How many employees joined each month in 1985. 32. How many employees who are joined in March 1985. 33. Which is the department id, having greater than or equal to 3 employees joined in April 1985.

Sub-Queries

34. Display the employee who got the maximum salary. 35. Display the employees who are working in Sales department 36. Display the employees who are working as Clerk. 37. Display the employees who are working in New York 38. Find out no.of employees working in Sales department.

39. Update the employees salaries, who are working as Clerk on the basis of 10%. 40. Delete the employees who are working in accounting department. 41. Display the second highest salary drawing employee details. 42. Display the Nth highest salary drawing employee details

Sub-Query operators: (ALL,ANY,SOME,EXISTS)

43. List out the employees who earn more than every employee in department 30. 44. List out the employees who earn more than the lowest salary in department 30. 45. Find out whose department has not employees. 46. Find out which department does not have any employees.

Co-Related Sub Queries:

47.Find out the employees who earn greater than the average salary for their department.

JOINS
Simple join

48.List our employees with their department names 49.Display employees with their designations (jobs) 50.Display the employees with their department name and regional groups. 51.How many employees who are working in different departments and display with department name. 52.How many employees who are working in sales department.

53.Which is the department having greater than or equal to 5 employees and display the department names in ascending order. 54.How many jobs in the organization with designations. 55.How many employees working in New York.

Non Equi Join:

56.Display employee details with salary grades. 57.List out the no. of employees on grade wise. 58.Display the employ salary grades and no. of employees between 2000 to 5000 range of salary.

Self Join:

59.Display the employee details with their manager names. 60.Display the employee details who earn more than their managers salaries. 61.Show the no. of employees working under every manager.

Outer Join:

61.Display employee details with all departments. 62.Display all employees in sales or operation departments.

Set Operators:

63.List out the distinct jobs in Sales and Accounting Departments. 64.List out the ALL jobs in Sales and Accounting Departments. 65.List out the common jobs in Research and Accounting Departments in ascending order.

Answers
1. SQL > Select * from employee; 2. SQL > Select * from department; 3. SQL > Select * from job; 4. SQL > Select * from loc; 5. SQL > Select first_name, last_name, salary, commission from employee; 6. SQL > Select employee_id id of the employee, last_name name", department id as department id from employee; 7. SQL > Select last_name, salary*12 annual salary from employee 8. SQL > Select * from employee where last_name=SMITH; 9. SQL > Select * from employee where department_id=20 10. SQL > Select * from employee where salary between 3000 and 4500 11. SQL > Select * from employee where department_id in (20,30) 12. SQL > Select last_name, salary, commission, department_id from employee where department_id not in (10,30) 13. SQL > Select * from employee where last_name like S% 14. SQL > Select * from employee where last_name like S%H 15. SQL > Select * from employee where last_name like S___ 16. SQL > Select * from employee where department_id=10 and salary>3500 17. SQL > Select * from employee where commission is Null 18. SQL > Select employee_id, last_name from employee order by employee_id 19. SQL > Select employee_id, last_name, salary from employee order by salary desc 20. SQL > Select employee_id, last_name, salary from employee order by last_name, salary desc 21. SQL > Select employee_id, last_name, salary from employee order by last_name, department_id desc 22. SQL > Select department_id, count(*), from employee group by department_id 23. SQL > Select department_id, count(*), max(salary), min(salary), avg(salary) from employee group by department_id 24. SQL > Select job_id, count(*), max(salary), min(salary), avg(salary) from employee group by job_id 25. SQL > Select to_char(hire_date,month)month, count(*) from employee group by to_char(hire_date,month) order by month

26. SQL > Select to_char(hire_date,yyyy) Year, to_char(hire_date,mon) Month, count(*) No. of employees from employee group by to_char(hire_date,yyyy), to_char(hire_date,mon) 27. SQL > Select department_id, count(*) from employee group by department_id having count(*)>=4 28. SQL > Select to_char(hire_date,mon) month, count(*) from employee group by to_char(hire_date,mon) having to_char(hire_date,mon)=jan 29. SQL > Select to_char(hire_date,mon) month, count(*) from employee group by to_char(hire_date,mon) having to_char(hire_date,mon) in (jan,sep) 30. SQL > Select to_char(hire_date,yyyy) Year, count(*) from employee group by to_char(hire_date,yyyy) having to_char(hire_date,yyyy)=1985 31. SQL > Select to_char(hire_date,yyyy)Year, to_char(hire_date,mon) Month, count(*) No. of employees from employee where to_char(hire_date,yyyy)=1985 group by to_char(hire_date,yyyy),to_char(hire_date,mon) 32. SQL > Select to_char(hire_date,yyyy)Year, to_char(hire_date,mon) Month, count(*) No. of employees from employee where to_char(hire_date,yyyy)=1985 and to_char(hire_date,mon)=mar group by to_char(hire_date,yyyy),to_char(hire_date,mon) 33. SQL > Select department_id, count(*) No. of employees from employee where to_char(hire_date,yyyy)=1985 and to_char(hire_date,mon)=apr group by to_char(hire_date,yyyy), to_char(hire_date,mon), department_id having count(*)>=3 34. SQL > Select * from employee where salary=(select max(salary) from employee) 35. SQL > Select * from employee where department_id IN (select department_id from department where name=SALES) 36. SQL > Select * from employee where job_id in (select job_id from job where function=CLERK 37. SQL > Select * from employee where department_id=(select department_id from department where location_id=(select location_id from location where regional_group=New York)) 38. SQL > Select * from employee where department_id=(select department_id from department where name=SALES group by department_id) 39. SQL > Update employee set salary=salary*10/100 wehre job_id=(select job_id from job where function=CLERK) 40. SQL > delete from employee where department_id=(select department_id from department where name=ACCOUNTING) 41. SQL > Select * from employee where salary=(select max(salary) from employee where salary <(select max(salary) from employee)) 42. SQL > Select distinct e.salary from employee where & no-1=(select count(distinct salary) from employee where sal>e.salary) 43. SQL > Select * from employee where salary > all (Select salary from employee where department_id=30)

44. SQL > Select * from employee where salary > any (Select salary from employee where department_id=30) 45. SQL > Select employee_id, last_name, department_id from employee e where not exists (select department_id from department d where d.department_id=e.department_id) 46. SQL > Select name from department d where not exists (select last_name from employee e where d.department_id=e.department_id) 47. SQL > Select employee_id, last_name, salary, department_id from employee e where salary > (select avg(salary) from employee where department_id=e.department_id) 48. SQL > Select employee_id, last_name, name from employee e, department d where e.department_id=d.department_id 49. SQL > Select employee_id, last_name, function from employee e, job j where e.job_id=j.job_id 50. SQL > Select employee_id, last_name, name, regional_group from employee e, department d, location l where e.department_id=d.department_id and d.location_id=l.location_id 51. SQL > Select name, count(*) from employee e, department d where d.department_id=e.department_id group by name 52. SQL > Select name, count(*) from employee e, department d where d.department_id=e.department_id group by name having name=SALES 53. SQL > Select name, count(*) from employee e, department d where d.department_id=e.department_id group by name having count (*)>=5 order by name 54. SQL > Select function, count(*) from employee e, job j where j.job_id=e.job_id group by function 55. SQL > Select regional_group, count(*) from employee e, department d, location l where e.department_id=d.department_id and d.location_id=l.location_id and regional_group=NEW YORK group by regional_group 56. SQL > Select employee_id, last_name, grade_id from employee e, salary_grade s where salary between lower_bound and upper_bound order by last_name 57. SQL > Select grade_id, count(*) from employee e, salary_grade s where salary between lower_bound and upper_bound group by grade_id order by grade_id desc 58. SQL > Select grade_id, count(*) from employee e, salary_grade s where salary between lower_bound and upper_bound and lower_bound>=2000 and lower_bound<=5000 group by grade_id order by grade_id desc 59. SQL > Select e.last_name emp_name, m.last_name, mgr_name from employee e, employee m where e.manager_id=m.employee_id 60. SQL > Select e.last_name emp_name, e.salary emp_salary, m.last_name, mgr_name, m.salary mgr_salary from employee e, employee m where e.manager_id=m.employee_id and m.salary

61. SQL > Select m.manager_id, count(*) from employee e, employee m where e.employee_id=m.manager_id group by m.manager_id 62. SQL > Select last_name, d.department_id, d.name from employee e, department d where e.department_id(+)=d.department_id 63. SQL > Select last_name, d.department_id, d.name from employee e, department d where e.department_id(+)=d.department_id and d.department_idin (select department_id from department where name IN (SALES,OPERATIONS)) 64. SQL > Select function from job where job_id in (Select job_id from employee where department_id=(select department_id from department where name=SALES)) union Select function from job where job_id in (Select job_id from employee where department_id=(select department_id from department where name=ACCOUNTING)) 65. SQL > Select function from job where job_id in (Select job_id from employee where department_id=(select department_id from department where name=SALES)) union all Select function from job where job_id in (Select job_id from employee where department_id=(select department_id from department where name=ACCOUNTING)) 66. SQL > Select function from job where job_id in (Select job_id from employee where department_id=(select department_id from department where name=RESEARCH)) intersect Select function from job where job_id in (Select job_id from employee where department_id=(select department_id from department where name=ACCOUNTING)) order by function

Das könnte Ihnen auch gefallen