Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 35

Introduction to SQL

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.

--------------------------------------------------------------------------------------------------------

What is The Database?

A database is an organized collection of structured information, or data, typically stored


electronically in a computer system.

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.)

What is Use of SQL Language?

 SQL can execute queries against a database


 SQL can retrieve data from a database

 SQL can insert records in a database

 SQL can update records in a database

 SQL can delete records from a database

 SQL can create new databases

 SQL can create new tables in a database

 SQL can create stored procedures in a database

 SQL can create views in a database

 SQL can set permissions on tables, procedures, and views

------------------------------------------------------------------------------------------------------------------

 How to download SQL Server 2014

 Go to the Chrome

 SQL server Express 2014


YouTube Support Video
https://www.youtube.com/watch?v=_T2_-79Sxi8

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

Data types might have different names in different database.

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

Ex. Name, Address, Education…

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

1)INT (size)= Allows whole numbers between -2,147,483,648 and 2,147,483,647

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'.

4)TIME (fsp)- A time. Format: hh:mm:ss.

5)YEAR= A year in four-digit format. Values allowed in four-digit format: 1901

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.

-------------------------------------------------------------------------------------------------------------------

SQL Commands Classification

1.DDL

2.DML

3.DQL

4.DCL

5.TCL
DDL -Data Definition Language

What is DDL = Data Definition Language (DDL)

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).

2)Drop=This command is used to delete objects from the database.

3)Truncate=IS used to remove all records from a table, including all spaces allocated for the records
are removed.

4)Alter=This is used to alter the structure of the database.

5)Rename=This is used to rename an object existing in the database.

------------------------------------------------------------------------------------------------------------------------

1) Create

Now First we create Database & After that we will create the Table into that

a. CREATE Database

CREATE DATABASE database_name;

Ex-Create Database Amruta;

2) CREATE TABLE

CREATE TABLE Table_Name (


Column1 Data_Type (Size),
Column2 Data_Type (Size),
Column3 Data_Type (Size),
Column4 Data_Type (Size), ……
);

Case 1. Create Table with NULL/NOT NULL

CREATE TABLE table_name (


column_name1 Data_Type [NULL|NOT NULL],
column_name2 Data_Type [NULL|NOT NULL],
......
);

Case 2. Create Table with Primary Key

CREATE TABLE Employee (


Emp_Id integer PRIMARY KEY,
First_Name varchar (20),
Last_Name varchar (20),
Email varchar (25),
Phone_No varchar(25),
Salary integer
);

Ex
CREATE TABLE My. Family (
First_Name varchar (255),
Education varchar (255),
Profession varchar (255),
Contact_No. int,
Age int,
);
------------------------------------------------------------------------------------------------------------------------

Rules-

1.Bracket 2. Datatype 3. Size 4. Column separation- Comma 5. Semicolon

CREATE TABLE Employee (


Emp_Id integer,
First_Name varchar (20),
Last_Name varchar (20),
Email varchar (25),
Phone_No varchar (25),
Salary integer
);

HW

Create Table Students

CREATE TABLE Students (

First_Name Varchar (255),

Middle_Name Varchar (200),

Last_Name Varchar (150),

Roll_Number char (3),

DOB DATETIME,

Education Varchar (255),

Profession varchar (200),

Salary price,

Address Varchar (255),

);

selects all the records from the Table (ex. Employee is table name)

SELECT * FROM Customers;

------------------------------------------------------------------------------------------------------------------

2.DML-Data Manipulation Language

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.

2) Update = It is used to update existing data within a table.

3) Delete = It is used to delete records from a database table.

1) Insert

INSERT INTO Table_Name (column_name1, column_name2...column_nameN)


VALUES (column1_value, column2_value...columnN_value);

CREATE TABLE Employee (


Emp_Id integer,
First_Name varchar (20),
Last_Name varchar (20),
Email varchar (25),
Phone_No varchar (25),
Salary integer
);

Ex. INSERT INTO Employee (Emp_Id, First_Name, Last_Name, Email, Phone_No, Salary)

VALUES (10, ‘Amruta’,’Bondar’,’amruta12@gmail.com’,8421420014,75000);

OR

INSERT INTO Employee

