Sie sind auf Seite 1von 138

Database Administration

Fundamentals
MTA Exam 98-364
Day1
Database concepts
Chapter -1
Understanding Database Concept
A database (db) is an organized collection of data, typically stored in
electronic format. It allows you to input, organize, and retrieve data quickly.
Traditional databases are organized by fields, records, and files.

Example:
Telephone book stored in a disk which is a file
Contains list of records.
Wanted to find the record you have go through each and every record. It is
time consuming.
For which, you enquiry the database to retrieve the record in the form of
query.
Understanding Database Concept
Databases are often found on database servers so that they can be accessed by
multiple users and provide a high level of performance. One popular database
server is Microsoft SQL Server.
They generally are mounted on racks located in a central data center and can be
accessed only through an administrators desktop system.
Primary data files, which have an .mdf extension, used to create user-defined objects.
Database becomes too large and you run out of room on your first hard disk, you can
create secondary data files, which have an .ndf extension, on separate physical hard
disks.
Third type of file used in SQL Server is a transaction log file. Transaction log files use an
.ldf extension and dont contain objects such as tables or views.
Most users do not access a database directly. Instead, they use a database
management system (DBMS) to access it indirectly.
What is DBMS?

A DBMS is a collection of programs that enables you to enter, organize, and


select data in a database.
Example:
A ticket agent may run a ticket system program on his or her desk computer
that in turn accesses a ticketing database.

Types of Database
Flat type Database
Hierarchical Database
Relational Database
Types of Database
Flat-type databases are considered flat because they are two-dimensional
tables consisting of rows and columns.
Example:
Types of Database

Hierarchical database
Hierarchical database use a tree structure that links a number of disparate
elements to one "owner," or "parent," primary record.
Relational Databases

A relational database is similar to a hierarchical database in that data is


stored in tables and any new information is automatically added into the
table without the need to reorganize the table itself.
A table in a relational database can have multiple parents.
Database Fundamental
A simple database with one table is similar to a spreadsheet that contains
rows and columns. However, unlike a spreadsheet, a database allows you to
store thousands of rows of data and then access that information more
quickly than by reading a spreadsheet.
Spreadsheets, however, are designed for and limited to only thousands of
rows per worksheet. When a spreadsheet is opened, the whole file is loaded
into the computers memoryso if enough data is stored, the file may
eventually fail to load due to insufficient memory. Switching to a database
makes the most sense.
They are designed to store billions of rows of data.
They are limited to the computers available hard disk space.
They are optimized to use all a computers available memory to improve
performance
Database Fundamental

CALCULATED VALUES
Databases can also be used to generate calculated values, either within the
database, within the reports generated from the database, or within the
application that is accessing the database.
Relational Database Concepts
A relational database model would organize the data into a database table
that contains rows and columns, with each column corresponding to one
attribute or type of information you want to store. In turn, each row would
correspond to one record or one instance of each column.
Understanding Data Manipulation Language

Data Manipulation Language (DML) is the language element that allows you to use the
core statements INSERT, UPDATE, DELETE, and MERGE to manipulate data in any SQL
Server tables. Core DML statements include the following:
SELECT: Retrieves rows from the database and enables the selection of one or many
rows or columns from one or many tables in SQL Server.
INSERT: Adds one or more new rows to a table or a view in SQL Server.
UPDATE: Changes existing data in one or more columns in a table or view.
DELETE: Removes rows from a table or view.
MERGE: Performs insert, update, or delete operations on a target table based on the results
of a join with a source table.
Data Definition Language DDL

Data Definition Language (DDL) statements form part of the Transact-SQL portion
of SQL Server and can be used to create database objects such as tables and
views.
It deals with creating database objects like tables, constraints, and stored
procedures. The interface used to create these underlying DDL statements is the
SSMS user interface.
The six main DDL statements are as follows:
USE: Changes the database context.
CREATE: Creates a SQL Server database object (table, view, or stored procedure).
ALTER: Changes an existing object.
DROP: Removes an object from the database.
TRUNCATE: Removes rows from a table and frees the space used by those rows.
DELETE: Remove rows from a table but does not free the space used by those rows
removed.
What is SQL Server?

A Relational Database Management System developed by


Microsoft.
Implemented from the specification of RDBMS.
It is also an ORDBMS.
It is platform dependent.
It is both GUI and command based software.
It supports SQL (SEQUEL) language, non-procedural, common
database and case insensitive language.
Usage of SQL Server

To create databases.
To maintain databases.
To analyse the data through SQL Server Analysis Services (SSAS).
To generate reports through SQL Server Reporting Services
(SSRS).
To carry out ETL operations through SQL Server Integration
Services (SSIS).
Versions of SQL Server

