Database Fundamental SQL Server
Database Fundamental SQL Server
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?
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
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?
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
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 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 20 Click Next on the above screen to the get the following
screen.
Installation Steps
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 Security. You will see "Logins". Right click on Logins and
you will get "New Login"?
User Databases
Method 1 Using T-SQL Script
use urdb
or
SQL Server Data types
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
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
T-SQL Script
Syntax
C
Syntax:
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.
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.
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:
Example:
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
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:
Example:
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 )
Example :
Drop an Index
Syntax
DROP INDEX table_name.index_name;
Example
DROP INDEX contacts.contacts_idx;
ALTER TABLE Statement
Example
Example:
Example:
Example:
Syntax
Example
Rename table
Syntax
Example
You can disable a primary key using the ALTER TABLE statement in
SQL Server (Transact-SQL).
Syntax
Example
You can enable a primary key using the ALTER INDEX statement in SQL Server
(Transact-SQL).
Syntax
Example
Syntax
Example
Syntax:
Example:
Syntax:
Example:
Example:
(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
Syntax:
USE [master]
GO
use [master]
select * from [dbo].[product];
DELETE FROM [master].[dbo].[product] where productid=2001;
(1 row(s) affected)
SQL Server Create View
Syntax:
Example :
ALTER VIEW [Student_view] AS SELECT id, name, age, fee FROM [javatpoint].[dbo].[Student]
WHERE id > 3;
SQL Server DROP a View
Syntax:
Example:
Syntax:
SELECT *|{[DISTINCT] column|expression [alias],...} FROM table;
Example:
SELECT * FROM departments;
Selecting Specific column
Operator Precedency
SELECT last_name, salary, 12*salary+100 FROM employees;
Using Arithmetic Operators
SELECT last_name, salary, 12*(salary+100) FROM employees;
CONCATENATION OPERATOR
SELECT last_name + job_id AS "Employees" FROM employees;
Literal character string
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 BETWEEN 2500 AND
3500 ;
Using IN condition
SELECT LEN('ThubAditya);
SELECT SPACE(10);
SELECT RAND();
SELECT GETDATE();
SELECT GETUTCDATE();
DATE FUNCTION
Returns the name of the current user in the SQL Server database.
SELECT CURRENT_USER;
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
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 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);