VALUES (10, ‘Amruta’,’Bondar’,’amruta12@gmail.com’,8421420014,75000);

Case 1- Insert Data to Specific Columns

INSERT INTO Employee (Emp_Id, FirstName, Last_Name)


VALUES (20,'Kavya','Kharate');

Case2- Insert Multiple Records

INSERT INTO Employee


VALUES
(30,'Sonali','Pande', 'sonali@test.com','123.456.4568',17000),
(40,'Arati','Pawar', 'Arati@test.com','123.456.4569',15000);

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 = 'jking@test.com'
WHERE EmpId = 10;

Case1-Update Multiple Columns

Query will change the Email and the PhoneNo in the Employee table whose EmpId is 2.

UPDATE Employee
SET Email = 'jb007@test.com', 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

DELETE FROM Table_Name


[WHERE Condition];

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.

By using Where conditions & its operations

…. DELETE FROM Employee WHERE Emp_Id = 4;

….. DELETE FROM Employee WHERE Salary > 20000;

Delete All Rows (means All Record)

DELETE FROM Employee;


Now, the Select * from Employee; query will display the empty table.

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.

TRUNCATE TABLE table_name;

CREATE TABLE Employee101 (


Emp_Id integer,
First_Name varchar (20),
Last_Name varchar (20),
Phone_No varchar (25),
Salary integer
);

INSERT INTO Employee101


VALUES
(1,'Shneha','Shinde', '963.456.4568',75000),
(2,' Preesha','Kale', '852.456.4569',52000),

Select * From Employee101;

TRUNCATE TABLE Employee101;

**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 TABLE Table_Name;

DROP COLUMN

The DROP COLUMN command is used to delete a column in an existing table.

ALTER TABLE Customers


DROP COLUMN Contact_Name;

CREATE TABLE Employee102 (


Emp_Id integer,
First_Name varchar (20),
Last_Name varchar (20),
Phone_No varchar (25),
Salary integer
);

INSERT INTO Employee102


VALUES
(1,'ABC','Khade', '963.785.4568',75000),
(2,' XYZ','Chate', '852.654.4569',52000),

Select * From Employee102;


DROP TABLE Table_Name;

Delete Truncate Drop


DML Command DDL Command DDL Command
DELETE FROM table_name [WHERE TRUNCATE TABLE table_name; DROP TABLE table_name;
Condition];
While in this command, view of table In the DROP command, view of table
exist. does not exist.
While this command is faster than The DROP command is quick to
DROP. perform but gives rise to
complications.
we can use the “ROLLBACK” Here we can’t restore the tuples of the Here we can’t restore the table by
command to restore the tuple because table by using the “ROLLBACK” using the “ROLLBACK” command
command.
We use Where Condition No No
By using Delete we can remove single We can remove all records At a time Data & Schema also remove
row or multiple At a time
Not delete column Remove column

5. Rename=This is used to rename an object existing in the database.

Rename Tables in the Database

sp_rename Employee, emp;

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.

Sp_Rename Employee, emp;

following operators can be used in the WHERE conditions.

Operators

=…………………………………… Equal

>……………………………………Greater than

>=…………………………………. Greater Than or Equal to

<……………………………………. Less Than

<=…………………………………… Less Than or Equal to

<> or ! = …………………………….. Not equal

Between………………………………. Between Some Range

Like………………………………………. Different Pattern

IN……………………………………………… To specify multiple possible values for a column

----------------------------------------------------------------------------------------------------------------
SELECT column1, column2,...columnN
FROM table_name
WHERE conditions

Multiple Conditions in WHERE Clause

SELECT * FROM Employee


WHERE Dept_Id = 1 AND Salary > 20000;

SELECT column1, column2,..


FROM table
WHERE column BETWEEN begin_value AND end_value

SELECT Emp_Id, FirstName, Last_Name, Salary


FROM Employee
WHERE Salary BETWEEN 10000 AND 20000;

BETWEEN Operator in WHERE Clause

ELECT * FROM Employee


WHERE Salary BETWEEN 15000 AND 20000;

SELECT * FROM Employee


WHERE FirstName BETWEEN 'a%' AND 'j%';

=================================================================

NOT BETWEEN
Use the NOT operator with the BETWEEN operator to filter records that do not fall in the specified range.

