Sie sind auf Seite 1von 46

Database Systems

COMP- 213

By:
Shahid Mahmood
Warning!
 Lecture slides are high-level description
of lectures

 Relying only upon the slides do not


guarantee good grades in exams

 For achieving good grades in exams


always attend lectures, Study books,
explore web and other resources, and
be efficient in submitting your allocated
tasks.
Agenda
 Structured Query Language (SQL)

 Historical aspects

 Rules of the Format

 Data Definition Language

 Data Manipulation Language


SQL (Structured Query Language)
 Also known as Structured English Query Language
(Sequel)

 A de-facto standard (accepted by ANSI, ISO etc.)


for relational DBMSs

 It is used for any type of interaction with the


database through DBMS

 It is used for creating/ altering/ deleting


database, tables, views, users etc.,

 It is used for data insertion, updation and deletion


SQL (Historical aspects)
 Relational data model was introduced by Codd
in 1970

 IBM started “system R” that adopted Sequel as


manipulation language

 1979 Oracle was the first commercial DBMS


which supported SQL

 First standard of SQL was defined by ANSI and


ISO in 1986, which was refined in 1989 as SQL-
89, later on as SQL-92 and then as SQL-97
Benefits of Standard SQL
 Reduce training cost

 Application Portability

 Application sustainability

 Reduced vender’s dependability

 Convenient cross system communication


General format (convention)
 SQL is NOT case sensitive.

 Reserved words in capital

 User-defined identifiers in lowercase

 Valid identifiers rules (Not in reserved words, Name can


start from: capital, underscore, number sign, @)

 Optional [with in square bracket]

 Required items {}

 Choices |

 Number of items n separated by comma[,…n]


(you can repeat n times whatever is written before comma)
General format (convention)
 SQL is NOT case sensitive.

Select [All | Distinct]

 (* | select list)

FROM

{TABLE | VIEW [,…n]}

 Select * FROM Std


SQL Server Data Type (String
Type:)
Data type Description Storage

char(n) Fixed width character string. Maximum 8,000 characters Defined width

2 bytes +
varchar(n) Variable width character string. Maximum 8,000 characters
number of chars

2 bytes +
varchar(max) Variable width character string. Maximum 1,073,741,824 characters
number of chars

4 bytes +
text Variable width character string. Maximum 2GB of text data
number of chars

nchar Fixed width Unicode string. Maximum 4,000 characters Defined width x 2

nvarchar Variable width Unicode string. Maximum 4,000 characters


SQL Server Data Type (String
Type:) Cont.
Data type Description Storage

nvarchar(max) Variable width Unicode string. Maximum 536,870,912 characters

ntext Variable width Unicode string. Maximum 2GB of text data

bit Allows 0, 1, or NULL

binary(n) Fixed width binary string. Maximum 8,000 bytes

varbinary Variable width binary string. Maximum 8,000 bytes

varbinary(max) Variable width binary string. Maximum 2GB

image Variable width binary string. Maximum 2GB


SQL Server Data Type (Number
Type:)
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

Allows whole numbers between -9,223,372,036,854,775,808 and


bigint 8 bytes
9,223,372,036,854,775,807

Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 –1.
The p 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
decimal(p,s) 5-17 bytes
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
SQL Server Data Type (Number
Type:) Cont.
Data type Description Storage

Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 –1.
The p 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
numeric(p,s) 5-17 bytes
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

Floating precision number data from -1.79E + 308 to 1.79E + 308.The n


float(n) parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4- 4 or 8 bytes
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


SQL Server Data Type (Date Type:)
From January 1, 1753 to December 31, 9999 with an accuracy of 3.33
datetime 8 bytes
milliseconds

datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds 6-8 bytes

smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes

date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes

time Store a time only to an accuracy of 100 nanoseconds 3-5 bytes

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

Stores a unique number that gets updated every time a row gets created or modified. The timestamp value is
timestamp based upon an internal clock and does not correspond to real time. Each table may have only one timestamp
variable
SQL Server Data Type (Other
Type:)
Data type Description

sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp

uniqueidentifier Stores a globally unique identifier (GUID)

xml Stores XML formatted data. Maximum 2GB

cursor Stores a reference to a cursor used for database operations

table Stores a result-set for later processing


Types of SQL commands
 SQL Commands can be divided into 3
categories
1. Data Definition Language (DDL)

2. Data Manipulation Language (DML)

3. Data Control Language (DCL)


Types of SQL commands
1. Data Definition Language (DDL): It
includes the statements that work with
the objects in a database

