SQL Interview
SQL Interview
Database
Database is collection of data in a format that can be easily accessed (Digital)
Database
Table 1 Table 2
Data Data
What is a table?
Student table
SQL Datatypes
They define the type of values that can be stored in a column
Database related Queries
SHOW DATABASES;
SHOW TABLES;
Types of SQL Commands
DDL (Data Definition Language) : create, alter, rename, truncate & drop
Example :
Keys
Primary Key
It is a column (or set of columns) in a table that uniquely identifies each row. (a unique id)
There is only 1 PK & it should be NOT null.
Foreign Key
A foreign key is a column (or set of columns) in a table that refers to the primary key in another table.
There can be multiple FKs.
PRIMARY KEY makes a column unique & not null but used only for one
Constraints
FOREIGN KEY prevent actions that would destroy links between tables
Ex:
3. Drop :
used to delete an existing table along with it’s data and structure.
Ex:
used to remove all rows form a table . while reamining the table structure.
Ex:
5. Rename :
Ex:
1. Select :
Syntax:
select colunm1, column2, ...;
if you want to select all the fields available into table , use the following syntax:
DML commands enable you to insert , update, delete and retrieve data.
Syntax:
INSERT INTO table_name (colname1, colname2)
Ex:
3. DELETE:
Ex:
Where Clause
To define some conditions
Comparison Operators : = (equal to), != (not equal to), > , >=, <, <=
LIKE (The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column) T
There are two wildcards
There are twooften used
wildcards in conjunction
often withwith
used in conjunction thethe LIKE
LIKEoperator:
operator:
- The percent sign
- The (%) represents
percent zero, one,
sign (%) represents orone,
zero, multiple characters
or multiple characters
- The underscore sign
- The (_) represents
underscore one, single
sign (_) represents characterhere
one, single character are two wildcards often used in
conjunction with the LIKE operator:
- The percent sigThere are two wildcards often used in conjunction with the LIKE operator:
- The percent sign (%) represents
Syntax: zero,column1,
SELECT DISTINCT one, orcolumn2
multiple characters
FROM table_name;
- The undeThere are two wildcards often used in conjunction with the LIKE operator:
- The percent sign (%) represents zero, one, or multiple characters
- The underscore sign (_) represents one, single characterrscore sign (_) represents one, single
charactern (%) represents zero, one, or multiple characters
- The underscore sign (_) represents one, single character
EXAMPLE:-
Example: SELECT * FROM employees WHERE first_name LIKE 'J%';
COUNT( )
MAX( )
Get Maximum Marks
MIN( )
SUM( )
AVG( )
Count number of students in each city where max marks cross 90.
General Order
SELECT column(s)
FROM table_name
WHERE condition
GROUP BY column(s)
HAVING condition
ORDER BY column(s) ASC;
Having Clause
Similar to Where i.e. applies some condition on rows.
Used when we want to apply any condition after grouping.
Count number of students in each city where max marks cross 90.
Cascading for FK
On Delete Cascade
When we create a foreign key using this option, it deletes the referencing rows in the child table
when the referenced row is deleted in the parent table which has a primary key.
On Update Cascade
When we create a foreign key using UPDATE CASCADE the referencing rows are updated in the child
table when the referenced row is updated in the parent table which has a primary key.
Joins in SQL
Join is used to combine rows from two or more tables, based on a related column between them.
Types of Joins
Outer Joins
Inner Join
Returns records that have matching values in both tables
Syntax
SELECT column(s)
FROM tableA
INNER JOIN tableB
ON tableA.col_name = tableB.col_name;
SELECT *
Inner Join FROM student
Example INNER JOIN course
ON student.student_id = course.student_id;
student course
Result
Left Join
Returns all records from the left table, and the matched records from
the right table
Syntax
SELECT column(s)
FROM tableA
LEFT JOIN tableB
ON tableA.col_name = tableB.col_name;
SELECT *
Left Join FROM student as s
Example LEFT JOIN course as c
ON s.student_id = c.student_id;
student course
Result
Right Join
Returns all records from the right table, and the matched records
from the left table
Syntax
SELECT column(s)
FROM tableA
RIGHT JOIN tableB
ON tableA.col_name = tableB.col_name;
SELECT *
Right Join FROM student as s
Example RIGHT JOIN course as c
ON s.student_id = c.student_id;
student course
Result
Full Join
Returns all records when there is a match in either left or right table
Syntax in MySQL
LEFT JOIN
UNION
RIGHT JOIN
Full Join
Example
course
student
Result
Think & Ans
Qs: Write SQL commands to display the right exclusive join :
Syntax
SELECT column(s)
FROM table as a
JOIN table as b
ON a.col_name = b.col_name;
Self Join
Example
Employee
Result
Union
It is used to combine the result-set of two or more SELECT statements.
Gives UNIQUE records.
To use it :
every SELECT should have same no. of columns
columns must have similar data types
columns in every SELECT should be in same order
Syntax
SELECT column(s) FROM tableA
UNION
SELECT column(s) FROM tableB
SQL Sub Queries
A Subquery or Inner query or a Nested query is a query within another SQL query.
SELECT column(s)
FROM table_name
WHERE col_name operator
( subquery );
SQL Sub Queries
Example
Get names of all students who scored more than class average.
1. commit :
the commit command is used to permanently save the changes made during a transaction.
once commit is executed , the transaction is considered successful , and changes are made
permanent.
update Employees
set salary = salary * 1.10
where dept = ‘sales’;
commit;
2. Rollback :-
the rollback command is used to undo changes made during the transaction.
it reverts all the changes applied to the database since the transaction began.
Ex:
BEGIN;
UPDATE Inventory
set quantity = quantity - 10
where product_id = 101;
Rollback;
3. SAVEPOINT:
the savepoint command creates a named point with in a transaction , allowing you to set a
point to which you can later rollback needed.
Ex:
BEGIN;
UPDATE accounts
set balance = balance - 100
where acc_id = 131;
savepoint before withdrawal;
Update accounts
set balance = balance + 100
where acc_id = 147;
commit;
DCL (Data Control Language :
the DCL focuses on the management of access rights, permissions and security related aspects
of a database system.
DCL commands are used to control who can access the data, modify the data, or platform
administrative tasks with in a database.
1. GRANT:-
Syntax & Ex :
GRANT previledge_type GRANT select
ON Object_name ON Employees
to user_or_role; to Analyst;
2.REVOKE:
the REVOKE command is used to remove or revoke specific prviledges or permissions that
have been previously granted to users or roles.
REVOKE previledge_type
ON Object_name REVOKE select
to user_or_role; ON employees
from Analyst;
Realtime interview asked interview
questions (Infosys)
1].query to fetch employees whose salary is greater than 50,000.
2].Write a SQL query to find the second highest salary from the Employees table.
4].Retrieve all records where the status is 'Active' from the Users table.
6].Write a query to find all customers who have made more than one purchase.
Normalization devided larger tables into smaller tables and links them using
relationships(primary key, foreign key).
Types Of Normal Forms
After 1 NF
All Non - key attributes are fully functional dependent on the primary key.
After 2 NF
Emp_id Mobile
E1001 1234
T2 E1002 6789
E1002 7890
E1003 6785
Explaination:
Ø Seperated table into 2 table .
Ø 1 table for Emp_id , Name and Dept (depends only on Emp_id)
Ø Another table for Emp_id , Mobile No (Depends on the Composite key)
Ø Eliminated Partial Dependency -
Ø Name, Dept depends only on Emp_id so they are moved to a seperate table.
Ø Mobile no depends on Composite key (Emp_id, Mobile No) so it remains in its own table.
Note:
as Emp_id alone cannot uniquely identify a record with multiple phone numbers.
3NF:
it is in 2 NF
their is No transitive Dependency.
A transitive Dependency is when changing a non - key Column , might cause any other
column to change.
Note :
Dept depends on Emp_id but if additional attribute of a Dept (Ex. Dept_location) . Dept will
have dependencies other than Emp_id . this violates 3 NF.
Steps to convert 3NF
Remove transitive Dependency . create a seperate table for Dept details and Dept as a primary
key.
Emp_id Mobile No
E1001 1234
E1002 6789
E1002 7890
E1003 6785
Table 3 - (3 NF) Dept Details
Dept Dept_Location
IT Pune
Sales Mumbai
HR Delhi
BCNF:
In BCNF every functional Dependency A - > B , then A has be the superkey ( is uniquely
identifies rows in a table ) of that perticular table.
BCNF Violations
Emp_id Mobile No
E1001 1234
E1002 6789
E1003 7890
Table -2B (BCNF) Employees with Multiple Mobiles
Mobile No Emp_id
6789 E1002
7890 E1002
Dept Dept_Location
IT Pune
Sales Mumbai
HR Delhi
Explaination:
Decomposition of Table 2:
1.To address the BCNF violation, Mobile and Emp-id were split into separate tables:
Ø Table 2A ensures that Emp-id as a superkey identifies a unique Mobile.
Ø Table 2B tracks multiple mobile numbers for the same employee.
No BCNF Violations:
for a dependency A -> B if for a single value of A , Multi value of B exist then
relation will be multivalued dependency.
Identifying Multi-Valued Dependencies:
1.The relationship between Mobile and Emp-id suggests a multi-valued dependency. Each
Emp-id can have multiple mobile numbers.
1.There are no multi-valued dependencies in this table, as Name and Dept both depend on
Emp-id.
Emp_id Mobile No
E1001 1234
E1002 6789
E1003 7890
Table -2B1 (4NF) Employees Mobiles numbers
Emp_id Mobile No
E1002 6789
E1002 7890
Mobile No Emp_id
6789 E1002
7890 E1002
Table 3 Dept Details
Dept Dept_Location
IT Pune
Sales Mumbai
HR Delhi
Explanation of Changes:
Now, every non-trivial dependency involves attributes fully dependent on their respective
superkeys.
The tables are now in 4NF, ensuring no redundancy or anomalies due to multi-valued
dependencies.