SELECT Emp_Id, FirstName, Last_Name, Salary


FROM Employee
WHERE Salary NOT BETWEEN 10000 AND 20000;

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).

SELECT column1, column2,..


FROM table
WHERE column IN (value1, value2, value3,...)

SELECT Emp_Id, FirstName, LastName, Salary


FROM Employee
WHERE EmpId IN (1, 3, 5, 6)

SELECT EmpId, FirstName, LastName, Salary


FROM Employee
WHERE FirstName IN ('james','john','abdul');

NOT IN
Use the NOT operator with the IN operator to filter records that do not fall in the specified values.

SELECT EmpId, FirstName, LastName, Salary


FROM Employee
WHERE EmpId NOT IN (1, 3, 5);

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.

(Take from Note Book & from Teacher Tutorial)

SELECT * FROM table_name


WHERE column_name LIKE 'pattern'

CREATE TABLE Employee100 (


Emp_Id integer,
First_Name varchar (20),
Last_Name varchar (20),
Email varchar (25),
Phone_No varchar (25),
Salary integer
);

INSERT INTO Employee


VALUES
(20,'Sonali','Pande', 'sonali@test.com','123.456.4568',17000),
(30,'Arati','Pawar', 'Arati@test.com','963.456.4569',25000),
(40,'Kirti','Kale', 'kirti@test.com','853.456.4569',65800),
(50,'Pratighya','Thakare', 'pratighya@test.com','783.456.4569',73200),
(60,'Rani','Bondar', 'rani@test.com','923.456.4569',425000),
(70,'Priya','Khade', 'priya@test.com','883.456.4569',804000),
(80,'Priti','Chate', 'priti@test.com','873.456.4569',20200);

SELECT * FROM Employee


WHERE Emp_Id = 10 AND Salary > 20000;

SELECT Emp_Id, FirstName, Last_Name, Salary


FROM Employee
WHERE Salary BETWEEN 25000 AND 75000;

SELECT Emp_Id, FirstName, Last_Name, Salary


FROM Employee
WHERE Salary NOT BETWEEN 20000 AND 45000;

SELECT Emp_Id, FirstName, Last_Name, Salary


FROM Employee
WHERE Emp_Id IN (10, 30, 50, 60)

SELECT Emp_Id, FirstName, Last_Name, Salary


FROM Employee
WHERE FirstName IN ('Rani','Priti','Priya');

SELECT Emp_Id, FirstName, Last_Name, Salary


FROM Employee
WHERE Emp_Id NOT IN (10, 30, 50);

SELECT * FROM table_name


WHERE column_nameN LIKE 'pattern'

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

SELECT * FROM Employee100


WHERE First_Name LIKE '_r'

SELECT * FROM Employee


WHERE FirstName BETWEEN 'a%' AND 'j%';
-----------------------------------------------------------------------------------------------------------------
SELECT * FROM Student_record1

WHERE First_Name LIKE 'a%';

SELECT * FROM Student_record1

WHERE First_Name LIKE '%a';

SELECT * FROM Student_record1

WHERE Last_Name LIKE '%wa%';

SELECT * FROM Student_record1

WHERE First_Name LIKE '_r%';

SELECT * FROM Student_record1

WHERE First_Name LIKE 'a_%';

SELECT * FROM Student_record1

WHERE Middle_Name LIKE 'a __%';

------------------------------------------------------------------------------------------------------------------

Aliases

SQL aliases are used to give a table, or a column in a table, a temporary name.

Aliases are often used to make column names more readable.

An alias only exists for the duration of that query.

An alias is created with the AS keyword.

SELECT column_name AS alias_name


FROM table_name;
SELECT Date_Of_Birth AS DOB, Middle_Name AS MN,
FROM Student_record1;

Aliases can be useful when:

 There are more than one table involved in a query


 Functions are used in the query

 Column names are big or not very readable

==================================================================

CONCAT

First Name, Middle Name, Last Name Full Name

Amruta Keshav Bondar Amruta Keshav Bondar

Two or more columns are combined togetherr

concatenate is to link something together.

The CONCAT() function can be used to database table's columns.

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.

SELECT CONCAT (FIRST_NAME,’ ‘,Middle_Name,’ ‘,Last_Name)AS Full_Name

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.