Version Year Code Name


6.0 1995 SQL95
6.5 1996 Hydra
7.0 1998 Sphinx
8.0 (2000) 2000 Shiloh
9.0 (2005) 2005 Yukon
10.0 (2008) 2008 Katmai
10.5 (2008 R2) 2010 Kilimanjaro
11.0 (2012) 2012 Denali
12 (2014) 2014 Hekaton (initially), SQL 14
(current)
Installation
SQL Server supports two types of installation
Standalone
Cluster based
SQL Server Components

SQL Server works in client-server architecture.


Supports two types of components
Workstation
Server.
Workstation components are installed in every device/SQL
Server operators machine.
Server components are installed in centralized server. These are
services. Example: SQL Server, SQL Server Agent, SQL browser
etc.
Instance of SQL Server

An instance is an installation of SQL Server.


An instance is an exact copy of the same software.
If we install 'n' times, then 'n' instances will be created.
There are two types of instances in SQL Server a) Default b) Named.
Only one default instance will be supported in one Server.
Multiple named instances will be supported in one Server.
Default instance will take the server name as Instance name.
Default instance service name is MSSQLSERVER.
16 instances will be supported in 2000 version.
50 instances will supported in 2005 and later versions.
Pre-requisites for 2014&2016

Setup support files.


.net framework 4.0.
SQL Server native client.
Windows installer 4.5/later version.
Windows PowerShell 2.0.
Installation Steps
Step 1 Download the Evaluation Edition
from http://www.microsoft.com/download/en/details.aspx?id=29066
Once the software is downloaded, the following files will be available based on
your download (32 or 64 bit) option.
ENU\x86\SQLFULL_x86_ENU_Core.box
ENU\x86\SQLFULL_x86_ENU_Install.exe
ENU\x86\SQLFULL_x86_ENU_Lang.box
OR
ENU\x86\SQLFULL_x64_ENU_Core.box
ENU\x86\SQLFULL_x64_ENU_Install.exe
ENU\x86\SQLFULL_x64_ENU_Lang.box
Note X86 (32 bit) and X64 (64 bit)
Installation Steps
Step 2 Double-click the SQLFULL_x86_ENU_Install.exe or
SQLFULL_x64_ENU_Install.exe, it will extract the required files for
installation in theSQLFULL_x86_ENU or SQLFULL_x86_ENU folder
respectively.

Step 3 Click the SQLFULL_x86_ENU or SQLFULL_x64_ENU_Install.exe


folder and double-click SETUP application. For understanding, here we
have used SQLFULL_x64_ENU_Install.exe software.
Installation Steps

Step 4 Once we click on 'setup' application, the following


screen will open.
Installation Steps

Step 5 Click Installation which is on the left side of the above


screen.
Installation Steps

Step 6 Click the first option of the right side seen on the above
screen. The following screen will open.
Installation Steps
Step 7 Click OK and the following screen pops up.
Installation Steps
Step 8 Click Next to get the following screen.
Installation Steps
Step 9 Make sure to check the product key selection and click
Next.
Installation Steps

Step 10 Select the checkbox to accept the license option and click
Next.
Installation Steps

Step 11 Select SQL Server feature installation option and click Next.
Installation Steps

Step 12 Select Database engine services checkbox and click Next.


Installation Steps

Step 13 Enter the named instance (here I used TestInstance) and


click Next.
Installation Steps

Step 14 Click Next on the above screen and the following screen
appears.
Installation Steps

Step 15 Select service account names and start-up types for the
above listed services and click Collation.
Installation Steps

Step 16 Make sure the correct collation selection is checked and click Next.
Installation Steps

Step 17 Make sure authentication mode selection and


administrators are checked and click Data Directories.
Installation Steps

Step 18 Make sure to select the above directory locations and


click Next. The following screen appears.
Installation Steps

Step 19 Click Next on the above screen.


Installation Steps

Step 20 Click Next on the above screen to the get the following
screen.
Installation Steps

Step 21 Make sure to check the above selection correctly and


click Install.

Installation is successful as shown in the above


screen. Click Close to finish.
MS SQL Server - Management Studio

First Method
Start All Programs MS SQL Server 2012 SQL Server
Management Studio
Second Method
Go to Run and SSMS .Then click Enter.
SQL Server Login Database

What is credential?
Credentials are simply a username and a password that you provide your username
and password when logging on to Windows or even your e-mail account. This
username and password builds up the credentials.
There are four types of logins provided by SQL Server:
A login based on Windows credentials.
A login specific to SQL Server.
A login mapped to a certificate.
A login mapped to asymmetric key.
Logins based on Windows credentials facilitates you to log in to SQL Server using a
Windows username and password. If you want to create your own credentials
(username and password,) you can create a login specific to SQL Server.
To create, alter, or remove a SQL Server login, you can take one of two approaches:
Using SQL Server Management Studio.
Using T-SQL statements.
Using SQL Server Management Studio