CREATE: DATABASE, TABLE, INDEX,

ALTER: TABLE

DROP: DATABASE, TABLE, INDEX


Types of SQL commands
2. Data Manipulation Language (DML): It
includes the statements that work with
the data in a database

SELECT

INSERT

UPDATE

DELETE
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


General Coding Rules
 SQL is non-case sensitive language

1. Use spaces to separate the elements in each


statement

2. Use commas to separate the items in a list

3. Use single quote to enclose literal values

4. Line breaks, white space, indentation, and


capitalization have NO effect on the operation
of a statement
Formatting rules for identifiers
1. The first character of an identifier must be a
letter, underscore (_), at sign (@), or a
number sign (#) [Unicode Standard 2.0]

2. All characters after the first must be a letter

3. An identifier can not be a Transact-SQL


reserved word

4. An identifier can’t contain spaces or special


characters other than those already mentioned

5. The identifier can contain 1-128 characters


Comments
1. To code a block comment that consists of more
than one line, type /* at the start of the block
and */ at the end

2. To code a single-line comment, type -- followed


by the comment
Coding recommendation
1. Start each new clause on a new line

2. Break long clauses into multiple lines and


indent continued lines

3. Capitalize the first letter of each key word and


each word in column and table names

4. Use comments only for portions of code that


are difficult to understand. Then make sure that
the comments are correct and up-to-date
CREATE Commands
 CREATE DATABASE:

CREATE DATABASE database_name

[ON [PRIMARY] (FILENAME = ‘file_name’)]

[FOR ATTACH]

Example: CREATE DATABASE Test_db

ON PRIMARY (FILENAME = ‘C:\Program


files\Microsoft SQL
Server\MSSQL\Data\Test_db.mdf’)

FOR ATTACH
CREATE Commands
 CREATE TABLE command is used to:

- Create a table

- Define attribute of the table with data types

- Define different constraints on attributes, like


primary and foreign keys, check constrain, not null,
default value etc.
CREATE Commands
 CREATE TABLE:

CREATE TABLE

[database_name.[OWNER]. | OWNER.]

table_name ({<column_definition> | column_name


AS computed_column_expression |
<table_constraint>})

|[{PRIMARY KEY | UNIQUE}[,….n]])


CREATE Commands
<column_constraint>::=

[CONSTRAINT constrain_name]

{[NULL|NOT NULL]

|[{PRIMARY KEY | UNIQUE}]

|[[FOREIGN KEY]

REFERENCES ref_table [(ref_column)]

[ON DELETE {CASCADE | NO ACTION}]

[ON UPDATE {CASCADE | NO ACTION}]]

| CHECK (logical_expression)}
System databases of SQL Server
System database Description
Records all the system-level information for an instance of SQL Server. It
master Database records the existence and location of all other databases as well as the
initialization information for SQL Server

msdb Database Is used by SQL Server Agent for scheduling alerts and jobs.

Is used as the template for all databases created on the instance of SQL Server.
Modifications made to the model database, such as database size, collation,
model Database
recovery model, and other database options, are applied to any databases
created afterward.
Is a read-only database that contains system objects that are included with SQL
Resource Database Server. System objects are physically persisted in the Resource database, but
they logically appear in the sys schema of every database.

tempdb Database Is a workspace for holding temporary objects or intermediate result sets.
CREATE Table (for Paper work)
Column Data Type Data Length identity Allow Null Default
Name Value
ID Int 4 yes No No

Cust_name nvarchar 50 No No No

Cust_phone Int 15 No No 0

Reference Abbreviati Actual data Rational


on
Example: Create Table (Invoices)
CREATE TABLE Invoices

