This document provides an overview of SQL and creating and managing databases and tables in SQL Server 2014. It defines SQL and some common SQL statements used to interact with databases. It then covers creating databases using CREATE DATABASE and creating tables using CREATE TABLE, specifying data types for columns. The document discusses data definition language (DDL) statements for creating, modifying and deleting databases and tables. It provides examples of creating tables with and without attributes like primary keys, foreign keys, check constraints and modifying and deleting tables.
2. What is SQL?
• SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL
is used to communicate with a database.
• According to ANSI, it is the standard language for relational database
management systems.
• SQL statements are used to perform tasks such as update data on a database,
or retrieve data from a database. Some common relational database
management systems that use SQL are: Oracle, Sybase, Microsoft SQL
Server, Access, etc.
• Although most database systems use SQL, most of them also have their own
additional proprietary extensions that are usually only used on their system.
• The standard SQL commands such as "Select", "Insert", "Update", "Delete",
"Create", and "Drop" can be used to accomplish almost everything that one
needs to do with a database.
• Main and Functional categories are DML, DDL, DCL.
Slide 2
3. Slide 3
The SQL statements for data definition
You use the data definition language (DDL) statements to
create, modify, and delete database objects such as the database
itself, the tables contained in a database, and the indexes for
those tables.
Typically, a database administrator is responsible for using the
DDL statements on production databases in a large database
system.
SQL programmers use these statements to create and work with
small databases for testing.
In SQL Server, you’ll use the Management Studio to generate
the DDL statements for you, although you can then verify or
correct them as needed.
4. Slide 4
DDL statements to create database and table
Statement Description
CREATE DATABASE Creates a new database.
CREATE TABLE Creates a new table in the current
database.
5. Slide 5
Some DDL statements to modify and delete
Statement Description
ALTER TABLE Modifies the structure of a table.
DROP DATABASE Deletes a database.
DROP TABLE Deletes a table.
6. Slide 6
The basic syntax of the CREATE DATABASE
statement
CREATE DATABASE database_name
How to create a database
The CREATE DATABASE statement creates a new, empty
database on the current server.
The new database is created using the default settings and the
database files are stored in the default directory on the hard drive.
One of the files SQL Server creates when it executes the CREATE
DATABASE statement is a log file. This file is used to record
modifications to the database.
SQL Server generates the name for the log file by appending
“_log” to the end of the database name.
7. To create a database
• Transact-SQL
CREATE DATABASE New_AP
Slide 7
8. To rename a database
• Transact-SQL
ALTER DATABASE New_AP
MODIFY NAME = New_AP1
Slide 8
9. To delete a database
• Transact-SQL
DROP DATABASE New_AP
Slide 9
11. The basic syntax of the CREATE TABLE
statement
Slide 11
CREATE TABLE table_name
(column_name_1 data_type [column_attributes]
[, column_name_2 data_type [column_attributes]]...
[, table_attributes])
How to create a table
The CREATE TABLE statement creates a table based on the
column definitions, column attributes, and table attributes you
specify.
A table can contain between one and 1024 columns.
Each column must have a unique name and must be assigned a
data type. In addition, you can assign one or more column
attributes to it.
You can also assign one or more constraints to a column or to the
entire table.
12. SQL Server 2012’s Commonly Used Data Types
• SQL data type is an attribute that specifies type of data of any
object. Each column and expression has related data type in
SQL.
• You would use these data types while creating your tables. You
would choose a particular data type for a table column based
on your requirement.
Slide 12
13. Numeric: Integer data types
Datatype Min Max Storage
Bigint -263 263-1 8 bytes
Int -2,147,483,648 2,147,483,647 4 bytes
Smallint -32,768 32,767 2 bytes
Tinyint 0 255 1 byte
Bit 0 1 1 byte
The integer data types are used to store whole numbers,
which are numbers without any digits to the right of the
decimal point.
Slide 13
14. Numeric: Decimal data types
Datatype Min Max Storage
Decimal[(p[,s])] -1038+1 1038–1 5 - 17 bytes
Numeric[(p[,s])] same as Decimal same as Decimal same as Decimal
Money -2^63 / 10000 2^63-1 / 10000 8 bytes
Smallmoney -214,748.3648 214,748.3647 4 bytes
The decimal data types are used to store decimal values, which can
include digits to the right of the decimal point. The precision of a
decimal value indicates the total number of digits that can be stored,
and the scale indicates the number of digits that can be stored to the
right of the decimal point.
Slide 14
15. String data types
Datatype Min Max Storage
Char 0 chars 8000 chars Defined width
Varchar 0 chars 8000 chars 2 bytes + number of chars
nchar 0 chars 4000 chars Defined width x 2
nvarchar 0 chars 4000 chars
• The string data types can be used to store standard characters that use a
single byte of storage or Unicode characters that use two bytes of storage.
• The char and nchar data types are typically used for fixed-length strings.
These data types use the same amount of storage regardless of the actual
length of the string.
• The varchar and nvarchar data types are typically used for variable-length
string. These data types use only the amount of storage needed for a given
string.
• Unless your system is used in a multi-language environment, you should use
the char and varchar data types rather than nchar and nvarchar data types.
Slide 15
16. Date and Time Data Types
Datatype Min Max Storage
Date 0001-01-01 9999-12-31 3 bytes
Time 00:00:00.0000000 23:59:59.9999999
Datetime 1753-01-01 00:00:00.000 9999-12-31 23:59:59.997 8 bytes
Smalldatetime 1900-01-01 00:00 2079-06-06 23:59
Common Date Formats
yyyy-mm-dd 2012-04-30
mm/dd/yyyy 4/30/2012
mm-dd-yy 4-30-12
Month dd, yyyy April 30, 2012
Mon dd, yy Apr 30, 12
dd Mon 12 30 Apr 12
Common Time Formats
hh:mi 16:20
hh:mi am/pm 4:20 pm
hh:mi:ss 4:20:36
Slide 16
17. Tables with and without attributes
Slide 17
Creating a table without column attributes
CREATE TABLE Vendors
(VendorID INT,
VendorName VARCHAR(50))
Creating a table with column attributes
CREATE TABLE Invoices
(InvoiceID INT PRIMARY KEY IDENTITY,
VendorID INT NOT NULL,
InvoiceDate SMALLDATETIME NULL,
InvoiceTotal MONEY NULL DEFAULT 0)
18. An introduction to constraints
Slide 18
Constraints are used to enforce the integrity of the data in a table by
defining rules about the values that can be stored in the columns of
the table.
Constraints can be used at the column level to restrict the value of a
single column or at the table level to restrict the value of one or
more columns.
You code a column-level constraint as part of the definition of the
column it constrains.
You code a table-level constraint as if it were a separate column
definition, and you name the columns it constrains within that
definition.
Constraints are tested before a new row is added to a table or an
existing row is updated. The operation succeeds only if the new or
modified row meets all of the constraints.
19. Column and table constraints
Slide 19
Constraint At the column level
NOT NULL Prevents null values from being stored in the
column.
PRIMARY KEY Requires that each row in the table have a
unique value in the column. Null values are
not allowed.
UNIQUE Requires that each row in the table have a
unique value in the column.
CHECK Limits the values for a column.
[FOREIGN KEY]
REFERENCES
Enforces referential integrity between a
column in the new table and a column in a
related table.
20. A statement that creates a table with a two-
column primary key constraint
Slide 20
CREATE TABLE InvoiceLineItems1
(InvoiceID INT NOT NULL,
InvoiceSequence SMALLINT NOT NULL,
InvoiceLineItemAmount MONEY NOT NULL,
PRIMARY KEY (InvoiceID, InvoiceSequence))
21. CHECK Constraint
Slide 21
The syntax of a check constraint
CHECK (condition)
How to use check constraints
Check constraints limit the values that can be stored in the columns
of a table.
The condition you specify for a check constraint is evaluated as a
Boolean expression. If the expression is true, the insert or update
operation proceeds. Otherwise, it fails.
A check constraint that’s coded at the column level can refer only
to that column.
A check constraint that’s coded at the table level can refer to any
column in the table.
22. CHECK Constraint at Column and Table levels
Slide 22
A statement that creates a table with two column-level check
constraints
CREATE TABLE Invoices1
(
InvoiceID INT IDENTITY PRIMARY KEY,
InvoiceTotal MONEY NOT NULL CHECK (InvoiceTotal >= 0),
PaymentTotal MONEY NOT NULL DEFAULT 0 CHECK (PaymentTotal >= 0)
)
The same statement with the check constraints coded at the
table level
CREATE TABLE Invoices2
(
InvoiceID INT NOT NULL IDENTITY PRIMARY KEY,
InvoiceTotal MONEY NOT NULL,
PaymentTotal MONEY NOT NULL DEFAULT 0,
CHECK ((InvoiceTotal >= 0) AND (PaymentTotal >= 0))
)
23. A table-level check constraint that
limits VendorID to a specific format
Slide 23
CREATE TABLE Vendors1
(
VendorID CHAR(6) NOT NULL PRIMARY KEY,
VendorName VARCHAR(50) NOT NULL,
CHECK (VendorID LIKE '[A-Z][A-Z][0-9][0-9][0-9][0-9]')
)
24. How to use foreign key constraints
Slide 24
You use the FOREIGN KEY clause to define a foreign key
constraint, also called a reference constraint.
A foreign key constraint defines the relationship between two
tables and enforces referential integrity.
If you code a foreign key constraint at the column level, you can
relate a single column in the new table to a single column in the
related table.
To define a relationship that consists of two or more columns, you
must define the constraint at the table level.
Typically, a foreign key constraint refers to the primary key of the
related table. However, it can also refer to a unique key.
25. Slide 25
The syntax of a column-level foreign key
constraint
[FOREIGN KEY] REFERENCES ref_table_name (ref_column_name)
The syntax of a table-level foreign key constraint
FOREIGN KEY (column_name_1 [, column_name_2]...)
REFERENCES ref_table_name (ref_column_name_1
[, ref_column_name_2]...)
26. A foreign key constraint at the column level
Slide 26
A statement that creates the primary key table
CREATE TABLE Vendors
(VendorID INT NOT NULL PRIMARY KEY,
VendorName VARCHAR(50) NOT NULL)
A statement that creates the foreign key table
CREATE TABLE Invoices
(InvoiceID INT NOT NULL PRIMARY KEY,
VendorID INT NOT NULL REFERENCES Vendors (VendorID),
InvoiceTotal MONEY NULL)
27. Multicolumn foreign key constraint at the table level
Slide 27
Create Table Products
(
productID int not null,
pNamevarchar(50) not null,
pDesc varchar(50) not null
primary key (productid, pname)
)
Create Table Sales
(
salesID int primary key identity,
productNo int ,
productName varchar(50) ,
quantity int,
Constraint FK_Product_Sales Foreign Key (productNo, productName)
References Products(productID, pName)
)
28. Delete and Alter a Table
To delete a table named Vendors
DROP TABLE Vendors
To alter a table
ALTER TABLE Vendors
ADD LastTranDate SMALLDATETIME NULL
To drop a column
ALTER TABLE Vendors
DROP COLUMN LastTranDate
To add new check constraint
ALTER TABLE Invoices WITH NOCHECK
ADD CHECK (InvoiceTotal >=1)
Add a foreign key constraint
ALTER TABLE InvoiceLineItems WITH CHECK
ADD FOREIGN KEY (AccountNo) REFERENCES GLAccounts(AccountNo)
To change a data type of a column
ALTER TABLE InvoiceLineItem
ALTER COLUMN InvoiceLineItemDescription VARCHAR(200)
Slide 28