0% found this document useful (0 votes)
5 views49 pages

SQL New Notes

The document states that the training data is current only until October 2023. It implies that any information or developments occurring after this date may not be included in the training. This sets a limitation on the relevance of the data for future events.

Uploaded by

karthickramsaero
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views49 pages

SQL New Notes

The document states that the training data is current only until October 2023. It implies that any information or developments occurring after this date may not be included in the training. This sets a limitation on the relevance of the data for future events.

Uploaded by

karthickramsaero
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

SQL INSTALLATION PROCESS

STEP 1

Type Chrome in: sql download

STEP 2

Choose Microsoft SQL Server downloads

STEP 3

Scroll down -> Click -> Express (Download Now)

STEP 4

After downloading, Double click that file..

STEP 5

Click -> Yes

STEP 6

Choose Installation type -> Basic

STEP 7

Accept the License

STEP 8

Install (Package Installing)

STEP 9

Install SSMS

STEP 10

Scroll down -> Download SSMS:

Click -> Free download for SQL Server management studio (SSMS)

File Downloading…
STEP 11

After Downloading

Click that file

STEP 12

Click Install

STEP 13

Click -> Yes

Close

STEP 14

Installation Completed…

Finally Check the windows.

Type Search Bar in sql or SSMS (see….Server Management Studio


Management
SQL
Introduction to SQL
SQL is a standard language for accessing and manipulating databases.

What is SQL?
 SQL stands for Structured Query Language
 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards Institute
(ANSI) in 1986, and of the International Organization for Standardization
(ISO) in 1987

What Can SQL do?


 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
RDBMS
RDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems such as MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

The data in RDBMS is stored in database objects called tables. A table is a


collection of related data entries and it consists of columns and rows.

Some of The Most Important SQL Commands


 SELECT - extracts data from a database
 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index

SQL Query Examples


1. Create DataBase: Used to create a new DataBase.
Example:
create database EmployeeDetail

We will create a new database, if you want to use a specific database, use this
query.
use EmployeeDetail

2. Create Table: Used to create a new Table in a DataBase.


Example:
create table EmployeeRecord(ID int ,
Name varchar(50),
Salary int,
Address varchar(200),
DOB date,
Gender char,
PhNo bigint)
3. Modify/Alter Table:
i) Modify not support this SQL server so use ALTER COLUMN query.
Example:
alter table EmployeeRecord
modify PhNo varchar(10)

ii) Alter column data type: Used to rename the Datatype.


Example:
alter table EmployeeRecord
alter column PhNo varchar(10)
iii) Add new column:
Example:
alter table EmployeeRecord
add email varchar(233)
iv) Drop column:
Example:
alter table EmployeeRecord
drop column email
v) Rename to column name:
Example:
exec sp_rename ‘tablename.old
column name’,’new_column
name’,’column’
vi) Rename to Table name:
Example:
exec sp_rename
‘tablename’,’new_table name’

Def: PhNo datatype is bigint now changed as varchar(10)

4. Insert table:
Used to insert the field details.
Example:
insert into EmployeeRecord values (1,'Aswin',1000,'Trichy',9876432108)
insert into EmployeeRecord values (2,'Aaron',2000,'Chennai',9597804309)
insert into EmployeeRecord values (3,'James',3000,'Dubai',8907654039)
insert into EmployeeRecord values (4,'Jhon',4000,'Madhurai',9789651234)
insert into EmployeeRecord values (5,'Praveen',5000,'Chennai',7865439201)
Screenshot for Example:

5. Select table:
If you want see the table columns use this select statement.All coulmns
are selected.
Example:
select * from EmployeeRecord

Def:ID,Name ... are the field names of the table you want to select data
from.
Select ID,Name from EmployeeRecord

I) SELECT DISTINCT Statement:


It is used to return only distinct (different) values. It does not show repeated
values.

Example:
SELECT DISTINCT Address FROM EmployeeRecord

II) COUNT DISTINCT Statement:


Using the DISTINCT keyword in a function called COUNT, we can return the
number of different countries.
Example:
SELECT COUNT(DISTINCT Address) FROM EmployeeRecord

III)Select Top Clause:


It is used to specify the number of records to return.And it is useful on large
tables with thousands of records. Returning a large number of records can
impact performance.
Example:
SELECT TOP 3 * FROM EmployeeRecord

SELECT TOP 50 percent * FROM EmployeeRecord


IV) Like Operator and Wildcards:
It is used in a WHERE clause to search for a specified pattern in a column.

 The percent sign % represents zero, one, or multiple characters. It is


