e Notes: SQL
Database: A database is an organized collection of data I’e stored and accessed electronically.
The data is structured in way that is allows easy retrival, management , and updating.
DBMS: is a software that allows user to create, define, maintain and control access to databases.
It acts as an intermediary between the user and the database,
SQL comes under relational Database eg, sql , sql server, mysql, oracle
Non relational Database useses mongoDB, Django,
SQL - structured Query language it is a programming language
Datatype: it is used to specify the type of the data which we storing into the variable
Variable is nothing but a storage area, which stores the data.
Compiler is used to show the output to the user
Create table/ create Database is shown in blue because it is system generated predefined keywords
Blacks word are called user defined
Syntax: is nothing but set of Rules by following the rules we can write the programs.
SQL is structured query language it is a Language performs the operations on the database like
Define, alter, etc..
1) Create database (database name)
2) Create table tablename(
Id int, name varchar()
)
Alteration table
Alter table tablename
Add tablecode varchar()
2) alter table tablename
Alter column tablename varchar()
Inserting data into table
Insert into tablename (id, name) values(1,’Bharat’)
Then query is like Select * from tablename.
Select name from tablename
2--- all these numbers are called index numbers (sl num)
sl ID Name signature
1 101 Ram raam
2 102 Bheem bheeem
BY using the insert command we can add the values in two methods
1) By using the value method
2) By using the address method
Value method
This method will applicable when we know the column names and column order and
corresponding data types
Address method
This method will be applicable when we don’
Keys:
why we will use keys in DBMS.
1) To identify each row of a table uniquely
2) To maintain Data integrity
3) To maintain relationship b/w table
Keys are 8 types:
1) Super key – in super key we can use multiple unique columns ( like id, name,branch)
(Here we can take as id + name or id + name +branch)
2) Candidate key: Candidate key is nothing but a minimal Subset of a Super key ( minimal
means As minimal as Possible) Either ID + name or Id. (A candidate key is a minimal
attribute or Combination of attributes for unique Identification of each row of a table)
3) Primary key
4) Alternate key
5) Foreign key
6) Composite key
7) Compound key
8) Surrogate key
Primary key:
create table country(
id int primary key,
name varchar(10)
then insert into Country(id, name) values (1,'babu')
when we are using primary key we need to insert separate data into primary key table,
so that it wont allow duplicate data.
primary key will protect from violation of original values
it will not allow duplicate values
it wont allow null values
Errors is like vilolation of Primary key
Attribute, field also called as columns.
Records, tuple, are also called as rows.
Constraints – sql constraints are used to specify the rules for the data in table. (this constraint
we can observe in the syntax error.
Foreign key
Error of Fk is like conflict withn Fk
Rdbms
create table State(
StateId int primary key,
StateName varchar(30),
StateCode varchar(40),
CountryId int,
foreign key(CountryId) references Country(CountryId)
)
insert into State(
stateId,StateName,
Statecode,
CountryId)
values(5,'ABC','T',4)
table name
1) Customers
2) Categories
3) Employees
4) Shippers
5) Orders
6) Suppliers
7) Products
8) Orderdetails.
Select StateName,CountryName from State St
Left Join Country as Ct on Ct.CountryId= St.CountryId
insert into State (StateID,
StateName,StateCode)
values (12,'XYZ','X')
Select * from State
Inner join:
1) Need to display orderdetails with product name
2) I need to display orders with customername
3) I need to display orders with employees firstname
4) I need to display orders with shipper name
5) I need to display orders with customer name,first name,shippername,
6) I need to display products with suppliersname
7) I need to display productwith cat name
8) I need to display Suppliername with categoryname
create Procedure GetAllCustomers<Name>
AS
BEGIN
select * from Customers
END
EXEC GetAllCustomers
Get all orders
Stored procedure is a precompiled block of code
Stored procedure Functions
1) SP is precompiled block of code
2) And it protects from sql injections
3) Sp may or maynot return values It will return values
4) Its keyword to execute EXEC Select(keyword) dbo.
Creating Triggers
create Trigger TRG_Mandal
On Mandal
After Insert
As
Begin
insert into Mandallog
select * from inserted
End
-- =============================================
CREATE TRIGGER <Schema_Name, sysname, Schema_Name>.<Trigger_Name, sysname,
Trigger_Name>
ON <Schema_Name, sysname, Schema_Name>.<Table_Name, sysname, Table_Name>
AFTER <Data_Modification_Statements, , INSERT,DELETE,UPDATE>
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for trigger here
END
GO
Select * from Mandal
insert into Mandal(MandalID,MandalName,MandalCode,DistrictID)
values (10,'ABC','DD',11)
Select * from Mandallog
Delete from Mandal
Where MandalID=10
Constraints
GET categorybycategoryid
GET ordersbyorderid
GET supplierbysupplierid
Get shipperbyshipperid
Get employeesbyemployeid
Get orderdetailsbyOrderdetailsID
Get productbyproductid
Ex: Create Procedure GetOrderByOrderID(
@OrderID int
)
As
Begin
Select * From Orders Where OrdersID=@OrderID
End
Here we will get
output as Details
EXEC GetOrderByOrderID 1234
of that particular
OrderID
TDD--- technical design doc
BRD--- business req doc
Distinct keyword
select Distinct Country, City from Customers
select * from Customers Order BY 1 DESC,2 DESC, 7 DESC
Count keyword
select
Count(*)
from Customers
select Country,
Count(*)
from Customers
Group BY Country
To create table in systemDatabase
Then in tempdb----temptables
create table #Country(
CountryID int,
CountryName varchar(100),
CountryCode varchar(100)
)
Select * from #Country
FUNCTIONS:
Create Function fnTotalCustomers()
Returns INT
As
Begin
Declare @Returnvalue INT;
Select @Returnvalue = Count(*) from Customers
Return @Returnvalue
End
Select dbo.fnTotalCustomers()
Temporary table via Stored Procedures;
Create Procedure GetAllCustomersByTempo(procedurename)
As
Begin
Create Table #Customers( --- creating temp table as similar to existing
table.
CustomerID Int,
CustomerName Varchar(50),
ContactName Varchar(50),
Address Varchar(50),
City Varchar(50),
PostalCode Varchar(100),
Country Varchar(50)
)
Insert into #Customers
Select * from Customers(Nolock) —It will stop Others to execute
Select 'Its Coming From #Customers',* from #Customers— (--It is known as
customizing the column and also it is known as Debigging
technique)
Drop Table #Customers – to delete the table
End
--We can alter the table by replacing Create By Alter on First line
To execute-- EXEC GetAllCustomersByTempo
Table variable By Declare;
Declare @Customers Table(
CustomerID Int,
CustomerName Varchar(50),
ContactName Varchar(50),
Address Varchar(50),
Only change is we use
City Varchar(50), in Declare word on
PostalCode Varchar(100), place of Create and @
Country Varchar(50)
on place of #.
)
Insert into @Customers
Select * from Customers(Nolock)
Select 'Its Coming From @Customers ' Custom,* from @Customers
WITH CustomersInCity AS (
SELECT CustomerID, CustomerName, City, Country
FROM Customers
)
SELECT *
FROM CustomersInCity;
Begin Transaction
Begin Try
Insert into Country (CountryID,CountryName)
Values (6,'Australia')
Commit Transaction
End Try
Begin Catch
RollBack Transaction
End Catch
Parameterised Procedure
create procedure GetSuppliersById
(
@GetSupById int
)
As
Begin
Select* from Suppliers where SuppliersID = @GetSupById
End
GO
Exec GetSuppliersById 1 .
1) Query a list of CITY names from STATION for cities that have an
even ID number. Print the results in any order, but exclude duplicates from the
answer.
ANS) SELECT DISTINCT CITY
FROM STATION
WHERE mod(ID,2) = 0;
Query the two cities in STATION with the shortest and longest CITY names, as well as their respective
lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city,
choose the one that comes first when ordered alphabetically
(
SELECT CITY, LENGTH(CITY) AS city_len
FROM STATION
ORDER BY city_len ASC, CITY ASC
LIMIT 1
)
UNION
(
SELECT CITY, LENGTH(CITY) AS city_len
FROM STATION
ORDER BY city_len DESC, CITY ASC
LIMIT 1
);