The AVG() function is used with the numeric columns only.

SELECT AVG (column_name)


FROM table_name
WHERE condition;

SELECT AVG(Salary) AS AVERAGE


FROM Student_record1;

-------------------------------------------------------------------------------------------------------------------

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.

SELECT COUNT([ALL | DISTINCT] expression | column_name)


FROM table_name
[WHERE condition]
[GROUP BY];
SELECT COUNT(First_Name) AS "Total"
FROM Student_record1;

The COUNT() function excludes the NULL values.

SELECT COUNT (*) AS "Total Records"


FROM Student_record1;

3. MAX () =

The MAX () function is an aggregate function that is used to find the largest value in the given column
or expression.

It can be applied on the numeric, character, or date values.

SELECT MAX(column_name)
FROM table_name
[WHERE condition]
[GROUP BY];

SELECT MAX(Salary) AS "Highest Salary"


FROM Student_record1;

The MAX() function can be allpied on the varchar columns.

SELECT MAX(First_Name) AS "Largest First_Name"


FROM Student_record1;
-----------------------------------------------------------------------------------------------------------------

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];

SELECT MIN(Salary) AS "Smallest Salary" FROM Student_record1;


---------------------------------------------------------------------------------------------------------------------

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.

SELECT SUM (column_name)


FROM table_name
[WHERE condition];

SELECT SUM(Salary) AS "Total Salary"


FROM Student_record1;
==================================================================
GROUP BY Clause
The GROUP BY clause is used to get the summary data based on one or more groups. The groups
can be formed on one or more columns.
For example, the GROUP BY query will be used to count the number of employees in each department,
or to get the department wise total salaries.

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.

SELECT column1, column2,...columnN


FROM table_name

[WHERE]

[GROUP BY column1, column2...columnN]


[HAVING]

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 is used to form the groups of records.

-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.

