Вы находитесь на странице: 1из 15

1

Database Management System (DBMS)

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.

Relational Database Management System (RDBMS)

A Relational Database Management System (RDBMS) is a Database Management System (DBMS)


where the database is organized and accessed according to the relationships between data. RDBMS is
the basis for SQL, and for all modern database systems like Oracle, SQL Server, IBM DB2, Sybase,
MySQL, and Microsoft Access.

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

Data Definition Language (DDL)

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:

• CREATE TABLE - creates a new database table


• ALTER TABLE - alters (changes) a database table
• TRUNCATE TABLE – deletes all the records of a database table
• DROP TABLE - deletes a database table
• CREATE INDEX - creates an index (search key)
2

• DROP INDEX - deletes an index

Data Manipulation Language (DML)

The update commands used to manipulate a table together form the Data Manipulation Language (DML):

• UPDATE - updates data in a database table


• DELETE - deletes data from a database table
• INSERT INTO - inserts new data into a database table

Transaction Controls

Transactions, if available, can be used to wrap around the DML operations:

• 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.

Data Retrieval Language (DRL)

The command used to retrieve records from a table is:

• SELECT * FROM tablename

Data Control Language (DCL)

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:

• GRANT authorizes one or more users to perform an operation or a set of operations on an


object.
• REVOKE removes or restricts the capability of a user to perform an operation or a set of
operations.

The End of a Statement

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.

Here is an example of a line of comment:

/* First find out if the database we want to create exists already */

A comment can also be spread on more than one line, like a paragraph. Here is an example:

/* First find out if the MotorVehicleDivision database we


want to create exists already.
If that database exists, we don't want it anymore. So,
delete it from the system. */

Transact-SQL also supports the double-dash comment. This comment applies to only one line of text.

-- Now that the database is not in the system, create it

PRINT

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:

DECLARE @VariableName DataType;

You can also declare more than one variable. To do that, separate them with a comma. The formula would
be:

DECLARE @Variable1 DataType1, @Variable2 DataType2, @Variable_n DataType_n;

In Transact-SQL, the name of a variable starts with the @ sign.

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.

The formula used is:

SELECT @VariableName = DesiredValue

Or

SET @VariableName = DesiredValue

Here is an example:

DECLARE @Category int


SET @Category = 208
PRINT @Category
GO

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

To support the null value, Transact-SQL provides a constant named NULL.

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

Special SQL Server Operators are:

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.

The syntax of the CONVERT() function is:

CONVERT(DataType [(length)], Expression [, style])


The first argument must be a known data type. If you are converting the value into a string (varchar,
nvarchar, char, and nchar) or a binary type, you should specify the number of allowed characters the data
types own parentheses. As reviewed for the CAST() function, the Expression is the value that needs to be
converted.

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:

char CHAR(int value)

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

varchar LEFT(String, NumberOfCharacters)

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:

varchar RIGHT(String, NumberOfCharacters)

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:

varchar REPLACE(String, FindString, ReplaceWith)

or

binary REPLACE(String, FindString, ReplaceWith)

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:

varchar SUBSTRING(String, Start Index, NumberOfCharacters)

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.

Measure Based Functions

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)

Date Time Functions

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

Transact-SQL provides the DATEADD() function. Its syntax is:

DATEADD(TypeOfValue, ValueToAdd, DateOrTimeReferenced)

DATEDIFF

Transact-SQL provides the DATEDIFF() function. Its syntax is:

DATEDIFF(TypeOfValue, StartDate, EndDate)

DATEPART

Transact-SQL provides the DATEPART() function. Its syntax is:

DATEPART(TypeOfValue, DateReferenced)

TypeOfValue will be day or month or year

Creating a Database

The command used to create a database in SQL uses the following formula:

CREATE DATABASE DatabaseName

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

CREATE DATABASE DatabaseName;

Here is an example:

CREATE DATABASE GeneralCensus;

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:

DROP DATABASE DatabaseName;


11

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.

The Current Database

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

The syntax to create a table is:

CREATE TABLE TableName(Columnname datatype(size));

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:

sp_rename ExistingTableName, TableNewName;

Deleting a Table

To delete a table using SQL, use the following formula:

DROP TABLE TableName

Removing all the records of a Table

To delete all the records of a table using SQL, use the following formula:

TRUNCATE TABLE TableName

Modifying a Table

Adding a new column

In SQL, the basic formula to add a new column to an existing table is:

ALTER TABLE TableName


ADD ColumnName Properties

Deleting a new column

To delete a column using code use the following formula:

ALTER TABLE TableName


DROP COLUMN ColumnName

Modifying a new column

In SQL, to change the data type or properties of a column,

ALTER TABLE TableName


ALTER COLUMN ColumnName Properties
12

Renaming a column

In SQL, to change the name of a column,

sp_rename 'TableName.ColumnName', 'NewColumnName', 'COLUMN'

Inserting a record into a table

In the SQL, data entry is performed using the INSERT combined with the VALUES keywords. The
INSERT statement uses the following syntax:

INSERT INTO TableName(Column1, Column2, Column_n) VALUES(Value1, Value2, Value_n);

Updating records of a table

Updating a record consists of changing its value for a particular column. To update a record using SQL:

UPDATE TableName
SET ColumnName = Expression

Removing records of a table

To delete a record using SQL:

DELETE FROM TableName


WHERE Condition(s)
Retrieving records of a table

The command used to retrieve records from a table is:

SELECT * FROM tablename

ORDER BY clause

In SQL, to specify the sorting order, use the ORDER BY expression. The syntax used would be:

SELECT * FROM tablename ORDER BY columnname [ASC | DESC];

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:

SELECT * FROM tablename WHERE Expression;

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:

ColumnName operator Value

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

ABS(x) returns the absolute value of x


13

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

MIN returns the smallest value in a given column


MAX returns the largest value in a given column
SUM returns the sum of the numeric values in a given column
AVG returns the average value of a given column
COUNT returns the total number of values in a given column
COUNT(*) returns the number of rows in a table

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

DELETE FROM DELETE FROM table_name


(Note: Deletes the entire table!!)

or

DELETE FROM table_name


WHERE condition
DROP DATABASE DROP DATABASE database_name
DROP INDEX DROP INDEX table_name.index_name
DROP TABLE DROP TABLE table_name
GROUP BY SELECT column_name1,SUM(column_name2)
FROM table_name
GROUP BY column_name1
HAVING SELECT column_name1,SUM(column_name2)
FROM table_name
GROUP BY column_name1
HAVING SUM(column_name2) condition value
IN SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
INSERT INTO INSERT INTO table_name
VALUES (value1, value2,....)

or

INSERT INTO table_name


(column_name1, column_name2,...)
VALUES (value1, value2,....)
LIKE SELECT column_name(s)
FROM table_name
WHERE column_name
LIKE pattern
ORDER BY SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]
SELECT SELECT column_name(s)
FROM table_name
SELECT * SELECT *
FROM table_name
SELECT DISTINCT SELECT DISTINCT column_name(s)
FROM table_name
SELECT INTO SELECT *
(used to create backup copies of INTO new_table_name
tables) FROM original_table_name

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

Вам также может понравиться