SQL Query Interview Questions With Answers: Table - Employeedetails
SQL Query Interview Questions With Answers: Table - Employeedetails
SQL Query Interview Questions With Answers: Table - Employeedetails
in this post we will see some of the most commonly asked SQL
queries in interviews. The questions will start from very basic questions and
then move to more complex problems. Consider the below two tables for most
of the questions asked here.
Table - EmployeeDetails
Table - EmployeeSalary
121 P1 8000
321 P2 1000
421 P1 12000
SELECT FullName
FROM EmployeeDetails
WHERE EmpId IN
(SELECT EmpId FROM EmpolyeeSalary
WHERE Salary BETWEEN 5000 AND 10000);
Ques.4. Write a query to fetch only the first name(string before space)
from the FullName column of EmployeeDetails table.
Ans. In this question, we are required to first fetch the location of the space
character in the FullName field and then extract the first name out of the
FullName field. For finding the location we will use LOCATE method in mySQL
and CHARINDEX in SQL SERVER and for fetching the string before space, we
will use SUBSTRING OR MID method.
mySQL- Using MID
SELECT MID(FullName, 0, LOCATE(' ',FullName)) FROM EmployeeDetails;
Also, we can use LEFT which returns the left part of a string till specified number
of characters.
SELECT LEFT(FullName, CHARINDEX(' ',FullName) - 1) FROM EmployeeDetails;
Ques.6. Write a SQL query to fetch all the Employees who are also
managers from EmployeeDetails table.
Ans. Here, we have to use Self-Join as the requirement wants us to analyze
the EmployeeDetails table as two different tables, each for Employee and
manager records.
Ques.10. Write a SQL query to fetch only odd rows from table.
Ans. This can be achieved by using Row_number in SQL server-
Ques.11. Write a SQL query to fetch only even rows from table.
Ans. Using the same Row_Number() and checking that the remainder when
divided by 2 is 0-
Ques.12. Write a SQL query to create a new table with data and
structure copied from another table.
Ans. Using SELECT INTO command-
This can also done using mySQL 'Like' command with CREATE statement-
Ques.15. Write a SQL query to fetch records that are present in one
table but not in another table.
Ans. Using MINUS-
SELECT NOW();
SQL Server-
SELECT getdate();
Oracle-
Ques.17. Write a SQL query to fetch all the Employees details from
EmployeeDetails table who joined in Year 2016.
Ans. Using BETWEEN for the date range '01-01-2016' AND '31-12-2016'-
Ques.19. Write SQL query to find the nth highest salary from table.
Ans. Using Top keyword (SQL Server)-
SELECT Salary
FROM EmployeeSalary Emp1
WHERE 2 = (
SELECT COUNT( DISTINCT ( Emp2.Salary ) )
FROM EmployeeSalary Emp2
WHERE Emp2.Salary > Emp1.Salary
)
SELECT Salary
FROM EmployeeSalary Emp1
WHERE N-1 = (
SELECT COUNT( DISTINCT ( Emp2.Salary ) )
FROM EmployeeSalary Emp2
WHERE Emp2.Salary > Emp1.Salary
)
Also, we recommend that you first try to form queries by yourself rather than just
reading them from the post. Try to find answers on your own.
But you can’t start until the required sample data is not in place. You can check out the
tables below that we’ve provided for practice. So first of all, you need to create the test
data in your database software.
By the way, we have a bunch of other posts available for SQL interview preparation. So
if you are interested, then follow the link given below.
To prepare the sample data, you can run the following queries in your database query
executor or on the SQL command line. We’ve tested them with MySQL Server 5.7 and
MySQL Workbench 6.3.8 query browser. You can also download these Softwares and
install them to carry on the SQL exercise.
Q-5. Write An SQL Query To Find The Position Of The Alphabet (‘A’)
In The First Name Column ‘Amitabh’ From Worker Table.
Ans.
The required query is:
Q-11. Write An SQL Query To Print All Worker Details From The
Worker Table Order By FIRST_NAME Ascending.
Ans.
The required query is:
Q-13. Write An SQL Query To Print Details For Workers With The
First Name As “Vipul” And “Satish” From Worker Table.
Ans.
The required query is:
Q-22. Write An SQL Query To Fetch Worker Names With Salaries >=
50000 And <= 100000.
Ans.
The required query is:
Q-23. Write An SQL Query To Fetch The No. Of Workers For Each
Department In The Descending Order.
Ans.
The required query is:
Q-24. Write An SQL Query To Print Details Of The Workers Who Are
Also Managers.
Ans.
The required query is:
Q-26. Write An SQL Query To Show Only Odd Rows From A Table.
Ans.
The required query is:
Q-27. Write An SQL Query To Show Only Even Rows From A Table.
Ans.
The required query is:
Q-30. Write An SQL Query To Show Records From One Table That
Another Table Does Not Have.
Ans.
The required query is:
Q-31. Write An SQL Query To Show The Current Date And Time.
Ans.
Following MySQL query returns the current date:
SELECT CURDATE();
Following MySQL query returns the current date and time:
SELECT NOW();
Following SQL Server query returns the current date and time:
SELECT getdate();
Following Oracle query returns the current date and time:
Q-32. Write An SQL Query To Show The Top N (Say 10) Records Of
A Table.
Ans.
Following MySQL query will return the top n records using the LIMIT method:
Q-33. Write An SQL Query To Determine The Nth (Say N=5) Highest
Salary From A Table.
Ans.
The following MySQL query returns the nth highest salary:
SELECT Salary
FROM Worker W1
WHERE 4 = (
SELECT COUNT( DISTINCT ( W2.Salary ) )
FROM Worker W2
WHERE W2.Salary >= W1.Salary
);
Use the following generic method to find nth highest salary without using TOP or limit.
SELECT Salary
FROM Worker W1
WHERE n-1 = (
SELECT COUNT( DISTINCT ( W2.Salary ) )
FROM Worker W2
WHERE W2.Salary >= W1.Salary
);
Q-39. Write An SQL Query To Fetch The First 50% Records From A
Table.
Ans.
The required query is:
SELECT *
FROM WORKER
WHERE WORKER_ID <= (SELECT count(WORKER_ID)/2 from Worker);
Q-42. Write An SQL Query To Show The Last Record From A Table.
Ans.
The following query will return the last record from the Worker table:
Q-44. Write An SQL Query To Fetch The Last Five Records From A
Table.
Ans.
The required query is:
Q-48. Write An SQL Query To Fetch Nth Max Salaries From A Table.
Ans.
The required query is:
SELECT distinct Salary from worker a WHERE n >= (SELECT count(distinct
Salary) from worker b WHERE a.Salary <= b.Salary) order by a.Salary desc;
Simply put, a JOIN combines records from two separate tables. Oftentimes, we
come upon situations within SQL in which data on two separate tables is linked,
but separated. JOINs help bring that data back together.
Here's an example: let's say we have two tables in a database that tracks sales
from an e-commerce company. One table is called customers, and contains data
individual customers, like first_name and email. The second table is
called orders, and contains information on individual orders that have been
placed — like order_date and product.
Each order in our database is placed by a customer, but we don't keep the
customer's information within the orders table. Why not? Because if the same
customer placed multiple orders, and we kept track of customer information
within the orders table, we'd be duplicating data unnecessarily. By separating
customer information into its own customers table, we can reduce redundancy
and make updates and changes much easier to handle.
So, we include a field called customer_id within each record on the orderstable.
this ID is linked to a customer_id on the customers table, which contains non-
redundant data for each individual customer.
When we want to bring two tables together, we use a JOIN statement to combine
data as necessary.
There are multiple types of JOIN clauses, and they all serve slightly different
functions:
INNER JOIN returns a list of rows for which there is a match in both tables
specified. It's the default join type, so if you just type JOIN without
specifying any other conditions, an INNER JOIN will be used.
LEFT JOIN will return all results from the left table in your statement,
matched against rows in the right table when possible. If a row in the left
table does not contain a corresponding match in the right table, it will still
be listed — with NULL values in columns for the right table.
RIGHT JOIN will return all results from the right table in your statement,
matched against rows in the left table when possible. If a row in the right
table does not contain a corresponding match in the left table, it will still be
listed — with NULL values in columns for the left table.
FULL JOIN will return all results from both the left and the right tables in
your statement. If there are instances in which rows from the left table do
not match the right table or vice versa, all data will still be pulled in — but
SQL will output NULL values in all columns that are not matched.
CROSS JOIN returns the Cartesian product of two tables — in other words,
each individual row of the left table matched with each individual row of the
right table.
Simply put, INNER JOIN should be used when we want to exclude all records that
do not match both of the tables we're joining.
Let's check out an example of this: let's say that we have two tables — one
called students, and one called advisors. The students table contains a field
called advisor_id that references an id within the advisors table:
CREATE TABLE `advisors` (
`advisor_id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
PRIMARY KEY (`advisor_id`)
)
Here's the catch: not all students have an advisor, and not all advisors are
assigned to students:
/*
+------------+------------+------------+------------+
| student_id | first_name | last_name | advisor_id |
+------------+------------+------------+------------+
| 1 | Tanisha | Blake | 2 |
| 2 | Jess | Goldsmith | NULL |
| 3 | Tracy | Wu | 3 |
| 4 | Alvin | Grand | 1 |
| 5 | Felix | Zimmermann | 2 |
+------------+------------+------------+------------+
5 rows in set (0.00 sec)
*/
SELECT * FROM advisors;
/*
+------------+------------+-----------+
| advisor_id | first_name | last_name |
+------------+------------+-----------+
| 1 | James | Francis |
| 2 | Amy | Cheng |
| 3 | Lamar | Alexander |
| 4 | Anita | Woods |
+------------+------------+-----------+
4 rows in set (0.00 sec)
*/
/*
+--------------+--------------+
| student_name | advisor_name |
+--------------+--------------+
| Alvin | James |
| Tanisha | Amy |
| Felix | Amy |
| Tracy | Lamar |
+--------------+--------------+
4 rows in set (0.00 sec)
*/
Since we're using an INNER JOIN the results of this query exclude students for
whom the advisor_id is set to NULL. Let's take a look at what happens when we
use a LEFT JOIN instead:
SELECT s.first_name AS student_name, a.first_name AS advisor_name
FROM students AS s
LEFT JOIN advisors AS a ON s.advisor_id = a.advisor_id;
/*
+--------------+--------------+
| student_name | advisor_name |
+--------------+--------------+
| Alvin | James |
| Tanisha | Amy |
| Felix | Amy |
| Tracy | Lamar |
| Jess | NULL |
+--------------+--------------+
5 rows in set (0.01 sec)
*/
Notice that our data set now contains information on all students, even those for
whom the advisor is set to NULL!
To make this a bit clearer, let's use our example of students and advisors above:
a LEFT JOIN of students onto advisors will show a list of all students, even those
who do not have advisors — because students is the LEFT table:
/*
+--------------+--------------+
| student_name | advisor_name |
+--------------+--------------+
| Alvin | James |
| Tanisha | Amy |
| Felix | Amy |
| Tracy | Lamar |
| Jess | NULL |
+--------------+--------------+
5 rows in set (0.01 sec)
*/
Notice that the advisor 'Anita' is excluded in the table above, because she is not
assigned to any students.
On the other hand, a RIGHT JOIN of students onto advisors will show a list of all
students who are assigned to advisors, plus a list of advisors not assigned to
students — because advisors is the RIGHT table:
/*
+--------------+--------------+
| student_name | advisor_name |
+--------------+--------------+
| Alvin | James |
| Tanisha | Amy |
| Felix | Amy |
| Tracy | Lamar |
| NULL | Anita |
+--------------+--------------+
5 rows in set (0.00 sec)
*/
Notice that the student 'Jess' is excluded in the table above, because she is not
assigned to an advisor.
5. How should data be structured to
facilitate JOINclauses in a one-to-many relationship?
Whta about a many-to-many relationship?
This one is a bit trickier, and is an interesting database design question.
The answer: we use an intermediary mapping table with two FOREIGN KEYs.
Consider the following:
CREATE TABLE orders (
order_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
order_placed_date DATE NOT NULL,
);
In this example, we need to use two JOIN statements to link all these tables
together: one to link products_to_orders to products, and one to
link products_to_orders with orders.
Q. How do you list files in a directory?
ls – list directory contents
Q. How do you list all files in a directory, including the hidden files?
ls -a (-a, do not hide entries starting with.)
Q. How do you find out all processes that are currently running?
ps -f (-f does full-format listing.)
Q. How to copy file into directory?
cp /tmp/file_name . (dot mean in the current directory)
Q. How to remove directory with files?
rm -rfdirectory_name
Q. How do you find out the processes that are currently running or a particular user?
ps -au Myname (-u by effective user ID (supports names)) (a – all users)
Q. How do you kill a process?
The syntax for kill is
Directories commands
$ pwd -command is used for knowing user current working directory or you can say print working
directory.
$ cd - similar to DOS cd .it is use to change directory.
$ mkdir - use to create new directory.
$ rmdir - use to remove directory.
$ More filename -List the contents of file pausing after each screen (press Space to continue listing).
$ grep string file-Search file for occurrences of string.
$ less filename - Display filename one screenful.A pager similar to (better than) more.
Suspend terminal output to your system. To resume terminal output, press ^q. ^s is usually referred
to as XON.
To view text a page at a time, use the more command.
^q
Resume terminal output suspended by pressing ^s (see above). ^q is usually referred to as XOFF.
^z
Suspend the foreground process, that is, place the current active program in a paused state.
Type the fg command to reactivate a process in the foreground. A foreground process will usually
keep control of your keyboard and terminal.
Type the bg command to reactivate a process in the background. A background process will let you
type other commands on the keyboard while it is running in a detached state.
^u
Erase command line.
^w
Erase previous word on a UNIX command line. A word is a string of characters separated by a
space or tab.
OTHER COMMANDS
$ print file -Send file to the UNIX laser printer.
$ man command - Display information about command.
$ apropos keyword - List commands/programs that contain keyword in their description.
$ du - List the number of Kbytes for each directory below current working directory.
$ talk username - Interactively communicate with username; username has to be logged-in.
$ finger username - Find the username for username.
$ w - Display current activity on the system.
$ who - Show users that are currently logged-in.
$ tin - A program to read a collection of newsgroups (new articles arrive daily).
$ help [command] - If specified without command, a brief introduction is listed.If command is
specified, help displays the man page for command.
$ pine - Send email through the Internet
$ quota –v - Display disk usage and disk quota. This command does not display your email quota.
$ mydiskspace - Display uhunix disk usage only. This command does not display your email quota.
$ write username - Writes files or text to username.
$ !! - Repeats last command.
Process management
$ kill - Command use to terminate process.example: kill - 5555
$ nice program name - Command use to run program with lower priority.Recommended for running
background processes.
Preview changes,
before merging:
https://www.guru99.com/agile-scrum-extreme-testing.html
Planning
Requirements Analysis
Design
Coding
Acceptance Testing.
What is Agile?
Agile model believes that every project needs to be handled differently and
the existing methods need to be tailored to best suit the project
requirements. In Agile, the tasks are divided to time boxes (small time
frames) to deliver specific features for a release.
Iterative approach is taken and working software build is delivered after each
iteration. Each build is incremental in terms of features; the final build holds
all the features required by the customer.
The most popular Agile methods include Rational Unified Process (1994),
Scrum (1995), Crystal Clear, Extreme Programming (1996), Adaptive
Software Development, Feature Driven Development, and Dynamic Systems
Development Method (DSDM) (1995). These are now collectively referred to
as Agile Methodologies, after the Agile Manifesto was published in 2001.
Easy to manage.
An overall plan, an agile leader and agile PM practice is a must without which it
will not work.
Each of these stages have a definite Entry and Exit criteria; , Activities &
Deliverables associated with it.
Exit Criteria: Exit Criteria defines the items that must be completed before testing
can be concluded
You have Entry and Exit Criteria for all levels in the Software Testing Life Cycle
(STLC)
In an Ideal world you will not enter the next stage until the exit criteria for the
previous stage is met. But practically this is not always possible. So for this tutorial,
we will focus on activities and deliverables for the different stages in STLC life cycle.
Lets look into them in detail.
Requirement Analysis
During this phase, test team studies the requirements from a testing point of view to
identify the testable requirements.
The QA team may interact with various stakeholders (Client, Business Analyst,
Technical Leads, System Architects etc) to understand the requirements in detail.
Requirements could be either Functional (defining what the software must do) or
Non Functional (defining system performance /security availability )
Automation feasibility for the given testing project is also done in this stage.
Activities
Deliverables
RTM
Automation feasibility report. (if applicable)
Test Planning
Typically , in this stage, a Senior QA manager will determine effort and cost
estimates for the project and would prepare and finalize the Test Plan. In this phase,
Test Strategy is also determined.
Activities
Deliverables
Activities
Deliverables
Test cases/scripts
Test data
Activities
Deliverables
Test Execution
During this phase the testers will carry out the testing based on the test plans and
the test cases prepared. Bugs will be reported back to the development team for
correction and retesting will be performed.
Activities
Deliverables
Activities
Deliverables
Finally, summary of STLC Phases along with Entry and Exit Criteria
STLC Stage Entry Criteria Activity Exit Criteria Deliverables
Prepare RequirementTraceability
Matrix (RTM).
Test Planning Requirements Analyze various testing approaches Approved test Test
Documents available plan/strategy plan/strategy
document. document.
Requirement Finalize on the best suited approach
Traceability matrix. Effort estimation Effort estimation
Preparation of test plan/strategy document signed document.
Test automation document for various types of off.
feasibility document. testing
Test case Requirements Create test cases, test design, Reviewed and Test
development Documents automation scripts (where signed test cases/scripts
applicable) Cases/scripts
RTM and test plan Test data
Review and baseline test cases and Reviewed and
Automation analysis scripts signed test data
report
Create test data
Test Environment System Design and Understand the required Environment setup Environment
setup architecture architecture, environment set-up is working as per ready with test
documents are the plan and data set up
available Prepare hardware and software checklist
development requirement list Smoke Test
Environment set-up Test data setup is Results.
plan is available Finalize connectivity requirements complete
Test Execution Baselined RTM,Test Execute tests as per plan All tests planned Completed RTM
Plan , Test case/scripts are executed with execution
are available Document test results, and log status
defects for failed cases Defects logged and
Test environment is tracked to closure Test cases
ready Update test plans/test cases, if updated with
necessary results
Test data set up is
done Map defects to test cases in RTM Defect reports
Test Cycle closure Testing has been Evaluate cycle completion criteria Test Closure
completed based on - Time,Test coverage , Cost report signed off
, Software Quality , Critical Business by cli
Test results are Objectives
available
Prepare test metrics based on the
Defect logs are above parameters.
available
Document the learning out of the
project
It is used to track the requirements and to check the current project requirements
are met.
What is RTM (Requirement Traceability Matrix)?
Requirement Traceability Matrix or RTM captures all requirements proposed by the
client or software development team and their traceability in a single document
delivered at the conclusion of the life-cycle.
In other words, it is a document that maps and traces user requirement with test
cases. The main purpose of Requirement Traceability Matrix is to see that all test
cases are covered so that no functionality should miss while doing Software testing.
Requirement ID
Risks
Requirement Type and Description
Trace to design specification
Unit test cases
Integration test cases
System test cases
User acceptance test cases
Trace to test script
Here the scenario is that the customer should be able to login to Guru99 banking
website with the correct password and user#id while manager should be able to
login to the website through customer login page.
"Verify Login, when correct ID and Password is entered, it should login successfully"
Step 2: Identify the Technical Requirement that this test case is verifying. For our
test case, the technical requirement is T94 is being verified.
Step 3: Note this Technical Requirement (T94) in the Test Case.
Step 6: Do above for all Test Cases. Later Extract the First 3 Columns from your
Test Suite. RTM in testing is Ready!
Advantage of Requirement Traceability Matrix
It confirms 100% test coverage
It highlights any requirements missing or document inconsistencies
It shows the overall defects or execution status with a focus on business
requirements
It helps in analyzing or estimating the impact on the QA team's work with
respect to revisiting or re-working on the test cases