(InvoiceID INT NOT NULL IDENTITY PRIMARY KEY,

VendorID INT NOT NULL

REFERENCES Vendors (VendorID),

InvoiceNumber VARCHAR(50) NOT NULL,

InvoiceDate SMALLDATETIME NOT NULL,

InvoiceTotal MONEY NOT NULL,

PaymentTotal MONEY NOT NULL DEFAULT 0,

CreditTotal MONEY NOT NULL DEFAULT 0,

TermsID INT NOT NULL

REFERENCES Terms (TermsID),

InvoiceDueDate SMALLDATETIME NOT NULL,


Example: Create Table (Student)
CREATE TABLE Student

(StID Char(5) NOT NULL PRIMARY KEY

Check (StID Like (‘S [0-9] [0-9] [0-9]’)),

/* Input Mask (controlled data input)*/

StName Char(50) NOT NULL,

StAddress NVARCHAR(50) NOT NULL,

StPhone NVARCHAR(20),

StProgName NVARCHAR(10) NOT NULL,

StCurntSems Smallint DEFAULT 1,

CGPA REAL)
Example: Create Table (Semester)
CREATE TABLE Semester

(SemName Char(10) NOT NULL PRIMARY KEY

StrDate Smalldatetime NOT NULL,

EndDate Smalldatetime NOT NULL,

Constraint Chk_Dt_val check (Datediff(week,


StrDate, EndDate) betwee 14 and 19))
Alter Table command
 ALTER TABLE table

{[ALTER COLMN colmn_name

{new_data_type [( precision ] , Scale])]

[NULL | NOT NULL]

| ADD

{[<column_definition >]

| column_name AS
computed_column_expression

}[ ,…n]
Alter Table command
| DROP

{[CONSTRAIN] constraint_name

|COLUMN column} [,…n]

|{CHECK | NOCHECK} CONSTRAINT

{ALL | constraint_name [,….n]}

}
Alter Table command
e.g., ALTER TABLE Student

Add constraint fk_st_pr

Foreign key (prName) References

program (prName)

e.g., ALTER TABLE Program

Add constraint chk_totsem

CHECK (totsem < 9)


Alter Table command
A statement that adds a new column

ALTER TABLE Invoices

ADD BalanceDue MONEY NOT NULL

A statement that DROPS a column

ALTER TABLE Invoices

DROP COLUMN BalanceDue

A statement that CREATES an index column

CREATE INDEX IX_Invoices_VendorID

ON Invoices (VendorID)
Removing rows and/or table
TRUNCATE table table_name

/*this command will remove all the rows of a table.


However the structure of the table will remain there.*/

e.g., TRUNCATE TABLE Class

/*DELETE can also be used to remove one or more rows at a


time*/

e.g., DELETE FROM Table_name

DELETE * FROM Table_name

DELETE from table_name WHERE condition

/* this command will delete the structure of the table along


with all the records*/

e.g., DROP TABLE Class


SQL as Data Manipulation Language
(DML)
Insert into Table command

A statement that enter values in a table

- give values within quote if not integer

- Order of the column values does matter

- Values of some (not null) attributes can be skipped. In


this particular case you will have to give the list of columns
those are required to be filled in.
Insert into Table command (DML)
A statement that enter values in a table

Syntax: INSERT INTO Table_name

{ [(column_list)

{VALUES

({DEFAULT | NULL |EXPRESSION} [,…n])

| DEFAULT VALUES

Note: Put text values in single quotes and numeric values


without quotes
Insert into Table command (DML)
A statement that enter values in a table

INSERT INTO Table

Values (col1 value, col2 value, … )

e.g., INSERT INTO Course

Values (‘COMP213’, ‘DBS’, 3, ‘CS’)

e.g., INSERT INTO Course (crCode, crName)

Values (‘COMP213’, ‘DBS’)


Query a Table command (DML)
A statement that query a database | a table

‘SELECT’ statement

- This is the maximum used command in DML

- Used to select certain ROWS as-well-as COLUMNS

- Used for different forms of products, that is different joins


The ‘SELECT’ command (DML)
Selecting ROWS from one or more tables

SELECT {* | column_name [,…n]}

FROM table-name

e.g., Query: Get the data of all the students

SELECT *

FROM student;
The ‘SELECT’ command (DML)
Selecting certain COLUMNS from a table (PROJECTION)

e.g., Query: Give the names of the students with their


program names

SELECT stName, prName

FROM student;
The ‘SELECT’ command (DML)
Selecting certain COLUMNS from a table using alias

SELECT {* | column_name [[AS] Alias [,…n]}

FROM table-name

e.g., Query: Give the names of the students with their


program names

SELECT stName, prName AS Program_Name

FROM student;
The ‘SELECT’ command (DML)
Adding the amounts of two columns or concatenating with
“+”

SELECT mTerm+ sMrks + fMrks

From Enroll

Select ‘distinct’ for avoid repetition and getting distinct


values against an attribute

SELECT DISTINCT prname

FROM Student
The SQL COUNT(), AVG() and
SUM() Functions
The COUNT() function returns the number of rows that matches
a specified criteria.

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

The AVG() function returns the average value of a numeric


column.

SELECT AVG(column_name)
FROM table_name
WHERE condition;

The SUM() function returns the total sum of a numeric column.

SELECT SUM(column_name)
FROM table_name WHERE condition;
Questions?

Das könnte Ihnen auch gefallen