Open SQL Server management studio


Go to Security:
Using SQL Server Management Studio

Open Security. You will see "Logins". Right click on Logins and
you will get "New Login"?

Here you can set a login name and password.


What is a Database?
Database is a collection of objects such as table, view, stored
procedure, function, trigger, etc.
In MS SQL Server, two types of databases are available.
System databases
User Databases
System Databases
Master
Model
MSDB
Tempdb
Resource (Introduced in 2005 version)
Distribution (Its for Replication feature only)
Create Database

User Databases
Method 1 Using T-SQL Script

Create database Testdb


Method 2 Using SQL Server Management Studio
Create Database
Select the database
Using TSQL Script

use urdb

or
SQL Server Data types

Data types can be divided in three types:


String Types
Number Types
Date Types
String Data Type
Data Type Description

char(n) It is a fixed width character string. It can store maximum 8,000 characters.
varchar(n) It is a variable width character string. It can store maximum 8,000 characters.
varchar(max) It is a variable width character string. It can store maximum 1,073,741,824
characters.
text It is a variable width character string. It can store maximum 2GB of text data.
nchar It is a fixed width unicode string. It can store maximum 4,000 characters.
nvarchar It is a variable width unicode string. It can store maximum 4,000 characters.
nvarchar(max) It is a variable width unicode string. It can store maximum 536,870,912 characters.
ntext It is a variable width unicode string. It can store maximum 2GB of text data.
bit It allows 0, 1, or NULL values.
binary(n) It is a fixed width binary string. It can store maximum 8,000 bytes
varbinary It is a variable width binary string. It can store maximum 8,000 bytes
varbinary(max) It is a variable width binary string. It can store maximum 2GB.
image It is a variable width binary string. It can store maximum 2GB.
Number Types
data type description storage
tinyint allows whole numbers from 0 to 255 1 byte
smallint allows whole numbers between -32,768 and 32,767 2 bytes
int allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
bigint allows whole numbers between -9,223,372,036,854,775,808 and 8 bytes
9,223,372,036,854,775,807
decimal(p,s) fixed precision and scale numbers.allows numbers from -10^38 +1 to 10^38 ?1.the p 5-17 bytes
parameter indicates the maximum total number of digits that can be stored (both to
the left and to the right of the decimal point). p must be a value from 1 to 38. default
is 18.the s parameter indicates the maximum number of digits stored to the right of
the decimal point. s must be a value from 0 to p. default value is 0

numeric(p,s) fixed precision and scale numbers.allows numbers from -10^38 +1 to 10^38 ?1.the p 5-17 bytes
parameter indicates the maximum total number of digits that can be stored (both to
the left and to the right of the decimal point). p must be a value from 1 to 38. default
is 18.the s parameter indicates the maximum number of digits stored to the right of
the decimal point. s must be a value from 0 to p. default value is 0

smallmoney monetary data from -214,748.3648 to 214,748.3647 4 bytes


money monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes
float(n) floating precision number data from -1.79e + 308 to 1.79e + 308.the n parameter 4 or 8 bytes
indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte field and
float(53) holds an 8-byte field. default value of n is 53.
real floating precision number data from -3.40e + 38 to 3.40e + 38 4 bytes
Date Types
Data Type Description Storage
datetime It specifies a date and time from january 1, 1753 to december 31, 8 bytes
9999 with an accuracy of 3.33 milliseconds.
datetime2 It specifies a date and time from january 1, 0001 to december 31, 6-8 bytes
9999 with an accuracy of 100 nanoseconds.
smalldatetime It specifies a date and time from january 1, 1900 to june 6, 2079 with 4 bytes
an accuracy of 1 minute.
date It is used to store a date only. It specifies a date from january 1, 0001 3 bytes
to december 31, 9999.
time It is used to store a time only to an accuracy of 100 nanoseconds. 3-5 bytes

datetimeoffset It is the same as datetime2 with the addition of a time zone offset. 8-10 bytes

timestamp It stores a unique number that gets updated every time a row gets
created or modified. the timestamp value is based upon an internal
clock and does not correspond to real time. each table may have only
one timestamp variable.
Create Table-GUI
CREATE TABLE Statement

The SQL Server (Transact-SQL) CREATE TABLE statement allows


you to create and define a table.
Syntax
CREATE TABLE table_name ( column1 datatype [ NULL | NOT
NULL ], column2 datatype [ NULL | NOT NULL ], ... );
Create Table Example

T-SQL Script

