0% found this document useful (0 votes)
13 views

SQL

Uploaded by

siva nagendr
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

SQL

Uploaded by

siva nagendr
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

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

stored electronically in a computer system.


A database is usually controlled by a database management system (DBMS).

SQL Commands:

1. DDL - create, alter, drop, truncate


2. DML - insert, update, delete
3. DCL - Grant, Revoke
4. DQL - Select
5. TCL - Rollback, commit, save point

Drop vs delete vs truncate

Drop:
It is a Data Definition Language Command (DDL). It is used to drop the whole table.
With the help of the “DROP” command we can drop (delete) the whole structure in one
go i.e.
it removes the named elements of the schema. By using this command the existence of
the whole table is finished or say lost.

Delete:
Basically, it is a Data Manipulation Language Command (DML). It is used to delete
one or more tuples of a table.
With the help of the “DELETE” command, we can either delete all the rows in one go
or can delete rows one by one. i.e.,
we can use it as per the requirement or the condition using the Where clause. It is
comparatively slower than the TRUNCATE command.

Truncate:
It is also a Data Definition Language Command (DDL). It is used to delete all the
rows of a relation (table) in one go.
With the help of the “TRUNCATE” command, we can’t delete the single row as here
WHERE clause is not used. By using this command the existence of all the rows of
the table is lost.
It is comparatively faster than the delete command as it deletes all the rows
fastly. The TRUNCATE command does not remove the structure of the table.

Services in SQL Server

1. DB Engine
2. Analysis Services
3. Reporting Services
4. Integration Services
5. Mobile edition

alter:

alter table emp


alter coulmn name varchar(10)

alter table emp


add Address varchar(10)

alter table emp


drop column address
sp_rename 'oldtablename', 'newtablename'

sp_rename 'tablename.old column name' 'new columnname'

Identity:

Used yo increment column values automatically, it should be integer data type


column only

syntax: identity (seed value, increment value) - identity (1,1) (id int
identity(1,1))

Logical operators:

1) AND 2) OR 3) NOT 4) BETWEEN

Order by clause: select * from emp order by salary

Group by clause: it is used to display the records in grouping order

ex: select designation, count(*) from emp group by designation.

IN operator: it is used to pass multiple values in where condition

select * from emp where id IN(1,2,3)

IS Operator:
It is used to get the records while comparing with null

select * from emp where salary is null


select * from employee where Dep_id is null

Top: It is used to get top most records from table

select top 2 * from employee

Distinct: It is used to get unique values from tables

select distinct salary from employee


select distinct dep_id from employee

LIKE: There are used to get the records based on required order
To work with like operator we use wild cards. (%, _,_ _, [a-m])
select * from employee where name like '%s'

Set operators: this operators will return the results of 2 select operators.

1. union - it will return the unique values from both tables


2. union all - It will return the all the vaules from both tables
3. intersect - It will return the common values from both tables
4. except - it will return the values from 1st table which is not present in 2nd
table

select * from employee


union
select * from dep

delete:

It is used to delete only one record from all records in a table.


Delete command will support where condition
Delete command will not reset identity if the table is having datatype

Truncate:

It is used to delete all the records using trancate in a table, we can delete one
by one record because it's not support where condition.
Truncate will reset identity in a table.

Truncate table tablename.

constraints:

1. unique - It will return unique values and 1 null value, because 1 null value
will treated as unique.