CREATE TABLE ABC(

Emp_Id integer,

First_Name varchar (20),

Last_Name varchar (20),

Email varchar (25),

Phone_No varchar (25),

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.

SELECT column1, column2,...columnN


FROM table_name
[WHERE]
[GROUP BY column1, column2...columnN]
[HAVING conditions]
[ORDER BY]

 The HAVING clause is used to filter out grouping records.


 The HAVING clause must come after the GROUP BY clause and before the ORDER BY clause.

 The HAVING clause can include one or more conditions.

 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

EmpId FirstName LastName Email PhoneNo Salary DeptId

1 'John' 'King' 'john.king@abc.com' '650.127.1834' 33000 1

2 'James' 'Bond' 1

3 'Neena' 'Kochhar' 'neena@test.com' '123.456.4568' 17000 2

4 'Lex' 'De Haan' 'lex@test.com' '123.000.4569' 15000 1

5 'Amit' 'Patel' 18000 1

6 'Abdul' 'Kalam' 'abdul@test.com' '123.123.0000' 25000 2

In the GROUP BY section, we used the following query to retrieve the no of employees in each
department,

SELECT Dept_Id, COUNT(Emp_Id) as 'Number of Employees'


FROM Emp
GROUP BY Dept_Id
HAVING COUNT(Emp_Id) > 2;

SELECT Dept_Id, COUNT(Emp_Id) as 'Number of Employees'


FROM Employee
GROUP BY Dept_Id;
HAVING Salary > 15000

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.

SELECT column1, column2,...columnN


FROM table_name
[WHERE]
[GROUP BY]
[HAVING]
[ORDER BY column(s) [ASC|DESC]]

 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.

SELECT * FROM Employee


ORDER BY First_Name;

Abcdefgh

SELECT EmpId, FirstName, LastName


FROM Employee
ORDER BY FirstName DESC;

==================================================================

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.

SELECT column1, column2, ...


FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

For Numerical
SELECT * FROM Employee
ORDER BY Salary;

For Characters
SELECT * FROM Employee
ORDER BY First_Name;

SELECT * FROM Customers


ORDER BY Salary DESC;

SELECT * FROM Customers


ORDER BY Salary, Last_Name;

SELECT * FROM Customers


ORDER BY Salary ASC, Last_Name DESC;

==================================================================

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.

CREATE TABLE table_name (


column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

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.

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different

 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

 CHECK - Ensures that the values in a column satisfies a specific condition

 DEFAULT - Sets a default value for a column if no value is specified

 CREATE INDEX - Used to create and retrieve data from the database very quickly

1.NOT NULL= By default, a column can hold NULL values.

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.

CREATE TABLE Persons (


ID int NOT NULL,
Last_Name varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
--------------------------------------------------------------------------------------------------------------------

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.

A PRIMARY KEY constraint automatically has a UNIQUE constraint.

However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per tab

CREATE TABLE Persons (


ID int NOT NULL UNIQUE,
Last_Name varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

-----------------------------------------------------------------------------------------------------------------------
3.Primary Key

The PRIMARY KEY constraint uniquely identifies each record in a table.

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).

CREATE TABLE Persons (


ID int NOT NULL PRIMARY KEY,
Last_Name varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

-----------------------------------------------------------------------------------------------------------------------

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

Person ID Last_Name First_Name Age

1 Hansen Ola 30

2 Svendson Tove 23

3 Pettersen Kari 20

Order ID OrderNumber PersonID

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.

CREATE TABLE Orders (


Order_ID int NOT NULL,
Order_Number int NOT NULL,
Person_ID int,
PRIMARY KEY (Order_ID),
FOREIGN KEY (Person_ID) REFERENCES Persons(Person_ID)
);

------------------------------------------------------------------------------------------------------------------

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:

CREATE TABLE Persons (


Person_ID int NOT NULL,
Last_Name varchar(255) NOT NULL,
First_Name varchar(255),
Age int CHECK (Age>=18)
);

--------------------------------------------------------------------------------------------------------------

6.DEFAULT

The DEFAULT constraint is used to set a default value for a column.

The default value will be added to all new records, if no other value is specified.

CREATE TABLE Persons (


Pereson_ID int NOT NULL,
Last_Name varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Mumbai'
);

-----------------------------------------------------------------------------------------------------------------------

7.INDEX

The CREATE INDEX statement is used to create indexes in tables.

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.

Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column1, column2,Duplicate values ...);

Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ...);

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.

SELECT DISTINCT column1, column2, ...


FROM table_name;

-------------------------------------------------------------------------------------------------

JIONS

A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.

Here are the different types of the JOINs in SQL:

 (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)

Create Table Employee (


Emp_Id int, NOT NULL
First_Name varchar (200),
Last_Name varchar (200),
Email varchar (200),
Salary int,
Dept_Id int
);

Insert Into Employee


Values (1,’John’,’King’,’john.king@abc.com’,33000,1),
(2,’James’,’Bond’,’ ‘,’ ‘,’ ‘),
(3, 'Neena', 'Kochhar', 'neena@test.com', 17000,2),
(4, 'Lex', 'De Haan', 'lex@test.com', 15000,1),
(5, 'Amit', 'Patel',’ ‘,18000,3),
(6,’Abdul’,’Kalam’, 'abdul@test.com',25000,2);

2)
Create Table Department (
Dept_Id int
Name varchar (200)
);

Insert Into Department


Values (1,’Finance’),
(2,’HR’);

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.Common column_name = table2.Common column_name;

Or

SELECT table1.column_name(s), table2.column_name(s)……


FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

SELECT Employee.Emp_Id, Employee.First_Name, Employee.Last_Name, Department.Name


FROM Employee
INNER JOIN Department
ON Employee.Dept_Id = Department.Dept_Id;

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.

In some databases, it is called LEFT OUTER JOIN.

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

SELECT Employee.emp_Id, emp.First_Name, dept.DeptId, dept.Name


FROM Employee emp
LEFT JOIN Department dept
ON emp.DeptId = dept.DeptId;

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.

Insert Into Department


Values (3,’Salse’),

SELECT dept.DeptId, dept.Name, emp.empid, emp.FirstName


FROM Employee emp
RIGHT JOIN Department dept
ON emp.DeptId = dept.DeptId;

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.

Restore the DB-AdventureWorks201

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.

ALTER TABLE table_name


ADD column_name1 data_type,
column_name2 data_type,

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.

In the Create Table section, we created the Employee4 table,

Create Table Employee4 (


Emp_Id int,
First_Name varchar(200),
Last_Name varchar(200),
Email varchar(150),
PhoneNo int,
Salary int
);

Emp_Id First_Name Last_Name Email PhoneNo Salary

Now, let's add new columns to it using the ALTER command.

Adding Columns in DB Table


ALTER TABLE Employee
ADD Address VARCHAR2(100),
City VARCHAR2(25),
PinCode NUMBER;

Emp_Id First_Name Last_Name Email PhoneNo Salary Address City PinCode

5.Rename- Tables in the Database

Different databases support the different syntax to rename a table.

sp_rename Oldtable_Name, NewTable_Name;

sp_rename Employee4, emp5;

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

 Efficient data access

 Greater Flexibility for Queries

 Quickly find the information

 Easier to implement Security

 Allows easy modification

 Reduction of redundant and duplicate data

 More Compact Database

 Ensure Consistent data after modification

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!

Explain different types of Normalization.


There are many successive levels of normalization. These are called normal forms. Each consecutive
normal form depends on the previous one.The first three normal forms are usually adequate.
Normal Forms are used in database tables to remove or decrease duplication. The following are the many
forms:
What is normalization?
Normalization is the process of minimizing redundancy and dependency by organizing fields and table of a
database. The main aim of Normalization is to add, delete or modify field that can be made in a single table.
What is Denormalization?
DeNormalization is a technique used to access the data from higher to lower normal forms of database. It is
also process of introducing redundancy into a table by incorporating data from the related tables.
------------------------------------------------------------------------------------------------------------------------
-
What is the difference between DROP and TRUNCATE commands?
DROP command removes a table and it cannot be rolled back from the database whereas TRUNCATE
command removes all the rows from the table.
------------------------------------------------------------------------------------------------------------------------
What is Datawarehouse?
Datawarehouse is a central repository of data from multiple sources of information. Those data are
consolidated, transformed and made available for the mining and online processing. Warehouse data have a
subset of data called Data Marts.
------------------------------------------------------------------------------------------------------------------------
What is CLAUSE?
SQL clause is defined to limit the result set by providing condition to the query. This usually filters some
rows from the whole set of records.
Example – Query that has WHERE condition
Query that has HAVING condition.
What is an ALIAS command?
ALIAS name can be given to a table or column. This alias name can be referred in WHERE clause to identify
the table or column.
-----------------------------------------------------------------------------------------------------------------------
What are aggregate and scalar functions?
Aggregate functions are used to evaluate mathematical calculation and return single values. This can be
calculated from the columns in a table. Scalar functions return a single value based on the input value.
Example -.
Aggregate – max(), count – Calculated with respect to numeric.
Scalar – UCASE(), NOW() – Calculated with respect to strings.

Assignment

Create table Department2 (

Department_id int,

Name varchar(250),

Location_id int

);

insert into Department2

Values (10, 'Accounting', 122),

(20, 'Reaserch', 124),

(30, 'Sales', 123),

(40, 'Operations', 167);

------------------------------------------------------

Create table Job1 (

Job_id int,

Job_Function varchar(250)

);

insert into Job1

values (667,'Cleark'),

(668,'Staff'),

(669,'Analyst'),
(670,'SalesPerson'),

(671,'Manager'),

(672,'President');

-------------------------------------

Create Table Employee500(

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

);

INSERT INTO EMPLOYEE500 (Emp_ID,Last_Name, First_NamE,Middle_Name,Job_ID,Manager_ID,Hire_date,


Salary,Department_id)

VALUES ( 7369, 'SMITH', 'JOHN', 'Q', 667,7902, '17-DEC-84', 800, 20);

INSERT INTO EMPLOYEE500 (Emp_ID,Last_Name, First_NamE,Middle_Name,Job_ID,Manager_ID,Hire_date,


Salary,COMM,Department_id)

VALUES (7499, 'ALLEN', 'KEVIN', 'J', 670, 7698, '20-FEB-85', 1600,300,30);

INSERT INTO EMPLOYEE500 (Emp_ID,Last_Name, First_NamE,Middle_Name,Job_ID,Manager_ID,Hire_date,


Salary,Department_id)

VALUES (7505, 'DOYLE', 'JEAN', 'K', 671, 7839, '4-APR-85', 2850,30),

INSERT INTO EMPLOYEE500 (Emp_ID,Last_Name, First_NamE,Middle_Name,Job_ID,Manager_ID,Hire_date,


Salary,Department_id)

( 7506, 'DENNIS', 'LYNN', 'S', 671, 7839, '15-MAY-85', 2750, 30),

INSERT INTO EMPLOYEE500 (Emp_ID,Last_Name, First_NamE,Middle_Name,Job_ID,Manager_ID,Hire_date,


Salary,Department_id)

(7507, 'BAKER', 'LESLIE', 'D', 671, 7839, '10-JUN-85', 2200, 40),

INSERT INTO EMPLOYEE500 (Emp_ID,Last_Name, First_NamE,Middle_Name,Job_ID,Manager_ID,Hire_date,


Salary,COMM,Department_id)

VALUES (7521, 'WARK', 'CYNTHIA', 'D', 670,7698,'22-FEB-85', 1250,500,30);

--------------------------------------------------------------------------------------------------
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”

Select Emp_id AS id_of_the_employee, last_name AS name, 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;
---------------------------------------------------------------------------------------------------

8. List the details about “SMITH”


Select* from Employee112 where Last_name= 'SMITH';
-------------------------------------------------------------------------------------------------------
9. List out the employees who are working in department 30
Select * from Employee112 where Department_id = 30;
------------------------------------------------------------------------------------------------------
10. List out the employees who are earning salary between 1200 and 2200
Select * from Employee112 Where Salary Between 1200 AND 2200;
-------------------------------------------------------------------------------------------------------
11. List out the employees who are working in department 20 or 30
Select * from Employee112 Where Department_id in (20,30);
-------------------------------------------------------------------------------------------------------
12. Find out the employees who are not working in department 20 or 30
Select * from Employee112 Where Department_id Not in (20,30);
--------------------------------------------------------------------------------------------------------
13. List out the employees whose name starts with “S”
Select * from Employee112 Where Last_name Like 'S%';
--------------------------------------------------------------------------------------------------------
14. List out the employees whose name start with “S” and end with “H”
Select * from Employee112 Where Last_name Like 'S%H';
------------------------------------------------------------------------------------------------------
15. List out the employees whose name length is 4 and start with “S”
Select * from Employee112 Where Last_name Like 'S____';
------------------------------------------------------------------------------------------------------
16. List out the employees who are working in department 10 and draw the salaries more
than 3500
Select * from Employee112 Where Department_id= 30 And Salary>1250;
-------------------------------------------------------------------------------------------------------
17. list out the employees who are not receiving commission.
Select * From Employee112 Where COMM is Null;
=========================================================================================================
Order By Clause:
18. List out the employee id, last name in ascending order based on the employee id.
Select Emp_id, Last_name From Employee112 order by Emp_id;
-----------------------------------------------------------------------------------------------------
19. List out the employee id, name in descending order based on salary column
Select Emp_id, Last_name, Salary From Employee112 order by salary DESC;

---------------------------------------------------------------------------------------------------

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) ;
-----------------------------------------------------------------------------------------------------