CREATE TABLE employees ( employee_id INT PRIMARY KEY,


last_name VARCHAR(50) NOT NULL, first_name VARCHAR(50),
salary MONEY );

Command(s) completed successfully.


Constraint in SQL - Server

Constraint are using to restricted the insertion of


unwanted data in any columns. we can create
constraints on single or multiple columns of any table.
It maintain the data integrity of the table.
There are 6 types of constraints in Sql Server:-
Primary key constraint.
Foreign Key constraint.
Unique Key constraint.
Not Null constraint.
Check constraint
Default constraint
Primary Key constraint

What is a primary key in SQL Server?


A primary key is a single field or combination of fields that
uniquely defines a record. None of the fields that are part of the
primary key can contain a null value. A table can have only one
primary key.
A primary key can be defined in either a CREATE TABLE statement
or an ALTER TABLE statement.

Primary Key constraint

Syntax
C

CREATE TABLE table_name ( column1 datatype [ NULL | NOT NULL ] [


PRIMARY KEY ], column2 datatype [ NULL | NOT NULL ], ... );
OR
CREATE TABLE table_name ( column1 datatype [ NULL | NOT NULL ], column2 datatype [ NULL |
NOT NULL ], ... CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n) );
Primary Key constraint
Example:

CREATE TABLE employees ( employee_id INT PRIMARY KEY,


last_name VARCHAR(50) NOT NULL, first_name VARCHAR(50) NOT
NULL, salary MONEY );
(or)
CREATE TABLE employees ( employee_id INT, last_name
VARCHAR(50) NOT NULL, first_name VARCHAR(50) NOT NULL, salary
MONEY, CONSTRAINT employees_pk PRIMARY KEY (employee_id));
Foreign Key constraint

In SQL Server, foreign key is used to enforce referential integrity


within your SQL Server database. It specifies that a value in one
table must also appear in another table.
The referenced table is called parent table while the table having
foreign key is called child table. The foreign key in the child table
will generally reference a primary key in the parent table.
A foreign key can be created using either a CREATE TABLE
statement or an ALTER TABLE statement.
Foreign Key constraint

Syntax:

CREATE TABLE child_table


(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
...
CONSTRAINT fk_name
FOREIGN KEY (child_col1, child_col2, ... child_col_n)
REFERENCES parent_table (parent_col1, parent_col2, ... parent_col
_n)
[ON DELETE {NO ACTION | CASCADE | SET NULL | SET DEFAUL
T} ]
[ON UPDATE {NO ACTION | CASCADE | SET NULL | SET DEFAU
LT} ]
);
Foreign Key constraint

Example:
Let's create two table "products" and "inventory" where
primary key of products table is "product_id" which is
foreign key in "inventory" table.

CREATE TABLE products


( product_id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
category VARCHAR(25)
);

Foreign Key constraint

CREATE TABLE inventory


( inventory_id INT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT,
min_level INT,
max_level INT,
CONSTRAINT fk_inv_product_id
FOREIGN KEY (product_id)
REFERENCES products (product_id)
);
Create foreign key with more than one field

Let's create two table "products2" and "inventory2". In this example, "products2" table has a primary key that
contains both the product_name and location columns. Therefore, the second table and foreign key must also
reference these two columns.

CREATE TABLE products2


( product_name VARCHAR(50) NOT NULL, location VARCHAR(50) NOT NULL,
category VARCHAR(25) CONSTRAINT products_pk PRIMARY KEY (product_name, location) );
Create foreign key with more than one field

CREATE TABLE inventory2


( inventory_id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
location VARCHAR(50) NOT NULL,
quantity INT,
min_level INT,
max_level INT,
CONSTRAINT fk_inv_product
FOREIGN KEY (product_name, location)
REFERENCES products2 (product_name, location)
);
Unique Key constraint

Unique key constraint is use to make sure that there is no duplicate value in that column.
Both unique key and primary key both enforces the uniqueness of column but there is one
difference between them unique key constraint allow one null value but primary key does not
null value.In a table we create one primary key but we can create more than one unique key
in Sql Server.
Syntax:

Create Table Table_Name(column_Name Datatype Constraint Constraint_Name Unique )

Example:

Create Table MY_Tab ( IId int constraint Unique_Cons Unique ,


Name nvarchar(50) )
Not null constraint

A Not null constraint restrict the insertion of null values into a column. If we are using a Not Null
Constraint for a column then we cannot ignore the value of this column during an insert of data into
the table.
Syntax

CREATE TABLE Table_Name( Column_Name Datatype CONSTRAINT Constraint_Name NOT NULL);


Example:
Create Table My_Constraint
(
IID int NOT NULL,
Name nvarchar(50) CONSTRAINT Cons_NotNull not null,
Age int Not Null,
)