Mostly used.
 The underscore sign _ represents one, single character.

Example:
select * from EmployeeRecord where name like '%a%'

‘a%’, ‘la%’ , ‘%a’

select * from EmployeeRecord where Address like '_ric '

6. Update table:
If you want to change the field values use update statement. Change one or
more fields.
Example:
i)
update employeerecord set name='Raja' where name='Praveen'
ii)
update employeerecord set name='Raja', Salary=6000 where name='Madhan'

7. Delete table:
It is used to delete the all field values and table.
Example:
delete from EmployeeRecord

delete from EmployeeRecord where id = ‘1’

ii) DROP TABLE: Used to delete a table.


Example:
DROP TABLE EmployeeRecord

iii) TRUNCATE TABLE: is used to delete the data inside a table, but not the
table itself.
Example:
TRUNCATE TABLE EmployeeRecord
8. Comments:
Comments are used to explain sections of SQL statements, or to prevent
execution of SQL statements.
Singleline Comment:
Example:
--select * from Student

Multiline Comments:
Example:
/*Select * from StaffDetail
Select * from Stueden
Select * from EmployeeRecord*/
Select * from test1

9. SQL Fuctions:
i) MIN(): It returns the smallest value in the table.
Example:
select min(id) from employeerecord

ii) MAX(): It returns the largest value in the table.


Example:
select max(id) from employeerecord

iii) COUNT(): It returns the number of rows that matches a specified criterion.
Example:
select count(address) from EmployeeRecord

iv) AVG(): Itreturns the average value of a numeric column.


Example:
select avg(id) from employeerecord

v) SUM(): It returns the total sum of a numeric column.


Example:
select sum(salary) from employeerecord
10. Union Operators:
UNION: It is used to combine the result-set of two or
more SELECT statements. And selects only distinct values by default.
Example:
select Address from EmployeeRecord union
select Address from test1

UNION ALL: It is allow duplicate values.


Example:
select Name from EmployeeRecord union all
select Name from test1

11. Operators:
I) Logical Operators:
i) IN & NOT IN Operators:
IN():It allows to specify multiple values in a WHERE clause. And shorthand
for multiple OR conditions.
Example:
select * from employeerecord where Address in ('Chennai','Dubai')

NOT IN():It return all records that are NOT any of the values in the list.
Example:
select * from employeerecord where Address not in ('Chennai','Dubai')

ii) BETWEEN & NOT BETWEEN Operators:


BETWEEN: Used to select values within a given range. The values can be
numbers, text, or dates.
Example:
select * from EmployeeRecord where Salary between 1000 and 3000

NOT BETWEEN: Used to select values within a given range. The values can
be numbers, text, or dates.
Example:
select * from EmployeeRecord where Salary not between 1000 and 3000

iii) Exist & Not Exist Operators:


Exist: It is used to test for the existence of any record in a subquery.And returns
TRUE if the subquery returns one or more records.
Example:
select * from EmployeeRecord where exists (select address from
EmployeeRecord where Address='Chennai')
NOT Exist: used with a subquery in the WHERE clause to check if the result of
the subquery returns TRUE or FALSE. The Boolean value is then used to
narrow down the rows from the outer select statement.
Example:
select * from EmployeeRecord where not exists (select address from
EmployeeRecord where ID=5)

II) Arithmetic Operators:


i) Add Operator: To add the value in sql.
Example:
Select 30 + 20
Screenshot:

ii) Subtract Operator: To subtract the value in sql.


Example:
Select 30 - 20
Screenshot:

iii) Multiple Operator: To multiply the value in sql.


Example:
Select 30 * 20
Screenshot:

iv) Divide Operator: To divide the value in sql.


Example:
Select 30 / 10
Screenshot:
iv)Divide Operator: To find modulo division value in sql.
Example:
Select 17 % 5

Screenshot
SQL ANY and ALL
SQL ANY Operator
SQL ANY compares a value of the first table with all values of the second
table and returns the row if there is a match with any value.
It has the following syntax:

SELECT column
FROM table1
WHERE column OPERATOR ANY (
SELECT column
FROM table2
);

Here,

 column is the name of the column(s) to filter


 table1 and table2 are the two tables to compare
 OPERATOR is any SQL operator to connect the two queries
 ANY compares table1 and table2 to see if there are any matches

Note: The column placeholder can stand for multiple different columns from
the two tables.

Example 1: SQL ANY Operator