27. List out the department id having atleast four employees.


Select Department_id, count(*) No_of_Employee from Employee112
group by Department_id having COUNT(*)>2;
------------------------------------------------------------------------------------------------
28. How many employees in January month.
Select DATENAME(MM, Hire_date) month , count(*) No_of_Employee From Employee112
where DATENAME(MM, Hire_date) = 'February' group by DATENAME(MM, Hire_date);
--------------------------------------------------------------------------------------------------
29. How many employees who are joined in January or September month.
Select DATENAME(MM, Hire_date) month , count(*) No_of_Employee From Employee112
where DATENAME(MM, Hire_date) IN( 'February', 'June') group by DATENAME(MM, Hire_date);
-----------------------------------------------------------------------------------------------------
30. How many employees who are joined in 1985.
Select DATEPART(YY, Hire_date)Year, Count(*) No_Of_Employee from Employee112
Where DATEPART (YY, Hire_date)=1985 group by DATEPART(YY, Hire_date);
------------------------------------------------------------------------------------------------------
31. How many employees joined each month in 1985.
Select DATEPART(YY, Hire_date)Year,DATENAME(MM, Hire_date)Month, Count(*)
No_Of_Employee from Employee112
Where DATEPART (YY, Hire_date)=1985 group by DATEPART(YY, Hire_date), DATENAME(MM,
Hire_date);
--------------------------------------------------------------------------------------------------------
32. How many employees who are joined in March 1985.