Check Constraint
A Check constraint checks for a specific condition before inserting data into a table. If the data passes all
the Check constraints then the data will be inserted into the table otherwise the data for insertion will be
discarded. The CHECK constraint ensures that all values in a column satisfies certain conditions.
Syntax:

Create Table Table_Name (Column_Name Datatype Constraint Constraint_Name Check(Condition))

Example:

Create Table constraint_s (IId int Constraint Constraint_Name Check(IId>100))


Default Constraint
Specifies a default value for when a value is not specified for this column. If in an insertion query
any value is not specified for this column then the default value will be inserted into the column.
Syntax

Create Table Table_Name(Column_Name DataType Constraint Constraint_Name Default(Value))

Example

CREATE TABLE books ( book_id INT NOT NULL PRIMARY KEY, title varchar(255) NOT NULL, pubdate
date NOT NULL, isbn varchar(13) DEFAULT '1-84356-028-3', author_id INT NOT NULL )

INSERT INTO books(book_id,title,pubdate,author_id) VALUES(123,'SQL Tutorial','2010-01-01',1);


SELECT INTO Statement
The SQL Server (Transact-SQL) SELECT INTO statement is used to
create a table from an existing table by copying the existing
table's columns.
syntax:
SELECT expressions INTO new_table FROM tables [WHERE
conditions];
Example:

SELECT employee_id, last_name, first_name INTO contacts FROM employees WHERE


employee_id < 1000;
SQL Server Indexes
What is an Index in SQL Server?
An index is a performance-tuning method of allowing faster retrieval of records. An
index creates an entry for each value that appears in the indexed columns.
Syntax

CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name ON table_name


( column1 [ASC | DESC ], ... column_n [ ASC | DESC ] )

Example :

CREATE INDEX contacts_idx ON contacts (last_name);


SQL Server Indexes
Create Index on More than one column

CREATE INDEX contacts_idx ON contacts (last_name DESC, first_name DESC);

UNIQUE Index Example

CREATE UNIQUE INDEX contacts_uidx ON contacts (last_name, first_name);


Clustered Index

CREATE UNIQUE CLUSTERED INDEX contacts_uidx ON contacts (last_name, first_name);


SQL Server Indexes
Rename an Index
Syntax
sp_rename 'table_name.old_index_name', 'new_index_name', 'INDEX;
Example
sp_rename 'contacts.contacts_idx', 'contacts_index_cname', 'INDEX;

Drop an Index
Syntax
DROP INDEX table_name.index_name;
Example
DROP INDEX contacts.contacts_idx;
ALTER TABLE Statement

The ALTER TABLE statement in SQL Server (Transact-SQL) to add a column,


modify a column, drop a column, rename a column or rename a table.
Add column in table.
Syntax

ALTER TABLE table_name ADD column_name column-definition;

Example

ALTER TABLE employees ADD last_name VARCHAR(50);


ALTER TABLE Statement

Add multiple columns in table


Syntax:

ALTER TABLE table_name ADD column_1 column-definition, column_2 column-


definition, ... column_n column_definition;

Example:

ALTER TABLE employees ADD last_name VARCHAR(50), first_name VARCHAR(40);


ALTER TABLE Statement
Modify column in table
Syntax

ALTER TABLE table_name ALTER COLUMN column_name column_type;

Example:

ALTER TABLE employees ALTER COLUMN last_name VARCHAR(75) NOT NULL;


ALTER TABLE Statement
Drop column in table
Syntax:

ALTER TABLE table_name DROP COLUMN column_name;

Example:

ALTER TABLE employees DROP COLUMN last_name;


ALTER TABLE Statement
Rename column in table

Syntax

sp_rename 'table_name.old_column_name', 'new_column_name', 'COLUMN';

Example

sp_rename 'employees.last_name', 'lname', 'COLUMN';


ALTER TABLE Statement

Rename table

Syntax

sp_rename 'old_table_name', 'new_table_name';

Example

sp_rename 'employees', 'emps';


DROP TABLE Statement
The SQL Server (Transact-SQL) DROP TABLE statement allows you to
remove or delete a table from the SQL Server database.
Syntax
DROP TABLE table_name;
Example :
DROP TABLE employees;
Dropping the table from another Database:
DROP TABLE Database2.dbo.suppliers;
Dropping LOCAL TEMPORARY TABLE
DROP TABLE #employees;
Dropping GLOBAL TEMPORARY TABLE
DROP TABLE ##suppliers;
Primary Key - Using ALTER TABLE
statement
Syntax
ALTER TABLE table_name ADD CONSTRAINT constraint_name
PRIMARY KEY (column1, column2, ... column_n);
Example
ALTER TABLE employees ADD CONSTRAINT employees_pk
PRIMARY KEY (employee_id);
Primary key on multiple columns
ALTER TABLE employees ADD CONSTRAINT employees_pk
PRIMARY KEY (last_name, first_name);
Disable Primary Key

