L4 SQL
L4 SQL
Database
LET’S START WITH SQL :)
Database
MySQL MongoDb
Oracle
MariaDB,
LET’S START WITH SQL :)
Why SQL?
I
LET’S START WITH SQL :)
SQL ( Structured Query Language)
I
LET’S START WITH SQL :)
How SQL helps us ?
SQL commands are divided into different categories based on their functionalities.
Databse- School
table1- Student (Sname, Rollno)
table2-Teacher(Tname,Tid)
School Hospital
Patient
Course Fees
LET’S START WITH SQL :)
Creation of Database
IF NOT EXISTS and IF EXISTS clauses are commonly used in conjunction with the
CREATE TABLE and DROP TABLE statements to avoid errors
LET’S START WITH SQL :)
Deletion of Database
Deleting a Database
We use the DROP DATABASE statement to delete a database.
Dropping a database means deleting the entire database, including all tables,
data, and other objects within it. DROP Is a DDL Command.
These commands are not case-sensitive.
Using a Database
We use the USE DATABASE statement to use a database
These commands are not case-sensitive.
Showing a Database
We use the SHOW DATABASES statement to see all the databses present in a
server.
Command:
Creating a table
employee
CREATE- DDL Command
empId name salary
Example:
USE instagramDb;
LET’S START WITH SQL :)
Step 3 : Create tables into the db
5. DECIMAL(p, s) - Used for exact numeric representation. p is the precision and s is the
scale.
Command :
Command :
Command :
Command :
Command :
3.BLOB (Binary Large Object)- Used for storing large amounts of binary data.(var len)
Command :
Unique constraint: Ensures values in a column are unique across the table.
Not null constraint: Ensures a column cannot have a null value.
Check constraint: Enforces a condition to be true for each row.
Default constraint: Provides a default value for a column if no value is specified.
Primary key : Enforces the uniqueness of values in one or more columns
Foreign key: Enforces a link between two tables by referencing a column in one
table that is a primary key in another table.
LET’S START WITH SQL :)
Constraints in SQL
Unique constraint:
CREATE TABLE example1 (
phoneNbr INT UNIQUE);
Check constraint:
CREATE TABLE example1 (
age INT CHECK (age >= 18));
Default constraint:
CREATE TABLE example1 (
enrolled VARCHAR(20) DEFAULT 'no' );
LET’S START WITH SQL :)
Constraints in SQL
Keys in SQL
Primary key- A primary key is a unique identifier for each record in the table.
It ensures that each row can be uniquely identified and accessed within the
table.
Foreign key-A foreign key is a field in a table that refers to the primary key of
another table. It establishes relationships between tables.
LET’S START WITH SQL :)
Primary Key : A primary key is a key which uniquely identifies each record in a table.
It ensures that each tuple or record can be uniquely identified within the table.
It is always Unique+ Not null
ID Name Hometown
Student Subject
(Base/referenced table) (referencing table)
Roll Roll
Name Hometown Name subject
no no
Student Subject
(Base/referenced table) (referencing table)
Student Course
Base/referenced/parent table Refrencing/child table
LET’S START WITH SQL :)
Foreign Key
Foreign key helps to perform operations related to the parent table, such as joining
tables or ensuring referential integrity.
Query :
These cascading actions help maintain the integrity of the data across related
tables in the database.
QUERY:
CREATE TABLE childtableName (
childId INT PRIMARY KEY,
baseId INT,
FOREIGN KEY (baseId) REFERENCES baseTableName(baseId)
ON DELETE CASCADE
);
LET’S START WITH SQL :)
Cascading in Foreign Key
QUERY :
CREATE TABLE childtableName (
childId INT PRIMARY KEY,
baseId INT,
FOREIGN KEY (baseId) REFERENCES parenttableName(childId)
ON UPDATE CASCADE
);
LET’S START WITH SQL :)
Lets make a database for all SQL commands
Let‘s make a Database for a Company
Requirements :
QUERY :
UPDATE table_name
SET columnName1= value1(to be set) , columnName2 =value2(to be set)
WHERE condition;
LET’S START WITH SQL :)
UPDATE Command (Practice Question)
1.Write a query to update the salary for all employees in the 'HR’ department to 50000.
QUERY :
UPDATE employee
SET salary = 50000
WHERE department = “HR”;
LET’S START WITH SQL :)
UPDATE Command (Practice Question)
QUERY :
UPDATE employee
SET name = “raj”
WHERE name = “raaj”;
LET’S START WITH SQL :)
DELETE Command
QUERY:
DELETE FROM table_name
WHERE condition;
LET’S START WITH SQL :)
DELETE Command (Practice Question)
1. Write a query to DELETE all records from the employee table where the department is
'HR'
QUERY :
DELETE FROM employee
WHERE department = “HR”;
LET’S START WITH SQL :)
DELETE Command (Practice Question)
QUERY :
DELETE FROM employee
WHERE name = “raj”;
LET’S START WITH SQL :)
SELECT * FROM tableName; -> to retrieve all the data present in table
LET’S START WITH SQL :)
INSERT CREATE
SELECT
UPDATE ALTER
DELETE DROP
TRUNCATE
RENAME
LET’S START WITH SQL :)
ALTER Command
Let’s see all the things ALTER can help us to do. So mostly it is used to modify
the schema, so we will mostly see how it can help in modification of columns
like - addition of new column, deletion of column, modification of column and
much more
LET’S START WITH SQL :)
ALTER Command
1. ADD a column
Query :
ALTER TABLE tableName
ADD columnName datatype constraint ;
2. Drop a column
Query :
ALTER TABLE tableName
DROP COLUMN columnName ;
LET’S START WITH SQL :)
ALTER Command
3. Modify the data type of an existing column
MODIFY clause : The MODIFY clause is oftenly used within an ALTER TABLE
statement in SQL. It allows us to change the definition or properties of an
existing column in a table.
Query :
ALTER TABLE tableName
MODIFY columnName newdatatype ;
ALTER Command
4. Change the name of an existing columng
CHANGE : The CHANGE command is oftenly used within an ALTER TABLE
statement in SQL. It helps to change the name or data type of a column
within a table.
Query :
ALTER TABLE tableName
CHANGE oldcolumnName newcolumnName newdatatype;
ALTER Command
4. Rename the name of an existing columng
RENAME COMMAND : RENAME command is used to change the name of an
existing database object, such as a table, column, index, or constraint.
Query :
ALTER TABLE tableName
RENAME COLUMN oldcolumnName TO newcolumnName ;
RENAME Command
RENAME : RENAME command is used to change the name of an existing
database object, such as a table, column, index, or constraint.
RENAME Command
Query (Column Renaming ) :
ALTER TABLE tablename
RENAME COLUMN oldcolumnname TO newcolumnname;
TRUNCATE Command
TRUNCATE command - This command removes all rows from the given
table, leaving the table empty but preserving its structure,
QUERY :
TRUNCATE TABLE tableName;
LET’S START WITH SQL :)
DISTINCT - DISTINCT keyword is used within the SELECT statement to retrieve unique
values from a column or combination of columns.
Query :
SELECT DISTINCT col1
-> retrieve a list of unique values for col1
FROM tableName;
SELECT DISTINCT col1, col2 ->return unique combinations of col1 & col2
FROM tableName;
LET’S START WITH SQL :)
Operators in SQL
Comparison Operators : equal to (=) , not equal to (<> or !=) , greater than (>)
less than (<), greater than or equal to (>=), less than or equal to (<=)
1. AND : It combines two conditions and returns true if both are true
QUERY: SELECT * FROM employee WHERE city= 'Pune' AND age > 18;
QUERY: SELECT * FROM employee WHERE city= 'Pune' OR age > 18;
3. NOT: It reverses the result of a condition, returns true if the condition is false
IS NULL / IS NOT NULL Operators : IS NULL (checks for null values) , IS NOT
NULL(checks for not null values)
LIKE & Wildcard Operators : LIKE operator is used to search for a specified
pattern in a column. It uses wildcard operators for matching patterns.
QUERY : SELECT * FROM employee WHERE salary BETWEEN 1200 AND 1500;
LET’S START WITH SQL :)
Clauses in SQL
Clauses are like tools/conditions that helps us to make queries more specific
or decide what data to fetch.
WHERE clause
LIMIT CLAUSE
LIMIT clause - The LIMIT clause in SQL is used to restrict the number of rows
returned by a query.
QUERY :
SELECT col1 , col2 FROM tableName
LIMIT noOfRows;
QUERY :
SELECT col1 , col2 FROM tableName
ORDER BY col1 (ASC/DESC), col2 (ASC/DESC)
Practice question
QUERY :
SELECT * FROM employee
WHERE id=1;
LET’S START WITH SQL :)
Practice question
Write a SQL Query to fetch the details of employees having id as 1 and city
as MUMBAI
QUERY :
SELECT * FROM employee
WHERE id=1 AND city = “MUMBAI”;
LET’S START WITH SQL :)
Practice question
Write a SQL Query to fetch the details of employees having salary greater
than 1200 and city as MUMBA a.
QUERY :
SELECT * FROM employee
WHERE salary>1200 AND city = “MUMBAI”;
LET’S START WITH SQL :)
Practice question
Write a SQL Query to fetch the details of employees who are not from
MUMBAI.
QUERY :
SELECT * FROM employee
WHERE city NOT IN ( “MUMBAI”);
LET’S START WITH SQL :)
Practice question
Write a SQL Query to fetch the details of employees having the maximum
salary.
QUERY :
SELECT * FROM employee
ORDER BY salary DESC;
LET’S START WITH SQL :)
Practice question
QUERY :
SELECT * FROM employee
ORDER BY salary DESC
LIMIT 2;
LET’S START WITH SQL :)
Aggregate Functions
Aggregate functions performs some operations on a set of rows and then returns a
single value summarizing the data. These are used with SELECT statements to
perform calculations
COUNT()
SUM()
AVG()
MIN()
MAX()
GROUP_CONCAT()
LET’S START WITH SQL :)
Aggregate Functions
COUNT() - It counts the number of rows in a table or the number of non-null values
in a column.
This counts how many things are in a list or a group.
Query : SELECT count(name) FROM employee ; -> this will tell the number of
employees in a company
LET’S START WITH SQL :)
Aggregate Functions
Query : SELECT SUM(salary) FROM employee ; -> this willl tell the total amount
company is paying to its employees
LET’S START WITH SQL :)
Aggregate Functions
Query : SELECT AVG(salary) FROM employee ; -> this willl tell the avg amount
company is paying to its employees
LET’S START WITH SQL :)
Aggregate Functions
Query : SELECT MIN(salary) FROM employee ; -> this willl tell the minimumn
salary company is paying to its employees
LET’S START WITH SQL :)
Aggregate Functions
Query : SELECT MAX(salary) FROM employee ; -> this willl tell the max salary
company is paying to its employees
LET’S START WITH SQL :)
Grouping data with the GROUP BY clause.
GROUP BY clause - This is used to group rows that have the same values into together. It
helps to organize data into groups so that you can do calculations, like finding totals or
averages, for each group
QUERY :
SELECT col1, aggregateFun(col2)
FROM tableName
GROUP BY col1 ;
QUERY :
SELECT col1, col2 aggregateFun(col3)
FROM tableName
GROUP BY col1 col2
HAVING condition;
WHERE HAVING
used to filter rows from the result based on used to filter rows from the result based on
condition applied to a row before the aggregation condition applied to a row after the aggregation
It is used with SELECT, UPDATE, or DELETE It is used with GROUP BY and aggregate
commands functions
Query :
Select city, COUNT(name) AS no_of_emp
FROM employee
GROUP BY city;
LET’S START WITH SQL :)
Practice Questions
2. Write a query to find the maximum salary of employees in each city in descending
order
Query :
Select city, max(salary) AS max_salary
FROM employee
GROUP BY city
ORDER BY DESC;
LET’S START WITH SQL :)
Practice Questions
3. Write a query to display the department names alongside the total count
of employees in each department, sorting the results by the total number of
employees in descending order.
Query :
4. Write a query to list the departments where the average salary is greater
than 1200, also display the department name and the average salary.
Query :
Joins are used to combine rows from two or more tables based on a related or
shared or common column between them. There are commonly 4 types of joins
including INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN, SELF JOIN , CROSS
JOIN.
3 103 PhE
3 Ram 17
Student Course
LET’S START WITH SQL :)
Joins in SQL
1. Inner Join
rollno name rollno c_name
3 Eng
2 Rahul
A B 3 Riti 4 Maths
Student Course
LET’S START WITH SQL :)
Joins in SQL
2 Hindi
Left Right 1 Ram
table table
3 Eng
2 Rahul
4 Maths
A B 3 Riti
Student Course
LET’S START WITH SQL :)
Joins in SQL
3 Eng
2 Rahul
A B 3 Riti 4 Maths
Student Course
LET’S START WITH SQL :)
Joins in SQL
Left Right
2 Hindi
table table 1 Ram
3 Eng
2 Rahul
A B 3 Riti 4 Maths
Student Course
LET’S START WITH SQL :)
Joins in SQL
5. Self Join
rollno name
1 Ram
2 Rahul
A 3 Riti
Student
LET’S START WITH SQL :)
Joins in SQL
6. Cross Join
rollno name rollno c_name
2 Hindi
1 1 1 Ram
2 2
3 3 3 Eng
2 Rahul
3 Riti 4 Maths
A B
Student Course
LET’S START WITH SQL :)
Joins in SQL
1. Inner Join : It helps us in getting the rows that have matching values in both
tables, according to the given join condition.
102 Fruit
SELECT columns 101 Ram
FROM table1
103 Ball
INNER JOIN table2 102 Rahul
ON table1.colName = table2.colName;
103 Riti 104 Utensils
Customer Order
LET’S START WITH SQL :)
Joins in SQL
Query: It only returns rows where there is a
matching id in both tables id name id o_name
102 Fruit
SELECT * 101 Ram
FROM customer
103 Ball
INNER JOIN order 102 Rahul
ON customer.id = order.id;
103 Riti 104 Utensils
id name id o_name
customer Order
102 Rahul 102 Fruit
2. Left Join/Left Outer Join : It is used to fetch all the records from the left
table along with matched records from the right table.
If there are no matching records in the right table, NULL values are returned for
the columns of the right table.
Query:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.colName = table2.colName;
Left table : the table specified before the LEFT JOIN keyword
Right table : the table specified after the LEFT JOIN keyword
LET’S START WITH SQL :)
Joins in SQL
Query:
id name id o_name
SELECT *
FROM customer 101 Ram 102 Fruit
3. Right Join/ Right Outer Join : It is used to fetch all the records from the right
table along with matched records from the left table.
If there are no matching records in the left table, NULL values are returned for
the columns of the left table.
Query:
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.colName = table2.colName;
Left table : the table specified before the RIGHT JOIN keyword
Right table : the table specified after the RIGHT JOIN keyword
LET’S START WITH SQL :)
Joins in SQL
Query:
FROM customer
102 Fruit
RIGHT JOIN order 101 Ram
ON customer.id = order.id;
102 Rahul 103 Ball
4. Full Join/Full Outer Join: It returns the matching rows of both left and right
table and also includes all rows from both tables even if they don’t have
matching rows.
If there is no match, NULL values are returned for the columns of the missing
table.
In MySQL, the syntax for a full join is different compared to other SQL databases like
PostgreSQL or SQL Server.
MySQL does not support the FULL JOIN keyword directly. So we use a combination of
LEFT JOIN, RIGHT JOIN, and UNION to achieve the result.
LET’S START WITH SQL :)
Joins in SQL
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.colName = table2.colName;
UNION
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.colName = table2.colName;
LET’S START WITH SQL :)
Joins in SQL
Query:
UNION
SELECT * 103 Riti 104 Utensils
FROM customer
RIGHT JOIN order
customer
ON customer.id = order.id; Order
LET’S START WITH SQL :)
Joins in SQL
id name id o_name
Result :
102 Rahul 102 Fruit
5. CrossJoin: It combines each row of the first table with every row of the
second table.
id name o_id o_name
Query:
101 Ram 1 Fruit
SELECT *
FROM table1 102 Rahul 2 Ball
Customer Order
It results in a new table where the number of rows is equal to the product of
the number of rows in each table. (m*n)
LET’S START WITH SQL :)
Joins in SQL
6. Self Join: A self join in SQL is a type of join where a table is joined with itself.
It is a type of inner join.
Query:
SELECT columns
FROM table as t1
JOIN table as t2
ON t1.colName = t2.colName
t1 and t2 are aliases for the table, used to distinguish between the order rows.
LET’S START WITH SQL :)
Joins in SQL
Ram (Mentor)
s_id name mentor_id
3 Riti 1
Query :
SELECT s1.name as mentor_name, s2.name 4 Riya 3
as name
FROM student as s1
JOIN student as s2
WHERE s1.s_id=s2.mentor_id
LET’S START WITH SQL :)
Joins in SQL
mentor_name name
Ram Rahul
Riti Riya
LET’S START WITH SQL :)
Exclusive Joins in SQL
Exclusive joins are used when we want to retrieve data from two tables excluding matched
rows. They are a part of outer joins or full outer join.
Types :
A B A B A B
LET’S START WITH SQL :)
Exclusive Joins in SQL
Left Exclusive JOIN: When we retrive records from the left table excluding the ones
matching in both left and right table .
id name id o_name
Query:
101 Ram 102 Fruit
SELECT columns
102 Rahul 103 Ball
FROM table1
LEFT JOIN table2
103 Riti 104 Utensils
ON table1.colName = table2.colName;
WHERE table2.colName IS NULL;
customer
Order
LET’S START WITH SQL :)
Exclusive Joins in SQL
Right Exclusive JOIN: When we retrive records from the right table excluding the ones
matching in both left and right table .
id name id o_name
Query:
101 Ram 102 Fruit
SELECT columns
FROM table1 102 Rahul 103 Ball
Full Exclusive JOIN: When we retrive records from the right table and left table excluding
the ones matching in both left and right table .
Query:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.colName = table2.colName;
WHERE table2.colName IS NULL;
UNION
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.colName = table2.colName;
WHERE table1.colName IS NULL;
LET’S START WITH SQL :)
UNION Operator in SQL
UNION: UNION operator in SQL is used to combine the results of two or more SELECT
queries into a single result set and gives unique rows by removing duplicate rows.
QUERY:
id id id
SELECT columns
FROM table1 1 2 1
UNION
SELECT columns 2 3 2
FROM table2;
3 4 3
4
LET’S START WITH SQL :)
UNION ALL Operator in SQL
UNION ALL: UNION operator in SQL is used to combine the results of two or more SELECT
queries into a single result set and gives all rows by not removing duplicate rows.
QUERY:
SELECT columns
FROM table1
UNION ALL
SELECT columns
FROM table2;
LET’S START WITH SQL :)
UNION ALL Operator in SQL
id id id
1 2 1
2 3 2
3 4 3
4
LET’S START WITH SQL :)
SQL Subqueries/Nested queries
Outer Query
Inner Query
LET’S START WITH SQL :)
SQL Subqueries/Nested queries
QUERY:
SELECT columns, (subquery)
FROM tableName;
LET’S START WITH SQL :)
SQL Subqueries/Nested queries
QUERY:
SELECT *
FROM tableName
WHERE column name operator (subquery);
LET’S START WITH SQL :)
SQL Subqueries/Nested queries
QUERY:
SELECT *
FROM subquery AS altName ;
LET’S START WITH SQL :)
SQL Subqueries/Nested queries
1. Find all the employees who have salary greater than the min salary
QUERY:
SELECT AVG(salary) FROM employee
To find all the employees having salary greater than min salary
QUERY:
SELECT name, salary
FROM employee
WHERE salary > (subquery)
LET’S START WITH SQL :)
SQL Subqueries/Nested queries
Find employee having the min age 2 Afsara 26 'HR' 'Pune' 2000
QUERY:
SELECT MIN(age) FROM employee
QUERY:
SELECT name, age
FROM employee
WHERE age =(subquery);
LET’S START WITH SQL :)
SQL Subqueries/Nested queries
Find employee having age> min age 2 Afsara 26 'HR' 'Pune' 2000
QUERY:
SELECT min(age) AS min_age FROM employee;
QUERY:
SELECT emp.name
FROM employee emp, (subquery) AS subquery
WHERE emp.age > subquery.min_age;
LET’S START WITH SQL :)
SQL Subqueries/Nested queries
1. Print the employees with the average age and age of employees
Print the employee age and avg_age 2 Afsara 26 'HR' 'Pune' 2000
QUERY:
SELECT AVG(age) FROM employee
QUERY:
SELECT (subquery)AS avg_age , age
FROM employee;
LET’S START WITH SQL :)
Nth Highest Salary
Step 1: Select the column which you want to show the final result i.e salary.
Step 2: Order the salary in descending order so that you have the max at the first.
Step 3: Now the value of n could 1,2,3....till n, so we have to make the query in such a
way so that whatever be the value of n it can provide the result.
Step 4: So at the end of the query we will provide a LIMIT so that on the data set
which we have got after ordering the salary in descending order, we can fetch the
nth highest one.
LET’S START WITH SQL :)
Nth Highest Salary
LIMIT- LIMIT clause is used to restrict the number of rows returned by a query.
QUERY:
SELECT DISTINCT Salary
FROM tableName
ORDER BY Salary DESC
LIMIT n-1, 1;
LET’S START WITH SQL :)
Stored Procedures
Stored Procedure- These are programs that can perform specific tasks
based on the stored query. It is basically a collection of pre-written SQL
statements grouped together under a specific name.
Query: (to create a procedure)
CREATE PROCEDURE procedureName()
BEGIN
Query
END;
Query 1:
CREATE PROCEDURE getAllOrderDetails()
BEGIN
Select * from orders;
END;
Query 1:
DELIMITER /
CREATE PROCEDURE getAllOrderDetails()
BEGIN
SELECT * FROM orders;
END/
DELIMITER ;
Examples: Return the details of the order by id (Stored procedure with params)
Query 2:
CREATE PROCEDURE getAllOrderDetailsById(IN id int)
BEGIN
SELECT *FROM Orders WHERE id = id;
END;
QUERY:
CREATE VIEW viewName AS
SELECT columns FROM baseTableName; (Specify the columns to be
included in the view)
QUERY:
SELECT * FROM viewName ;
To drop a view
QUERY:
DROP VIEW IF EXISTS viewName;
LET’S START WITH SQL :)
CASE AND IF IN SQL
CASE: It allows you to perform conditional logic within a query. It can be used in
both SELECT and UPDATE statements to evaluate conditions and return specific
values based on those conditions.
QUERY:
CASE
WHEN condition1 THEN result1 WHEN
condition2 THEN result2 ... ELSE resultN
END
LET’S START WITH SQL :)
CASE with Select statement
Q. Categorise the students on basis of their percentage to Top, Pass and fail in a new
column category
QUERY:
SELECT sid, name, percentage,
CASE
WHEN percentage > 90 THEN ’Top’
WHEN percentage BETWEEN 89 AND 34 THEN ‘Pass’
ELSE ‘Fail’
END AS category
FROM student;
LET’S START WITH SQL :)
CASE with Update statement
Q. Students have got some grace marks so update their grades. Where its A update to A+
and where its B update to A.
QUERY:
UPDATE student
SET grade = CASE
WHEN grade= = ‘B’ THEN ‘A’
WHEN grade = ‘A’ THEN ‘A+’
END;
LET’S START WITH SQL :)
IF IN SQL
IF: It is used to return one of two values depending on whether a condition is true or
false. It is not supported in may DB but supported in MySQL
QUERY:
IF(condition, value_if_true, value_if_false)
LET’S START WITH SQL :)
IF with Select statement
Q. Categorise the students on basis of their percentage to Top, Pass and fail in a new
column category
QUERY:
SELECT sid, name, percentage,
IF(percentage > 90, ’Top’ , IF(percentage BETWEEN 89 AND 34, ‘Pass’, ‘Fail’)) AS category
FROM student;
LET’S START WITH SQL :)
IF with Update statement
Q. Swap all 'f' and 'm' values (i.e., change all 'f' values to 'm' and vice versa) with a single
update statement and no intermediate temporary tables.
QUERY:
UPDATE employee
SET gender = if(gender = 'm', 'f', 'm')
LET’S START WITH SQL :)
Top SQL Questions asked in interviews
Q. Write the SQL Query to 1.create a database Company, 2.create a table employee in it
delete/drop the database
Q.Write the SQL Query to 1.create a database Company, 2.create a table employee in it,
delete/drop the database
Q. Write the SQL Query to 1.create a table employee, 2.Insert data into the table employ
3. Update Salary for all people in HR department to 20000 4. Delete data for employee
having empId =1 5. Delete the entire table
Q. Write the SQL Query to 1.create a table employee, 2.Insert data into the table employ
3. Update Salary for all people in HR department to 20000 4. Delete data for employee
having empId =1 5. Delete the entire table
Q.Write a query to find the total number of employees working in the ‘IT’ department’.
COUNT(*) is a SQL aggregate function that returns the total number of rows in a
specified table or query. It counts all the rows, regardless of whether they contain NULL
values or not.
LET’S START WITH SQL :)
Top SQL Questions asked in interviews
Q.Write a query to find all the employees that have their name starting from ‘R’
Condition Query
Q.Write a query to calculate the total salary and average salary in a department
Q.Write a query to find the rows where a department has NULL values
Q.Write a query to find the duplicate rows in employee for column department.
Q. What is SQL?
-> SQL stands for Structured Query Language
It is a standard language used for managing and manipulating databases.
while, TRUNCATE removes all rows from a table without logging individual row
deletions and cannot be rolled back.
LET’S START WITH SQL :)
Top SQL Questions asked in interviews
while, UNION ALL combines the results of two queries and includes all duplicates.
1.Data retrival
SELECT: Use for retrieving data from one or more tables.
2. Data Filtering
WHERE: Filter records based on specific conditions
AND, OR, NOT: Combine multiple conditions.
BETWEEN : Range search
IN: Checks whether a specified value matches any value in a subquery or a list
LIKE : Pattern matching(%, _)
LET’S START WITH SQL :)
Top SQL Questions asked in interviews(Part-2)
How to think on what SQL clause/operator/function to choose?
3. Aggregation on data
AVG(): Returns the average value of a numeric column.
MIN(): Returns the minimum value in a column.
MAX(): Returns the maximum value in a column.
SUM(): Returns the total sum of a numeric column.
COUNT(): Counts the number of non-NULL values in a specified column
COUNT(*) : Counts the total number of rows in a table, including rows with
NULL values.
5. Sorting data
ORDER BY: Sorts the result set by one or more columns.
7. Conditional logic
CASE : Perform conditional logic within a query using WHEN, THEN and ELSE
IF : Return values depending on whether a condition is true or false.
LET’S START WITH SQL :)
Top SQL Questions asked in interviews(Part-2)
Step 2: Check data types, constraints ,primary key, foreign keys, and relationships
between tables
Step 4: Ensure appropriate indexes on columns used in WHERE, JOIN, and ORDER
BY clauses.
LET’S START WITH SQL :)
Top SQL Questions asked in interviews(Part-2)
Leetcode Questions
Leetcode Questions
Swap Salary
Q. Write a solution to swap all 'f' and 'm' values (i.e., change all 'f'
values to 'm' and vice versa) with a single update statement and
no intermediate temporary tables.
LET’S START WITH SQL :)
Top SQL Questions asked in interviews(Part-2)
Leetcode Questions
Duplicate Emails
Q.Write a solution to report all the duplicate emails. Note that it's guaranteed that the
email field is not NULL.
Return the result table in any order.
LET’S START WITH SQL :)
Top SQL Questions asked in interviews(Part-2)
Leetcode Questions
Employees Earning More Than Their Managers
Q. Write a solution to find the employees who earn more than their managers.
LET’S START WITH SQL :)
Top SQL Questions asked in interviews(Part-2)
Leetcode Questions
Not Boring Movies
Q. Write a solution to report the movies with an odd-numbered ID and a description that
is not "boring".
Return the result table ordered by rating in descending order.
LET’S START WITH SQL :)
Top SQL Questions asked in interviews(Part-2)
Leetcode Questions
Classes More Than 5 Students
Write a solution to find all the classes that have at least five students.