SQL - May
SQL - May
SQL - May
What Is SQL?
SQL is a standard language for storing, manipulating and retrieving data in databases & The Full form Of
SQL is Structured Query Language.
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987
We can learn the SQL Lang. into different database systems like MySQL, SQL Server, MS Access, Oracle,
but in our batch, we learn the SQL by using SQL Server 2014 - database systems.
& Version -We Have SQL Server service version - 12.0. 6024.0.
--------------------------------------------------------------------------------------------------------
Ex. All data of Customer - CustomerID, CustomerName, ContactName, Address, City, PostalCode and
Country this is the information manse data of employee.
What Is Table?
A table is a collection of related/Relational data entries and it consists of columns and rows.
A record/ rows: Contains specific data, like information about a particular Customer or a product.
(A record, also called a row, is each individual entry that exists in a table.)
Fields/ columns- have different types of data, such as text, numbers, dates, and hyperlinks. (A column is
a vertical entity in a table that contains all information associated with a specific field in a table.)
------------------------------------------------------------------------------------------------------------------
Go to the Chrome
Data Type
1) Each column in a database table is required to have a name and a data type.
2) The data type of a column defines what value the column can hold: integer, character, money, date
and time, binary, and so on.
3) The data type is a guideline for SQL to understand what type of data is expected inside of each
column, and it also identifies how SQL will interact with the stored data
String Data
1)CHAR (size)= A FIXED length string (can contain letters, numbers, and special characters).
The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1
2) VARCHAR (size)= A VARIABLE length string (can contain letters, numbers, and special characters).
The size parameter specifies the maximum string length in characters - can be from 0 to 65535
Numeric Data
FLOAT (size, d)
2)DATE= A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-12-31'
3)DATETIME (fsp)= A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The supported range
is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
Data Size
The number of bits per value is specified in size. The size parameter can hold a value from 1 to 64.
The default value for size is 1.
Why need of Size = SQL database administrators often need to estimate how large a database is.
-------------------------------------------------------------------------------------------------------------------
1.DDL
2.DML
3.DQL
4.DCL
5.TCL
DDL -Data Definition Language
DDL is a subset of SQL commands used to create, modify, and delete database structures but not data.
1)Create=This command is used to create the database or its objects (like table, index, function, views,
store procedure, and triggers).
3)Truncate=IS used to remove all records from a table, including all spaces allocated for the records
are removed.
------------------------------------------------------------------------------------------------------------------------
1) Create
Now First we create Database & After that we will create the Table into that
a. CREATE Database
2) CREATE TABLE
Ex
CREATE TABLE My. Family (
First_Name varchar (255),
Education varchar (255),
Profession varchar (255),
Contact_No. int,
Age int,
);
------------------------------------------------------------------------------------------------------------------------
Rules-
HW
DOB DATETIME,
Salary price,
);
selects all the records from the Table (ex. Employee is table name)
------------------------------------------------------------------------------------------------------------------
The SQL commands that deals with the manipulation of data present in the database belong to DML.
-Used to retrieve and work with data in SQL Server and SQL Database.
-Used to make changes to the database, such as: CRUD operations to create, read, update and delete
data. Using INSERT, SELECT, UPDATE, and DELETE commands.
1) Insert = It is used to insert data into a table.
1) Insert
Ex. INSERT INTO Employee (Emp_Id, First_Name, Last_Name, Email, Phone_No, Salary)
OR
2. UPDATE-
The UPDATE TABLE statement is used to update records of the table in the database.
UPDATE Table_Name
SET column_name1 = new_value,
column_name2 = new_value,
...
[WHERE Condition];
Note that the WHERE clause is optional, but you should use it to update the specific record.
An UPDATE statement without the WHERE clause will update values in all the rows of the
table.
UPDATE Table_Name
SET column_name1 = new_value,
column_name2 = new_value,
...
[WHERE Condition];
ex
UPDATE Employee
SET email = '[email protected]'
WHERE EmpId = 10;
Query will change the Email and the PhoneNo in the Employee table whose EmpId is 2.
UPDATE Employee
SET Email = '[email protected]', PhoneNo = '111.111.0007'
WHERE EmpId = 20;
Update Data
ex
UPDATE Employee
SET Salary = Salary + (Salary * 10/100);
------------------------------------------------------------------------------------------------------------------
3. Delete
-Use the DELETE statement to delete records from the existing table in the current schema or tables
of the schema
This DELETE syntax is valid in all the databases such as SQL Server, Oracle, MySQL, PostgreSQL,
SQLite, etc. The WHERE clause is optional.
You can delete the specific record(s) from the table using the WHERE clause.
The following will delete a record from the Employee table where the value of EmpId is 4.
Here we will be found Empty Table But Table entities or Schema is Same as it is.
**You cannot delete the value of a single column using the DELETE statement**. Delete command only
used for Remove the record (row) one by one or all records (row) at a time.
===========================================================
2. Truncate: -
1). The TRUNCATE statement is used to delete all rows from a table in the database.
2). It works the same as the DELETE statement, but you cannot use the WHERE clause with the
TRUNCATE statement.
3). The deleted rows using the TRUNCATE statement cannot be recovered. It deletes the rows
permanently.
**Be careful before deleting a table. Deleting a table results in loss of all information stored in the table! **
==============================================================
3. Drop
Use the DROP TABLE statement to delete a table with data from the database.
DROP COLUMN
Make sure that the original table name is correct, and the new name has not been used with other
database objects; otherwise, it will raise an error.
Operators
=…………………………………… Equal
>……………………………………Greater than
----------------------------------------------------------------------------------------------------------------
SELECT column1, column2,...columnN
FROM table_name
WHERE conditions
=================================================================
NOT BETWEEN
Use the NOT operator with the BETWEEN operator to filter records that do not fall in the specified range.
IN Operator
The IN operator is used to specify the list of values or sub query in the WHERE clause. A sub-query or
list of values must be specified in the parenthesis e.g. IN (value1, value2, ...) or IN (Select query).
NOT IN
Use the NOT operator with the IN operator to filter records that do not fall in the specified values.
LIKE Operator
The LIKE operator is used in the WHERE condition to filter data based on some specific pattern. It can
be used with numbers, string, or date values. However, it is recommended to use the string values.
WHERE First_Name LIKE 'a%' Finds any values that start with "a"
WHERE First_Name LIKE '%a' Finds any values that end with "a"
WHERE First_Name LIKE '%or%' Finds any values that have "or" in any position
WHERE First_Name LIKE '_r%' Finds any values that have "r" in the second position
WHERE First_Name LIKE 'a_%' Finds any values that start with "a" and are at least .
2 characters in length
WHERE First_Name LIKE 'a__%' Finds any values that start with "a" and are at least.
. 3characters in length
------------------------------------------------------------------------------------------------------------------
Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
==================================================================
CONCAT
The following join the First_Name column, a string with white space,Middle_Name column,a string
with white space, and the Last_Name column ,of the Student _record1 table.
From Student_record1;
SQL FUNCTIONS
1. AVG ()-
The AVG () is an aggregate function that is used to find out an average of the list of values of columns
or an expression.
-------------------------------------------------------------------------------------------------------------------
2. COUNT () =
The COUNT() function is an aggregate function that is used to find the number of values in the specified
column excluding NULL values. It can be applied on numeric, character, or date values.
3. MAX () =
The MAX () function is an aggregate function that is used to find the largest value in the given column
or expression.
SELECT MAX(column_name)
FROM table_name
[WHERE condition]
[GROUP BY];
4. MIN () =
The MIN() function is an aggregate function that is used to find the smallest value of given column or
expression. It can be applied on numeric, character or date values.
SELECT MIN(column_name)
FROM table_name
[WHERE condition]
[GROUP BY];
5. SUM () =
The SUM () function is an aggregate function that is used to find the sum (addition) of the given
column or an expression. It can be applied on the numeric values or numeric columns only.
You must use the aggregate functions such as COUNT (), MAX (), MIN (), SUM (), AVG (), etc., in
the SELECT query.
The result of the GROUP BY clause returns a single row for each value of the GROUP BY column.
[WHERE]
The SELECT clause can include columns that are used with the GROUP BY clause.
So, to include other columns in the SELECT clause, use the aggregate functions
like COUNT(), MAX(), MIN(), SUM(), AVG() with those columns.
-The GROUP BY clause must come after the WHERE clause if present and before the HAVING
clause.
-The GROUP BY clause can include one or more columns to form one or more groups based on that
columns.
-Only the GROUP BY columns can be included in the SELECT clause. To use other columns in
the SELECT clause, use the aggregate functions with them.
Emp_Id integer,
Salary integer
);
=================================================================
HAVING clause
The HAVING clause includes one or more conditions that should be TRUE for groups of records. It is like
the WHERE clause of the GROUP BY clause. The only difference is that the WHERE clause cannot be
used with aggregate functions, whereas the HAVING clause can use aggregate functions.
The HAVING clause always comes after the GROUP BY clause and before the ORDER BY clause.
The HAVING condition can only include columns that are used with the GROUP BY clause. To use
other columns in the HAVING condition, use the aggregate functions with them.
Employee Table
2 'James' 'Bond' 1
In the GROUP BY section, we used the following query to retrieve the no of employees in each
department,
Order by clause
The ORDER BY clause can be used in the SELECT query to sort the result in ascending or descending
order of one or more columns.
The ORDER BY clause is used to get the sorted records on one or more columns in ascending or
descending order.
The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in
the query.
Use ASC or DESC to specify the sorting order after the column name. Use ASC to sort the records in
ascending order or use DESC for descending order. By default, the ORDER BY clause sort the records
in ascending order if the order is not specified.
The following query will fetch all the records from the Employee table and sorts the result in ascending
order of the FirstName values.
Abcdefgh
==================================================================
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending
order, use the DESC keyword.
For Numerical
SELECT * FROM Employee
ORDER BY Salary;
For Characters
SELECT * FROM Employee
ORDER BY First_Name;
==================================================================
SQL Constraints
SQL constraints are used to specify rules for data in a table.
Constraints can be specified when the table is created with the CREATE TABLE statement, or
after the table is created with the ALTER TABLE statement.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the table. If there is any violation between the constraint and the data
action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and table level
constraints apply to the whole table.
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
FOREIGN KEY - Prevents actions that would destroy links between tables
CREATE INDEX - Used to create and retrieve data from the database very quickly
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new record, or update
a record without adding a value to this field.
2.UNIQE
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of
columns.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per tab
-----------------------------------------------------------------------------------------------------------------------
3.Primary Key
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple
columns (fields).
-----------------------------------------------------------------------------------------------------------------------
4.FOREING Key
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another
table.
The table with the foreign key is called the child table, and the table with the primary key is called the
referenced or parent table.
Person Table
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the "Persons"
table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the parent table.
------------------------------------------------------------------------------------------------------------------
5. CHECK
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in
other columns in the row.
EX. The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created.
The CHECK constraint ensures that the age of a person must be 18, or older:
--------------------------------------------------------------------------------------------------------------
6.DEFAULT
The default value will be added to all new records, if no other value is specified.
-----------------------------------------------------------------------------------------------------------------------
7.INDEX
Indexes are used to retrieve data from the database more quickly than otherwise. The users cannot see
the indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the indexes
also need an update). So, only create indexes on columns that will be frequently searched against.
Note :- The syntax for creating indexes varies among different databases. Therefore: Check the syntax for
creating indexes in your database.
------------------------------------------------------------------------------------------------------------------------
-
8.DISTINCT
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the
different (distinct) values.
-------------------------------------------------------------------------------------------------
JIONS
A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right
table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the
left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table
Cross join
Self-Join
1)
2)
Create Table Department (
Dept_Id int
Name varchar (200)
);
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.Common column_name = table2.Common column_name;
Or
The above inner join query joins the Employee table and Department table and retrieves records from
both the tables where Employee.DeptId = Department.DeptId.
It only fetches records from both the tables where DeptId in the Employee table matches with
the DeptId of the Department table.
If the DeptId is NULL or not matching, then it won't retrieve those records.
The LEFT JOIN is a type of inner join where it returns all the records from the left table and
matching records from the right table.
Here, the left table is a table that comes to the left side or before the "LEFT JOIN" phrase in the query,
and the right table refers to a table that comes at the right side or after the "LEFT JOIN" phrase.
It returns NULL for all non-matching records from the Left table.
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
The above LEFT JOIN query joins the Employee table and Department table where Employee is the left
table and Department is the right table.
It retrieves all the records from the Employee table and matching records from the Department table
where emp.DeptId = dept.DeptId.
Notice that it only displayed the records from the Department table whose dept.DeptId matches with
the emp.Dept
-------------------------------------------------------------------------------------------
The RIGHT JOIN is the reverse of LEFT JOIN. The RIGHT JOIN query returns all the records from the
right table and matching records from the left table.
Here, the right side table is a table that comes to the right side or after the "RIGHT JOIN" phrase in the
query, and the left table is a table that comes at the left side or before the "RIGHT JOIN" phrase.
The RIGHT JOIN returns NULL for all non-matching records from the left table. In some databases,
it is called RIGHT OUTER JOIN
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
In the above syntax, table2 is the right table and table1 is the left table.
For the demo purpose, we will use the following Employee and Department tables in all examples.
The above RIGHT JOIN query joins the Employee table and Department table where Employee is the left
table and Department is the right table. The above query will display the following result.
==================================================
The FULL JOIN returns all the records all the specified tables. It includes NULL for any non-
matching records.
In some databases, FULL JOIN is called FULL OUTER JOIN. It can return a very large result set
because it returns all the rows from all the tables.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;
SELECT emp.EmpId, emp.FirstName, dept.DeptId, dept.Name
FROM Employee emp
FULL JOIN Department dept
ON emp.DeptId = dept.DeptId;
As you can see, it fetches all the records from both tables. First, it fetches all the records from the left
table Employee and then all the records from the right table Department. It includes NULL for all non-
matching records from both table
let's swap the tables and see how the result will be changed.
DDL-
4.Alter
The ALTER command is a DDL command to modify the structure of existing tables in the database by
adding, modifying, renaming, or dropping columns and constraints.
You can add columns, rename columns, delete columns, or change the data type of columns using the
ALTER command.
Use ALTER TABLE ADD command to add new columns in the database table.
As per the above ALTER TABLE command, use the ADD keyword to add one or more new columns.
Please note that data type names are different in different databases, so use the data types based on the
database you are working.
Stored Procedure-sp
----------------------------------------------------------------------------------------------------------------------
Normalization.
What is Normalization and what are the advantages of it?
Normalization in SQL is the process of organizing data to avoid duplication and redundancy. Some of the
advantages are:
Better Database organization
More Tables with smaller rows
Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on this
technology, you can opt for structured training from edureka!
Assignment
Department_id int,
Name varchar(250),
Location_id int
);
------------------------------------------------------
Job_id int,
Job_Function varchar(250)
);
values (667,'Cleark'),
(668,'Staff'),
(669,'Analyst'),
(670,'SalesPerson'),
(671,'Manager'),
(672,'President');
-------------------------------------
Emp_id int,
Last_name varchar(250),
First_name varchar(250),
Middle_name varchar(250),
Job_id int,
Manager_id int,
Hire_date date,
Salary int,
COMM int,
Department_id int
);
--------------------------------------------------------------------------------------------------
1. List all the employee details
Select * From Employee112;
--------------------------------------------------------
2. List all the department details
Select * from Department2;
-----------------------------------------------------------
3. List all job details
Select * from Job;
--------------------------------------------------------------------------------------------------
4. List all the locations
---------------------------------------------------------------------------------------------------
5. List out first name,last name,salary, commission for all employees
Select First_name, Last_name,Salary, COMM
From Employee112;
--------------------------------------------------------------------------------------------------
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”
from Employee112;
----------------------------------------------------------------------------------------------------
7. List out the employees anuual salary with their names only.
Select First_name, Last_name, (Salary*12) from Employee112;
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
20. list out the employee details according to their last_name in ascending order and
salaries in descending order
Select * from Employee112 order by Last_name, Salary DESC;
--------------------------------------------------------------------------------------------------
21. list out the employee details according to their last_name in ascending order and
then ondepartment_id in descending order.
Select Emp_id, Last_name, Salary, Department_id from Employee112 order by Last_name,
Department_id DESC;
================================================================================================
Group By & Having Clause:
22. How many employees who are working in different departments wise in the
organization
Select Department_id, Count(*)From Employee112 group by Department_id;
------------------------------------------------------------------------------------------------
23. List out the department wise maximum salary, minimum salary, average salary of the
employees
Select Department_id, Count (*) AS ' Count',max(salary) AS' M salary', Min(Salary)' Min
Salary', AVG(Salary)' Avg SAlary'
from Employee112
group by Department_id;
---------------------------------------------------------------------------------------------------
24. List out the job wise maximum salary, minimum salary, average salaries of the
employees.
Select Job_id, Count (*)AS' Count',max(salary) As'Max Salary', Min(Salary) AS' Min
Salary', AVG(Salary) As' Avg Salary'
from Employee112 group by Job_id;
----------------------------------------------------------------------------------------------------
25. List out the no.of employees joined in every month in ascending order.
Select DATENAME (MM, Hire_date) Month, count(*) No_of_Employee from Employee112
group by DATENAME(MM, Hire_date);
----------------------------------------------------------------------------------------------------
26. List out the no.of employees for each month and year, in the ascending order based
on the year, month.
Select DATEPart (YYYY, Hire_date) Year,
DateName (MM, Hire_date) Month,
Count(*) NoOfEmployee from Employee112 group by Datepart(YYYY, Hire_date) ,
Datename(MM, Hire_date) ;
-----------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------
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.
Select * from Employee112 where salary=(select max(Salary) from Employee112);
-------------------------------------------------------------------------------------------------------
35. Display the employees who are working in Sales department
Select * from Employee112 where Department_id IN (select Department_id from Department2
where name='SALES');
---------------------------------------------------------------------------------------------------
36. Display the employees who are working as “Clerk”.
Select * from Employee112 where Job_id IN (select Job_id from Job where Job_Function
='Cleark');
----------------------------------------------------------------------------------------------
37. Display the employees who are working in “New York”
------------------------------------------------------------------------------------------------
38. Find out no.of employees working in “Sales” department.
Select * from Employee112 where Department_id IN
(select Department_id from Department2 where name='SALES');
----------------------------------------------------------------------------------------------
39. Update the employees salaries, who are working as Clerk on the basis of 10%.
===============================================================================
Joins
Simple join
-----------------------------------------------------------------------------------
49.Display employees with their designations (jobs)
SELECT Emp_id,Last_name, Salary,E.Department_id, Job_Function FROM Employee112 E
INNER JOIN Job J ON E.Job_id=J.Job_id;
------------------------------------------------------------------------------------
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
Select Name AS ' Department_name ', COUNT(*) As ' No_of_Employees' From Department2 D
Inner Join Employee112 E On E.Department_id=D.Department_id group by Name Having
COUNT(*)>=2;
-------------------------------------------------------------------------------------------------
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
Select E.Emp_id ' Employee ID' , E. Last_Name ' Employee Name', M.Last_name' Manager Name'
from Employee112 E, Employee112 M
Where E.Manager_id= M.Manager_id;
**
Select E.Emp_id' Employee Id', E. Last_name ' Employee Name', M.Last_name 'Manager name'
from Employee112 E, Employee112 M
where M.Emp_id<>E.Manager_id
AND M.Emp_id=E.Emp_id Order by M.Emp_id;
**
Select E.Emp_id' Employee Id', E.Last_name'Employee Name', M.Last_Name' ManagerName' From
Employee112 E
Inner Join Employee112 M on E. Manager_id=M.Emp_id;
**
Select E.Last_name 'Employee_name', M.Last_name ' Manager_Name' from Employee112 E,
Employee112 M where E.Manager_id=M.Emp_id;
**
-------------------------------------------------------------------------------------------------
60.Display the employee details who earn more than their managers salaries.
Select E.Last_name ' Employee Name', M.Last_name'Manager Name', M.Salary 'Manager Salary'
from Employee112 E Inner join Employee112 M
ON E.Manager_id=M.Emp_id AND E.Salary>M.Salary;
**
Select E.Last_name'Employee Name', E.Salary'Employee Salary', M.Last_name'Manager Name', M.Salary'Manager
Salary'
From Employee112 E, Employee112 M where E.Manager_id=M.Emp_id And M.Salary<E.Salary;
---------------------------------------------------------------------------------------------------
61.Show the no. of employees working under every manager.
----------------------------------------------------------------------------------------------------
Outer Join:
------------------------------------------------------------------------------------------------------
62.Display all employees in sales or operation departments.
Select Emp_id, Last_name, E.Department_id, Name From Employee112 E Left Outer Join Department2 D
On E.Department_id=D.Department_id And D.Department_id In (Select Department_id from Department2 Where
Name In ('Sales', 'Operations'))
-----------------------------------------------------------------------------------------------------
Set Operators:
Union
Select Job_Function from Job where Job_id In (Select Job_id from Employee112 where Department_id= (Select
Department_id from Department2 where Name='Accountings'))
-----------------------------------------------------------------------------------------------------
64.List out the ALL jobs in Sales and Accounting Departments.
Select Job_Function from Job where Job_id In (Select Job_id from Employee112 where Department_id=(Select
Department_id from Department2 where Name='Sales'))
-----------------------------------------------------------------------------------------------------
Union All
Select Job_Function from Job where Job_id In (Select Job_id from Employee112 where
Department_id= (Select Department_id from Department2 where Name='Accountings'))
----------------------------------------------------------------------------------------------------
65.List out the common jobs in Research and Accounting Departments in ascending order.
Select Job_Function from Job where Job_id In (Select Job_id from Employee112 where
Department_id=(Select Department_id from Department2 where Name='Research'))
Intersect
Select Job_Function from Job where Job_id In (Select Job_id from Employee112 where
Department_id= (Select Department_id from Department2 where Name='Accountings'))
----------------------------------------------------------------------------------------------------
Improvement
-----------------------------------------------------------------------------------------------------------------------------------
By default, SQL Server uses [dbo] schema for all objects in a database. We can query
SCHEMA_NAME() to get the default schema for the connected user
--------------------------------------------------------------------------------------------------------------------------------------