You can disable a primary key using the ALTER TABLE statement in
SQL Server (Transact-SQL).
Syntax

ALTER INDEX constraint_name ON table_name DISABLE;

Example

ALTER INDEX employees_pk ON employees DISABLE;


Enable Primary Key

You can enable a primary key using the ALTER INDEX statement in SQL Server
(Transact-SQL).
Syntax

ALTER INDEX constraint_name ON table_name REBUILD;

Example

ALTER INDEX employees_pk ON employees REBUILD;


Drop Primary Key

Syntax

ALTER TABLE table_name DROP CONSTRAINT


constraint_name;

Example

ALTER TABLE employees DROP CONSTRAINT employees_pk;


Enable a Foreign Key

ALTER TABLE statement is used to enable a foreign key in SQL Server.

Syntax:

ALTER TABLE table_name CHECK CONSTRAINT fk_name;

Example:

ALTER TABLE inventory HECK CONSTRAINT fk_inv_product_id;


Disable Foreign Key

ALTER TABLE statement is used to disable a foreign key.

Syntax:

ALTER TABLE table_name NOCHECK CONSTRAINT fk_name;

Example:

CREATE TABLE products3 ( product_id INT PRIMARY KEY,


product_name VARCHAR(50) NOT NULL, category VARCHAR(25));
Disable Foreign Key

CREATE TABLE inventory3


( inventory_id INT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT,
min_level INT,
max_level INT,
CONSTRAINT fk_inv_product_id
FOREIGN KEY (product_id)
REFERENCES products3 (product_id)
);

ALTER TABLE [mydb].[dbo].[inventory] NOCHECK CONSTRAINT fk_inv_product_id;


Drop a Foreign Key
ALTER TABLE statement is used to drop a foreign key from a table once it has been
created.
Syntax:

ALTER TABLE table_name DROP CONSTRAINT fk_name;

Example:

CREATE TABLE products


( product_id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
category VARCHAR(25)
);
Drop a Foreign Key
CREATE TABLE inventory
( inventory_id INT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT,
min_level INT,
max_level INT,
CONSTRAINT fk_inv_product_id
FOREIGN KEY (product_id)
REFERENCES products (product_id)
);

ALTER TABLE [mydb].[dbo].[inventory] DROP CONSTRAINT fk_inv_prod


uct_id;
Day2
Data Manipulation Language
SQL Server Insert Data

INSERT statement is used to insert a single record or multiple records into a


table.
Syntax:
INSERT INTO [database_name].[dbo].[table_name]
(column1, column2, ... )
VALUES
(expression1, expression2, ... ),
(expression1, expression2, ... ),
...;
Example using T-sql

insert into product (productid,productname,quantity,uniatprice, unitstock,


Reorderlevel)values(111,'Ironrod',25,35,100, 5);

(1 row(s) affected)
SQL Server Insert Data-GUI
SQL Server Update Data
UPDATE statement is used to update or modify the already inserted records
into a table.
USE [master]
GO
UPDATE [dbo].[product]
SET [productid] = <productid, int,>
,[productname] = <productname, varchar(50),>
,[quantity] = <quantity, int,>
,[uniatprice] = <uniatprice, money,>
,[unitstock] = <unitstock, int,>
,[Reorderlevel] = <Reorderlevel, int,>
WHERE <Search Conditions,,>
GO
Use the SQL Server management Studio

TSQL - script

update product set productid=2001 where productname='ironrod'


SQL Server DELETE Data
USE [master]
GO

DELETE FROM [dbo].[product]


WHERE <Search Conditions,,>
GO

Syntax:

USE [master]
GO

DELETE FROM [dbo].[product]


WHERE <Search Conditions,,>
GO
SQL Server DELETE Data

use [master]
select * from [dbo].[product];
DELETE FROM [master].[dbo].[product] where productid=2001;

(1 row(s) affected)
SQL Server Create View

A view is a virtual table created according to the result set of an SQL


statement.
A view contains rows and columns, just like a real table. The columns in the
view are the columns from one or more real tables in the database. SQL
functions, WHERE, and JOIN statements can also be added to the view.
There are two ways to create a view in SQL Server:
By using SQL Server management studio UI.
By using SQL Server query statement.
By using SQL Server management studio UI
By using SQL Server query statement.

Syntax:

CREATE VIEW view_name AS SELECT column1, column2, ...


FROM table_name WHERE condition;

Example :