Suppose we want to find teachers whose age is similar to any of the
student's age. Then, we can use the following query:

SELECT *
FROM Teachers
WHERE age = ANY (
SELECT age
FROM Students
);

Here, the subquery below returns all the ages from the Students table.

SELECT age
FROM Students

And, the condition below compares the student ages (returned by


subquery) with the ages of the teachers.

WHERE age = ANY (...)

If there is any match, the corresponding row of the Teachers table is


selected.
Example: ANY in SQL

Example 2: SQL ANY With the < Operator


We can use any comparison operators like = , > , < , etc., with
the ANY and ALL keywords.
Let's look at an example where we want teachers whose age is less than
any student.

SELECT *
FROM Teachers
WHERE age < ANY (
SELECT age
FROM Students
);

Here, the SQL command selects rows if age in the outer query is less than
any age in a subquery.
Example: ANY in SQL
SQL ALL Operator
SQL ALL compares a value of the first table with all values of the second
table and returns the row if there is a match with all values.

It has the following syntax:

SELECT column
FROM table1
WHERE column OPERATOR ALL (
SELECT column
FROM table2
);

Here,

 column is the name of the column(s) to filter


 table1 and table2 are the two tables to compare
 OPERATOR is any SQL operator to connect the two queries
 ALL compares table1 and table2 to see if all the values match

Note: The column placeholder can stand for multiple different columns from
the two tables.

Example 3: SQL ALL Operator


For example, if we want to find teachers whose age is greater than all
students, we can use

SELECT *
FROM Teachers
WHERE age > ALL (
SELECT age
FROM Students
);

Here, the subquery below returns all the ages from the Students table.

SELECT age
FROM Students

And, the condition below compares the student ages (returned by


subquery) with the ages of the teachers.

WHERE age > ALL (...)

If the teacher's age is greater than all student's ages, the corresponding
row of the Teachers table is selected.
Example: ALL in SQL
SQL – AGGREGATE FUNCTIONS

Group by

Eg 1

o/p
Eg 2

o/p

Order by
Having

Only execute first three line query

Execute all lines


Switch Case when Statement

Eg . Table

Eg 1

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

Different Types of SQL JOINs


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
Example Tables:
SQL Self Join

A self join is a regular join, but the table is joined with itself.

Self Join Syntax


SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

T1 and T2 are different table aliases for the same table.


SQL Cross Join
SQL CONSTRAINTS
CREATE PRIMARY KEY WAY 1:

(OR)
IN NORMAL TABLE WE CAN ALTER THE
PRIMARY KEY CONSTRAINT
In this table compulsory mention the NOT NULL in
StudentID Column, otherwise we get the error
COMPOSITE KEY
How to more than one column in primary key?
SQL NOT NULL Constraint
SQL UNIQUE Constraint
SQL CHECK Constraint
SQL DEFAULT KEY Constraint
SQL FOREIGN KEY Constraint
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.

create database leo


use leo

create table Course


(
CourseID int PRIMARY KEY,
CourseName varchar(255),
StaffName varchar(255)
)

insert into Course values(401,'Computer science','Radha'),


(402,'electrical and electronics','meera'),
(403,'information technology','geetha'),
(404,'mechanical','siva')

select * from Course


create table Students
(
StudentID int PRIMARY KEY,
FirstName varchar(255),
LastName varchar(255),
DateOfBirth Date,
Gender char(1),
CourseID int FOREIGN KEY REFERENCES Course(CourseID)
)

or

create table Students


(
StudentID int PRIMARY KEY,
FirstName varchar(255),
LastName varchar(255),
DateOfBirth Date,
Gender char(1),
CourseID int
CONSTRAINT FK_Students FOREIGN KEY(CourseID) REFERENCES
Course(CourseID)
)

select * from Students

insert into Students values(1001,'Aishwarya','Jayaram','2005-09-20','F',401)

//ERROR
insert into Students values(1002,'Aishwarya','Jayaram','2005-09-20','F',405)

delete from Course where CourseID = 402 //ERROR


delete from Students where CourseID = 402 //DELETED
delete from Course where CourseID = 402 //DELETED
select * from Course

alter table Students


ADD FOREIGN KEY(CourseID) REFERENCES Course(CourseID)
//OR

alter table Students


ADD CONSTRAINT FK_Students FOREIGN KEY(CourseID)
REFERENCES Course(CourseID)

//DROP THE CONSTRAINT


alter table Students
DROP CONSTRAINT FK_Students

You might also like