Select DATEPART(YY, Hire_date)Year,DATENAME(MM, Hire_date)Month, Count(*)


No_Of_Employee from Employee112
Where DATEPART (YY, Hire_date)=1985 AND Datename(MM, Hire_date)='February'
group by DATEPART(YY, Hire_date), DATENAME(MM, Hire_date);

-----------------------------------------------------------------------------------------------------
33. Which is the department id, having greater than or equal to 3 employees joined in
April 1985.

Select Department_id, Count(*) No_Of_Employee from Employee112


Where DATEPART (YY, Hire_date)=1985 AND Datename(MM, Hire_date)='February'
group by Department_id having count(*)>=2;

========================================================================================================

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%.

update Employee112 Set Salary=(Salary + Salary*10/100) where Job_id IN


(Select Job_id from Job where Job_Function='Cleark');
Select * from Employee112;

40. Delete the employees who are working in accounting department.

Delete from Employee112 where Department_id In


(Select Department_id from Department2 where name='Accounting');

41. Display the second highest salary drawing employee details.


Select * from Employee112 where Salary IN(Select Max(Salary) from Employee112
where Salary<(Select Max(Salary)From Employee112) );

42. Display the Nth highest salary drawing employee details

===============================================================================
Joins

Simple join

48.List our employees with their department names