CREATE VIEW [Student_view] AS SELECT id, name, age FROM [master].[dbo]


.[Student] WHERE id > 3;

query the view:

SELECT * FROM [Student_view];


Update a View
Syntax:

CREATE OR REPLACE VIEW view_name AS SELECT column1, column2, ...


FROM table_name WHERE condition;

Alter View Example:

ALTER VIEW [Student_view] AS SELECT id, name, age, fee FROM [javatpoint].[dbo].[Student]
WHERE id > 3;
SQL Server DROP a View

Syntax:

DROP VIEW view_name;

Example:

DROP VIEW [Student_view];


Day3
Data Manipulation Language- select
Basic Select

Syntax:
SELECT *|{[DISTINCT] column|expression [alias],...} FROM table;
Example:
SELECT * FROM departments;
Selecting Specific column

SELECT department_id, location_id FROM departments;


Using Arithmetic Operators
SELECT last_name, salary, salary + 300 FROM employees;

Operator Precedency
SELECT last_name, salary, 12*salary+100 FROM employees;
Using Arithmetic Operators
SELECT last_name, salary, 12*(salary+100) FROM employees;

Displaying a null value


SELECT last_name, salary, 12*(salary+100) FROM employees;
Using Column Aliases
Select department_id as departmentNo, location_id+300 locationid from
departments

Select department_id "departmentNo", location_id+300 "location id" from


departments
Distinct Values
SELECT DISTINCT salary FROM [mydb].[dbo].[Employees] WHERE salary > 15000

CONCATENATION OPERATOR
SELECT last_name + job_id AS "Employees" FROM employees;
Literal character string

SELECT last_name +' is a '+ job_id AS "Employee Details" FROM employees;


Using where clause

SELECT employee_id, last_name, job_id, department_id FROM employees


WHERE department_id = 90 ;

Character Strings
SELECT last_name, job_id, department_id FROM employees WHERE last_name = 'Whalen' ;
Comparision Operator

SELECT last_name, salary FROM employees WHERE salary <= 3000 ;

SELECT last_name, salary FROM employees WHERE salary BETWEEN 2500 AND
3500 ;
Using IN condition

SELECT employee_id, last_name, salary, manager_id FROM employees WHERE


manager_id IN (100, 101, 201) ;
Using Like Operator and NULL condition
SELECT first_name FROM employees WHERE first_name LIKE S%

SELECT last_name FROM employees WHERE last_name LIKE '_o% ;

SELECT last_name, manager_id FROM employees WHERE manager_id IS null


Logical condition
Logical condition
SELECT employee_id, last_name, job_id, salary FROM employees WHERE
salary >=10000 AND job_id LIKE '%MAN% ;

SELECT employee_id, last_name, job_id, salary FROM employees WHERE


