Академический Документы
Профессиональный Документы
Культура Документы
A Database Management System (DBMS) is a computer program that can access data in a database.
The DBMS program enables you to extract, modify, or store information in a database. Different DBMS
programs provide different functions for querying data, reporting data, and modifying data.
Table
The foundation of every Relational Database Management System is a database object called table.
Every database consists of one or more tables, which store the database’s data/information. Each table
has its own unique name and consists of columns and rows.
Columns
The database table columns (called also table fields) have their own unique names and have a pre-
defined data types. Table columns can have various attributes defining the column functionality (the
column is a primary key, there is an index defined on the column, the column has certain default value,
etc.).
Rows
While table columns describe the data types, the table rows contain the actual data for the columns.
Primary key
A primary key is a column or set of columns that uniquely identifies the rest of the data in any given row.
Foreign key
A foreign key is a column in a table where that column is a primary key of another table, which means that
any data in a foreign key column must have corresponding data in the other table where that column is
the primary key.
SQL
SQL stands for Structured Query Language. SQL allows you to access a database. SQL is an ANSI
standard computer language
The Data Definition Language (DDL) part of SQL permits database tables to be created or deleted. We
can also define indexes (keys), specify links between tables, and impose constraints between database
tables. The most important DDL statements in SQL are:
The update commands used to manipulate a table together form the Data Manipulation Language (DML):
Transaction Controls
• BEGIN TRANSACTION can be used to mark the start of a database transaction, which either
completes completely or not at all.
• COMMIT causes all data changes in a transaction to be made permanent.
• ROLLBACK causes all data changes since the last COMMIT or ROLLBACK to be discarded, so
that the state of the data is "rolled back" to the way it was prior to those changes being
requested.
COMMIT and ROLLBACK interact with areas such as transaction control and locking. Strictly, both
terminate any open transaction and release any locks held on data. In the absence of a BEGIN WORK or
similar statement, the semantics of SQL are implementation-dependent.
DCL handles the authorization aspects of data and permits the user to control who has access to see or
manipulate data within the database. Its two main keywords are:
In SQL, after writing a statement, you can end it with a semi-colon. In fact, if you plan to use many
statements in one block, you should end each with a semi-colon. When many statements are used, some
of them must come after others.
To separate statements, that is, to indicate when a statement ends, you can use the GO keyword (in
reality and based on SQL standards, it is the semi-colon that would be required, but the Microsoft SQL
Server interpreter accepts GO as the end of a statement).
Comment
3
A comment is text that the SQL interpreter would not consider as code.
A comment can also be spread on more than one line, like a paragraph. Here is an example:
Transact-SQL also supports the double-dash comment. This comment applies to only one line of text.
PRINT is mostly used for testing a simple value, a string, or an expression. Therefore, it displays its
results in a regular white window under a tab labeled Messages. PRINT can be used with only one
value
To display something in plain text as a result of a statement, type PRINT followed by what to display.
Therefore, PRINT uses the following formula:
PRINT WhatToPrint
Here is an example
PRINT 1234;
PRINT ‘create exists already’;
SELECT
SELECT is the most regularly used SQL operator. We will see that it is used to retrieve records from a
table. For this reason, SELECT displays its results in an organized window made of categories called
columns, under a tab labeled Results. SELECT can be used with more than one value
SELECT ‘create exists already’, 1234;
SELECT 24.85 AS HourlySalary;
If you want to display a regular constant number, simply type it. If you want to display a character, a word, or
a sentence, include it between single-quotes. If you want to include a single-quote in your statement, double
it; that is, write it twice.
Declaring Variables
To declare a variable, use the DECLARE keyword using the following formula:
You can also declare more than one variable. To do that, separate them with a comma. The formula would
be:
Initializing Variables
4
After declaring a variable, the variable is null. You can change this is to give a value to the variable. This is
referred to as initializing the variable.
Or
Here is an example:
Conditional Statements
Expressions usually start with a keyword, followed by the expression itself. After the expression, you can
tell the interpreter what to do. The statement may appear as follows:
Keyword Expression
Statement
BEGIN…END
In most cases, you will need more than one line of code to specify the Statement. To indicate that your
Statement covers more than one line, start it with the BEGIN keyword. Then you must use the END
keyword to indicate where the Statement ends. In this case, the formula of a conditional statement would
appear as follows:
Keyword Expression
BEGIN
Statement Line 1
Statement Line 2
Statement Line n
END
IF
Probably the primary comparison you can perform on a statement is to find out whether it is true. This
operation is performed using an IF statement in Transact-SQL. Its basic formula is:
IF Condition
Statement
IF…ELSE
The IF condition we used above is appropriate when you only need to know if an expression is true. In
case the expression to examine produces a false result and there is something to do. Its basic formula is:
IF Condition
Statement
ELSE
Statement
CASE…WHEN…THEN...ELSE
5
The CASE keyword is used as a conditional operator that considers a value, examines it, and acts on an
option depending on the value. ELSE is optional. The formula of the CASE statement is:
CASE Expression
WHEN Value1 THEN Result
WHEN Value2 THEN Result
WHEN Value_n THEN Result
ELSE Alternative
END
WHILE
To examine a condition and evaluate it before taking action, you can use the WHILE operator. The basic
formula of this statement is:
WHILE Expression
Statement
NULL Constant
After you have declared a variable, the SQL interpreter reserves a space in the computer memory for it
but doesn't put anything in that memory space. At that time, that area of memory doesn't hold a significant
value. Also at that time, the variable is considered null.
When a variable is said to hold a null value, it doesn't mean its value is 0. It doesn't even mean that the
variable's memory space is empty. It actually means that we cannot clearly determine the current value
that the variable is holding.
Operators
+ Addition
- Subtraction
* Multiplication
\ Division
% Modulo
& Bit wise AND
| Bit wise OR
^ Bit wise XOR
= Equality
!= or <> Not Equal
< Less Than
<= Less Than or Equal To
> Greater Than
>= Greater Than or Equal To
IN
LIKE
BETWEEN
IS Operator
To validate something as being possible, you can use the IS operator. For example, to acknowledge that
something is NULL, you can use the IS NULL expression
Built In Functions
CAST
6
Casting a value is converting from a string to expected type. The syntax of the CAST() function is:
CAST(Expression AS DataType)
The Expression is the value that needs to be cast. The DataType factor is the type of value you want to
convert the Expression to.
CONVERT
Like CAST(), the CONVERT() function is used to convert a value. Unlike CAST(), CONVERT can be used
to convert a value its original type into a non-similar type. For example, you can use CONVERT to cast a
number into a string and vice-versa.
String Functions
LEN
The number of characters of a string is also called the length of the string. To get the length of a string,
you can use the LEN() function. Its syntax is:
int LEN(String)
ASCII
int ASCII(String)
This function takes as argument as string and returns the ASCII code of the first (the left) character of the
string.
CHAR
If you have the ASCII code of a character and want to find its actual character, you can use the CHAR()
function. Its syntax is:
LOWER
If you want to convert all characters of a string to lowercase, you can use the LOWER() function. Its
syntax is:
varchar LOWER(String)
UPPER
If you want to convert all characters of a string to uppercase, you can use the UPPER() function. Its
syntax is:
varchar UPPER(String)
LEFT
A left sub-string is one or a group of characters retrieved from the left side of a known string. To get the
left sub-string of a string, you can use the LEFT() function. Its syntax is:
7
This function takes two arguments. The first argument specifies the original string. The second argument
specifies the number of characters from the most-left that will constitute the sub-string. After the operation,
the LEFT() function returns a new string made of the left character + the NumberOfCharacters on its right
from the String.
RIGHT
Instead of the starting characters of a string, you may want to create a string using the most-right
characters of an existing string. To support this operation, Transact-SQL provides the RIGHT() function.
Its syntax is:
This function takes two arguments. The first argument specifies the original string. The second argument
specifies the number of characters from the most-right that will constitute the sub-string.
REPLACE
To replace one character or a sub-string from a string, you can use the REPLACE() function. Its syntax is:
or
This function takes three arguments. The first is the string that will be used as reference. The second
argument, FindString, is a character or a sub-string to look for in the String argument. If the FindString
character or sub-string is found in the String, then it is replaced with the value of the last argument,
ReplaceWith.
SUBSTRING
A sub-string is one or a group of characters retrieved from of a known string. To get thes ub-string of a
string, you can use the SUBSTRING() function. Its syntax is:
This function takes three arguments. The first argument specifies the original string. The second argument
specifies the start index of characters that will constitute the sub-string. . The third argument specifies the
number of characters from the start index that will constitute the sub-string.
Arithmetic Functions
SIGN
To find out if a value is positive, null, or negative, Transact-SQL provides the SIGN() function. Its syntax is:
SIGN(Expression)
This function takes as argument a number or an expression that can be evaluated to a number. The
interpreter would then examine the number. If the Expression is positive, the function returns 1. If the
Expression is null, the function returns 0. If the Expression is negative, the function returns -1.
ABS
To get the absolute value of a number, you can use the ABS() function. Its syntax is:
ABS(Expression)
This function takes an expression or a number as argument and returns its absolute value.
8
CEILING
The ceiling of a number is the closest integer that is greater than or higher than the number considered.
To get the ceiling of a number, Transact-SQL provides the CEILING() function. Its syntax is:
CEILING(Expression)
This function takes as argument a number or an expression that can evaluate to a number. After the
conversion, if the function succeeds, it returns a double-precision number that is greater than or equal to
Expression.
FLOOR
The lowest but closest integer value of a number is referred to as its floor. To support finding the floor of a
number, Transact-SQL provides the FLOOR() function. Its syntax is:
FLOOR(Expression)
The FLOOR() function takes as argument a numeric value or an expression that can be evaluated to a
number. If the function succeeds during its conversion, it produces the integer that is the floor of the
argument.
EXP
To calculate the exponential value of a number, Transact-SQL provides the EXP() function. Its syntax is:
EXPExpression)
This function takes one argument as a number or an expression that can be evaluated to a number.
POWER
The power of a number is the value of that number when raised to another number. This is done using the
following formula:
ReturnValue = xy
To support finding the power of a number, Transact-SQL provides the POWER() function. Its syntax is:
POWER(x, y)
This function takes two required arguments. The first argument, x, is used as the base number to be
evaluated. The second argument, y, also called the exponent, will raise x to this value.
LOG
To assist with finding the natural logarithm of a number, Transact-SQL provides the LOG() function. Its
syntax is:
LOG(Expression)
This function takes one argument as a number or an expression that can evaluate to a number. After the
calculation, it returns the natural logarithm of the argument.
LOG10
To calculate the base 10 logarithm of a number, Transact-SQL provides the LOG10() function. Its syntax
is:
LOG10(Expression)
The number to be evaluated is passed as the argument X. The function returns the logarithm on base 10
using the formula:
9
y = log10x
which is equivalent to
x = 10y
SQRT
To support the calculation of a square root, Transact-SQL provides the SQRT() function. Its syntax is:
SQRT(Expression)
This function takes one argument as a positive decimal number. If the number is positive, after the
calculation, the function returns the square root of x.
PI
To get the value of PI, Transact-SQL provides the PI() function. Its syntax is simply:
PI()
RADIANS
If you know the value of an angle in degrees and you want to get the radians, Transact-SQL provides the
RADIANS() function. Its syntax is:
RADIANS(Expression)
This function takes as argument a value in degrees. If it succeeds in its calculation, it returns the radians
value.
DEGREES
If you know the radians but want to get the degrees of an angle, you can use the DEGREES() function. Its
syntax is:
DEGREES(Expression)
This function takes as argument a value in radians. If it succeeds, it returns the equivalent value in
degrees.
Trigonometric Functions
COS
To get the cosine of an angle, you can call the COS() function. Its syntax is:
COS(Expression)
The angle to be considered is passed as the argument to this function. The function then calculates and
returns its cosine.
SIN
To get the sine of an angle, you can use the SIN() function whose syntax is:
SIN(Expression)
The angle to be considered is passed as the argument. After its calculation, the function returns the sine
of the angle between –1 and 1.
10
TAN
To get the tangent of an angle, you can use the TAN() function of Transact-SQL. Its syntax is:
TAN(Expression)
GETDATE
To get the current date and the current time of the computer that a user is using, you can use the
GETDATE() function of Transact-SQL. Its syntax is:
GETDATE()
This function simply returns the current date and time of the operating system.
DATEADD
DATEDIFF
DATEPART
DATEPART(TypeOfValue, DateReferenced)
Creating a Database
The command used to create a database in SQL uses the following formula:
The CREATE DATABASE (remember that SQL is not case-sensitive) expression is required. The
DatabaseName factor is the name that the new database will carry. Although SQL is not case-sensitive,
you should make it a habit to be aware of the cases you use to name your objects. Every statement in
SQL can be terminated with a semi-colon. Although this is a requirement in many implementations of
SQL, in Microsoft SQL Server, you can omit the semi-colon. Otherwise, the above formula would be
Here is an example:
Deleting a Database
To delete a database in SQL Query Analyzer, you use the DROP DATABASE expression followed by the
name of the database. The formula used is:
Before deleting a database in SQL, you must make sure the database is not being used or accessed by
some one else or by another object.
While writing code in a Query Window, you should always know what database you are working on;
otherwise you may add code to the wrong database. To programmatically specify the current database,
type the USE keyword followed by the name of the database. The formula to use is:
USE DatabaseName;
Here is an example:
USE GovernmentStatistics;
Creating a Table
Renaming a Table
To change the name of a table with code, execute sp_rename, followed by the current name of the table,
a comma, and the new desired name of the table. The formula to use is:
Deleting a Table
To delete all the records of a table using SQL, use the following formula:
Modifying a Table
In SQL, the basic formula to add a new column to an existing table is:
Renaming a column
In the SQL, data entry is performed using the INSERT combined with the VALUES keywords. The
INSERT statement uses the following syntax:
Updating a record consists of changing its value for a particular column. To update a record using SQL:
UPDATE TableName
SET ColumnName = Expression
ORDER BY clause
In SQL, to specify the sorting order, use the ORDER BY expression. The syntax used would be:
The ascending order is controlled using the ASC keyword and descending order by DESC.
WHERE clause
If you are writing your SELECT statement, to formulate a condition, you use the WHERE keyword with a
basic formula as follows:
The expressions used in conditions are built using algebraic, logical, and string operators. The
Expression factor is called a criterion. The expression is written using the formula:
The ColumnName factor must be an existing column of a table. It is followed by the assignment operator.
The Value factor is the value that would set the condition.
Arithmetic Functions
SIGN(x) returns the sign of input x as -1, 0, or 1 (negative, zero, or positive respectively)
MOD(x,y) modulo - returns the integer remainder of x divided by y (same as x%y)
FLOOR(x) returns the largest integer value that is less than or equal to x
CEILING(x) or CEIL(x) returns the smallest integer value that is greater than or equal to x
POWER(x,y) returns the value of x raised to the power of y
ROUND(x) returns the value of x rounded to the nearest whole integer
returns the value of x rounded to the number of decimal places specified by the
ROUND(x,d)
value d
SQRT(x) returns the square-root value of x
Aggregate Functions
SQL Syntax
Statement Syntax
AND / OR SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition
ALTER TABLE (add column) ALTER TABLE table_name
ADD column_name datatype
ALTER TABLE (drop column) ALTER TABLE table_name
DROP COLUMN column_name
AS (alias for column) SELECT column_name AS column_alias
FROM table_name
AS (alias for table) SELECT column_name
FROM table_name AS table_alias
BETWEEN SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE CREATE DATABASE database_name
CREATE INDEX CREATE INDEX index_name
ON table_name (column_name)
CREATE TABLE CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
.......
)
CREATE UNIQUE INDEX CREATE UNIQUE INDEX index_name
ON table_name (column_name)
CREATE VIEW CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
14
or
or
or
SELECT column_name(s)
INTO new_table_name
FROM original_table_name
TRUNCATE TABLE TRUNCATE TABLE table_name
(deletes only the data inside the
table)
UPDATE UPDATE table_name
SET column_name=new_value
15
[, column_name=new_value]
WHERE column_name=some_value
WHERE SELECT column_name(s)
FROM table_name
WHERE condition