2. not null - it will not except the null values but it allows duplicate values.
3. Primary key - It will not accept null and duplicate values
4. check - It is special type of condition we can apply on any coulmn of table.
create table emp (id int, name varchar, age int check(age between 18 and 70);
5. default - This constrain accept default values when user not supplied column
values.
Though the column is having default constrain when we supply the value, the
supplied value will be stored.
6. Foreign key

Math functions:

abs(-23)
ceiling(25.75)
floor (34.5) -remove decimal value
square (4)
sqrt(49)
power()

String functions:

len()
ltrim()
rtrim()
lower()
upper()
ascii()
revers()
space()
concat()
concat_ws()
FORMAT()
Format("0.981", "Percent");

select rtrim ('durga ') + 'soft'


select substring ('allahfgfgf',5,5)

LOCATE(): This function is used to find the nth position of the given word in a
string.
Syntax: SELECT LOCATE('for', 'geeksforgeeks', 1);
LOWER(): This function is used to convert the upper case string into lower case.
REPEAT()
REPLACE():
REVERSE()
SPACE()
Upper()

multi-row functions:

1. max()
2. min()
3. avg()
4. sum()
5. count()
6. day(getdate())
7. month (getdate())
8. year(getdate())

how to take a backup of table in sql

select * into new table_name from old table_name

create table new_table select * from old

create table Sairam like old table

select right('Sairam',3)
select left('Sairam',3)

DELETE duplicate rows****:

SELECT EMPNAME,DEPT,CONTACTNO,CITY, COUNT(*) FROM details GROUP BY


EMPNAME,DEPT,CONTACTNO,CITY having count(*)>1

delete from details where id not in (select max(id) from details group by column
names)

or

with details_DEL As
(
select *, row_number() over(partition by EMPNAME order by EMPNAME) as rownumber
from details
)
select * from details_DEL
*************************************
with details_DEL As
(
select *, row_number() over(partition by EMPNAME order by EMPNAME) as rownumber
from details
)
delete from details_DEL where rownumber>1

CONVERT date to string:

declare @dt datetime = (select order_date from orders where prod_id =103) select
convert(varchar(20), @dt, 0) String

RANK and DENSE RANK:

Difference between Rank and Dense_Rank functions


Rank function skips ranking(s) if there is a tie where as Dense_Rank will not.

For example : If you have 2 rows at rank 1 and you have 5 rows in total.
RANK() returns - 1, 1, 3, 4, 5
DENSE_RANK returns - 1, 1, 2, 3, 4

with Result as
(
select salary, dense_rank() over(order by salary desc) as TopSalary from employee
)
select top 1 salary from Result where TopSalary = 5

Select * from (select salary, dense_rank() over(order by salary desc)toprank from


Employee) employee where toprank=2

Sub query and Nested Query:

Joins:

1. The different types of Joins in sql server


2. Cross Join
3. Inner Join
4. Outer Join -- Left , Right and Full Outer Join.

1. Advanced or intelligent joins in SQL Server


2. Retrieve only the non matching rows from the left table
3. Retrieve only the non matching rows from the right table
4. Retrieve only the non matching rows from both the left and right table

Views:In SQL, a view is a virtual table based on the result-set of an SQL


statement.

A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.

You can add SQL statements and functions to a view and present the data as if the
data were coming from one single table.

A view is created with the CREATE VIEW statement.


CREATE VIEW view_name AS select*******

System Defined Views.


Information Schema.
Catalog View.
Dynamic Management View.
User Defined Views.
Simple View.

SP:
A stored procedure is a prepared SQL code that you can save, so the code can be
reused over and over again.

So if you have an SQL query that you write over and over again, save it as a stored
procedure, and then just call it to execute it.

You can also pass parameters to a stored procedure, so that the stored procedure
can act based on the parameter value(s) that is passed.

CREATE PROCEDURE procedure_name


AS
begin
sql_statement
END;

EXEC procedure_name;

Indexes:
An index is a schema object. It is used by the server to speed up the retrieval of
rows by using a pointer.
It can reduce disk I/O(input/output) by using a rapid path access method to locate
data quickly.
An index helps to speed up select queries and where clauses, but it slows down data
input, with the update and the insert statements.
Indexes can be created or dropped with no effect on the data. In this article, we
will see how to create, delete, and uses the INDEX in the database.

CREATE INDEX index


ON TABLE column;

1. cluster index:
It will create automatically when table is having primary key constrain
in sql server a table shold have only one cluster index

2. Non cluster index


It will create automatically when table is having unique key constrain.
A table can have more than one non cluster index. Non cluster index will not
arrange physical.

Triggers:

A trigger is a special type of stored procedure that automatically runs when an


event occurs in the database server.
DML triggers run when a user tries to modify data through a data manipulation
language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a
table or view.
These triggers fire when any valid event fires, whether table rows are affected or
not.

DDL triggers run in response to a variety of data definition language (DDL) events.
These events primarily correspond to Transact-SQL CREATE, ALTER, and DROP
statements, and
certain system stored procedures that perform DDL-like operations.

Logon triggers fire in response to the LOGON event that's raised when a user's
session is being established.
You can create triggers directly from Transact-SQL statements or from methods of
assemblies that are created in the Microsoft .NET Framework common language runtime
(CLR)
and uploaded to an instance of SQL Server. SQL Server lets you create multiple
triggers for any specific statement.

CREATE [OR REPLACE] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }{INSERT [OR] | UPDATE [OR] | DELETE}[OF col_name]
ON table_name
AS
BEGIN
--- sql statements
END;

create trigger stud_marks


before INSERT
on Student

Schema:

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


collection of database objects like tables, triggers, stored procedures, etc.
A database schema is considered the “blueprint” of a database which describes how
the data may relate to other tables or other data models

Transactions:
Transactions group a set of tasks into a single execution unit. Each transaction
begins with a specific task and ends when all the tasks in the group successfully
complete.
If any of the tasks fail, the transaction fails. Therefore, a transaction has only
two results: success or failure.

Incomplete steps result in the failure of the transaction. A database transaction,


by definition, must be atomic, consistent, isolated and durable.
These are popularly known as ACID properties

BEGIN TRANSACTION transaction_name ;

Deadlock:
Deadlocks occur when two processes want to access resources that are mutually being
locked by each other. This locked situation can continue forever if nobody stops
it.
Cursors:
Cursor is a Temporary Memory or Temporary Work Station. It is Allocated by Database
Server at the Time of Performing DML(Data Manipulation Language)
operations on Table by User. Cursors are used to store Database Tables. There are 2
types of Cursors: Implicit Cursors, and Explicit Cursors.
These are explained as following below.

Implicit Cursors:
Implicit Cursors are also known as Default Cursors of SQL SERVER. These Cursors are
allocated by SQL SERVER when the user performs DML operations.

Explicit Cursors :
Explicit Cursors are Created by Users whenever the user requires them. Explicit
Cursors are used for Fetching data from Table in Row-By-Row Manner.

Declare Cursor Object.


Syntax : DECLARE cursor_name CURSOR FOR SELECT * FROM table_name
DECLARE s1 CURSOR FOR SELECT * FROM studDetails

performance tuning:

SQL tuning is the process of improving SQL queries to accelerate servers


performance. It's general purpose is to reduce the amount of time it
takes a user to receive a result after issuing a query, and to reduce the amount of
resources used to process a query.

Database Optimization Techniques


Query Optimization
Increase Memory
Improve Indexes

You might also like