salary >=10000 OR job_id LIKE '%MAN%' ;
Logical condition
SELECT last_name, job_id FROM employees WHERE job_id NOT IN ('IT_PROG',
'ST_CLERK', 'SA_REP) ;
Rules of Precedence
Rules of Precedence

SELECT last_name, job_id, salary FROM employees WHERE job_id = 'SA_REP


OR job_id = 'AD_PRES AND salary > 15000;
ODER BY CLAUSE (SORTING)
SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date

SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date


DESC ;
SORTING
SELECT employee_id, last_name, salary*12 annsal FROM employees ORDER BY
annsal ;

SELECT last_name, department_id, salary FROM employees ORDER BY


department_id, salary DESC;
Function in SQL SERVER
String Functions
SELECTemployee_id,upper(last_name)lastname,department_id,lower(email)e
mailid FROM employees WHERE last_name ='higgins;

SELECT first_name , last_name , LEFT(first_name , 1) + LEFT(last_name , 3) +


'@mymail.com FROM employees
String Function
SELECT first_name , last_name , LEFT(first_name , 1) + RIGHT(last_name , 3) +
'@mymail.com FROM employees

SELECT ASCII(last_name) AS NumCodeOfFirstChar FROM employees;


String Function

SELECT CHAR(65) AS NumberCodeToCharacter;

SELECT CHARINDEX('t', 'Customer') AS MatchPosition;

SELECT CONCAT(first_name, last_name) Name from employees

SELECT DATALENGTH(' ThubAditya );

SELECT LEN('ThubAditya);

SELECT LTRIM(' Thub Aditya') AS LeftTrimmedString;


String Function
SELECT NCHAR(65) AS NumberCodeToUnicode;

SELECT PATINDEX('%Thub%', 'AdityaThub);

SELECT REPLACE('Rummy', 'R', 'M);

SELECT RTRIM('Thub ') AS RightTrimmedString;

SELECT SPACE(10);

SELECT STUFF('HTML TRAINING', 1, 4, 'DATABASE);

SELECT SUBSTRING('HTML TRAINING', 1, 4)


Numeric Function
SELECT Abs(-243.5) AS AbsNum;

SELECT AVG(salary) AS salaryAverage FROM employees;

SELECT CEILING(25.75) AS CeilValue;

SELECT COUNT(Department_id) AS NumberOfDept FROM employees;

SELECT FLOOR(25.75) AS FloorValue;

SELECT MAX(salary) MaxSal, Min(salary) MinSal FROM Employees;


Numeric Function

SELECT RAND();

SELECT ROUND(235.415, 2) AS RoundValue;


SELECT SIGN(255.0);
If number > 0, it returns 1
If number = 0, it returns 0
If number < 0, it returns -1
SELECT sum(salary) sum FROM Employees;
Date Functions
SELECT CURRENT_TIMESTAMP;

SELECT DATEADD(year, 1, '2017/08/25') AS DateAdd;

SELECT DATEDIFF(year, '2017/08/25', '2011/08/25') AS DateDiff;

SELECT DATENAME(year, '2017/08/25') AS DatePartString;

SELECT DAY('2017/08/25') AS DayOfMonth;

SELECT GETDATE();

SELECT GETUTCDATE();
DATE FUNCTION

SELECT MONTH('2017/08/25') AS Month;

SELECT YEAR('2017/08/25') AS Year;


Conversion Function

SELECT CAST(25.65 AS int);

SELECT CONVERT(int, 25.65);


Advance Function

The COALESCE() function returns the first non-null expression in a list.


SELECT COALESCE(NULL, NULL, NULL, 'Thub', NULL, 'Aditya);

Returns the name of the current user in the SQL Server database.
SELECT CURRENT_USER;

ISDATE() function returns 1 if the expression is a valid date, otherwise 0.


SELECT ISDATE('2017-08-25);
The ISNULL() function lets you return an alternative value when an expression
is NULL.
SELECT ISNULL(NULL, 'Thub');
Advance Function

The ISNUMERIC() function returns 1 if the expression is a valid number,


otherwise 0.
SELECT ISNUMERIC(4567);

The NULLIF() function compares two expressions.


If expr1 and expr2 are equal, the NULLIF() function returns NULL. Otherwise,
it returns expr1.
SELECT NULLIF(25, 25);
The SESSION_USER function return the user name of the current session in the
SQL Server database.
SELECT SESSION_USER;
Advance Function

The SESSIONPROPERTY() function returns the setting for a specified option of


a session.
SELECT SESSIONPROPERTY('ANSI_NULLS);

The SYSTEM_USER function returns the login name information for the current
user in th e SQL Server database
SELECT SYSTEM_USER;.

The USER_NAME() function returns the user name in the SQL Server database.
SELECT USER_NAME();
CASE Statement
The CASE statement has the functionality of an IF-THEN-ELSE statement. You
can use the CASE statement within a SQL statement.
Syntax:
CASE expression
WHEN value_1 THEN result_1
WHEN value_2 THEN result_2
...
WHEN value_n THEN result_n
ELSE result
END
CASE Statement

SELECT last_name, job_id, salary,


CASE job_id WHEN 'IT_PROG' THEN 1.10*salary
WHEN 'ST_CLERK' THEN 1.15*salary
WHEN 'SA_REP' THEN 1.20*salary
ELSE salary END "REVISED_SALARY"
FROM employees;
Group Functions

Group functions operate on sets of rows to give one result per group.
Type of function
AVG
Count
Max
Min
Stddev
sum
SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) FROM employees WHERE
job_id LIKE '%REP%;

SELECT COUNT(*) FROM employees WHERE department_id = 50;

SELECT COUNT(commission_pct) FROM employees WHERE department_id = 80;

SELECT AVG(NVL(commission_pct, 0)) FROM employees;


GroupBy Clause

SELECT department_id, AVG(salary) FROM employees GROUP BY


department_id ;

SELECT AVG(salary) FROM employees GROUP BY department_id ;

SELECT department_id dept_id, job_id, SUM(salary) FROM employees GROUP


BY department_id, job_id ;

SELECT department_id, COUNT(last_name) FROM employees;


Error: not a single-group group function
Having Clause

SELECT department_id, MAX(salary) FROM employees GROUP BY


department_id HAVING MAX(salary)>10000 ;

SELECT job_id, SUM(salary) PAYROLL FROM employees WHERE job_id NOT LIKE
'%REP% GROUP BY job_id HAVING SUM(salary) > 13000 ORDER BY SUM(salary);

SELECT MAX(AVG(salary)) FROM employees GROUP BY department_id;

Das könnte Ihnen auch gefallen