SELECT Emp_id,Last_name,Salary,E.Department_id,name FROM Employee112 E
INNER JOIN Department2 D ON E.Department_id=D.Department_id;

-----------------------------------------------------------------------------------
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.

Select name AS 'Department name', COUNT(*) AS 'No_of_Employess' from Department2 D


INNER JOIN Employee112 E ON E.Department_id=D.Department_id group by name;

------------------------------------------------------------------------------------------
52.How many employees who are working in sales department.

Select Name , Count(*) AS 'No of Employees' from Department2 D


Inner Join Employee112 E On E.Department_id= D.Department_id group by Name
Having Name ='Sales';

-------------------------------------------------------------------------------------------
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.

Select Job_function , count(*) As 'No of Jobs' from Job J


Inner Join Employee112 E ON E.Job_id=J.Job_id group by Job_Function;

-------------------------------------------------------------------------------------------------
55.How many employees working in “New York”.
Non – Equi Join:
56.Display employee details with salary grades.
57.List out the no. of employees on grade wise.
58.Display the employ salary grades and no. of employees between 2000 to 5000 range of
salary.

-------------------------------------------------------------------------------------------------
Self Join

59.Display the employee details with their manager names.

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.

Select M.Last_name, Count(*)'Number of Employees'


From Employee112 E, Employee112 M where E.Manager_id=M.Emp_id Group by M.Last_name;
**
Select M.Manager_id, Count(*),'Number of Employee' From Employee112 E Inner Join
Employee112 M On M.Emp_id=E.Manager_id Group By M.Manager_id;

----------------------------------------------------------------------------------------------------

Outer Join:

61.Display employee details with all departments.

Select Emp_id, Last_name,Hire_date, Salary,E.Department_id, Name


From Employee112 E Left Outer Join Department2 D On E.Department_id=D.Department_id;

------------------------------------------------------------------------------------------------------
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:

63.List out the distinct 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
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

SELECT * FROM INFORMATION_SCHEMA. COLUMNS WHERE COLUMN_NAME LIKE 'PREFIX%' ORDER


BY TABLE_NAME; Query: SELECT * FROM INFORMATION_SCHEMA.

-----------------------------------------------------------------------------------------------------------------------------------

How do I find the SQL schema name?

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

--------------------------------------------------------------------------------------------------------------------------------------

What is a database schema?


A database schema defines how data is organized within a relational database; this is inclusive of logical
constraints such as, table names, fields, data types, and the relationships between these entities.

In a SQL database, a schema is a list of logical structures of data.


===============================================================================

You might also like