Vous êtes sur la page 1sur 9

Some Conventions for Writing SQL Statements

• Use uppercase letters for the keywords, which inclues SELECT, FROM, and
WHERE. Use lowercase letters for the user-supplied words (SQL Server 2005 is
not case-sensitive for commands).
• Align the keywords SELECT, FROM, and WHERE on separate lines

Null means that data is missing or unavailable, so the cell has no value.

Ascending and Descending Order

In SQL Server, the default order of an ORDER BY is ascending. To display or order


output in descending order, the keyword DESC has to be appended to the ORDER BY
clause. And, in order to display or order output in ascending order, the keyword ASC
can be appended to the ORDER BY clause.

Filtering with WHERE

The WHERE clause can be used with several comparison operators:

• > (greater than)


• <> not equal
• = equal
• >= greater than or equal to
• <= less than or equal to

The AND Operator

The AND is a way of combining conditions in a WHERE clause. An AND operator is used
in a WHERE clause if more that one condition is required.

The BETWEEN Operator

the BETWEEN operator allows you to determine whether a value falls within a given
range of values (inclusive).

SELECT dname, age


FROM Dependent
WHERE age
BETWEEN 3 AND 5

Negating the BETWEEN Operator

The BETWEEN operator can be negated by using the keyword NOT before the BETWEEN
operator.
IS NULL

Null values are used to designate missing data in columns. The IS NULL condition is
the only condition that directly tests for nulls. No value is considered to be equal to,
greater than, or less than NULL. Even a space is not considered to be a NULL, and a null
is not considered to be a space. Nulls are not considered like any other value in a table
either, since nulls do not have data types.

SELECT dname, age


FROM Dependent
WHERE age IS NULL

IS NOT NULL

To retrieve all rows that are not nulls, IS NOT NULL can be used.

The ROWCOUNT Function

For example, to see the first 10 rows of the Dependent table, you can type:

SET ROWCOUNT 10
SELECT *
FROM Dependent

After using ROWCOUNT, you should reset the ROWCOUNT property by:

SET ROWCOUNT 0

If you do not reset the ROWCOUNT property, you will keep getting whatever you set
your ROWCOUNT to for the remainder of this session

Using Aliases

Column aliases and table aliases are temporary names assigned within a query to
columns and tables respectively. They are created on the fly in a query, and do not
exist after the query is run.

To use more descriptive column headings, you can include column aliases just
before or after the column name by using AS in the SELECT statement

SELECT dname AS Dependent_name, age AS Dependent_age, sex AS


Dependent_sex
FROM Dependent
WHERE age > 5

Synonyms
Table aliases are not permanent, in the sense that they do not exist after the query
has been executed. Synonyms are more permanent; they are available for use until
they are deleted.

SQL Server 2005 allows you to create synonyms for your tables. Synonyms are
usually shorter names that can be used in place of the table name.

The general syntax to create a synonym is:

CREATE SYNONYM synonym_name


FOR Table_name

So, if you want to delete the synonym s1, type:

DROP SYNONYM s1

You can also delete the synonym by right-clickingon the synonym and selecting
Delete.

Adding Comments to SQL Statements

Comments are nonexecutable words or phrases included in SQL queries to make the
queries easier to understand (particularly by other people).

There are two ways of including comments in SQL Server 2005. The first way is
by the use of dashes,

SELECT * -- displays "all" attributes

The second way of including comments in Server SQL 2005 is by the use of
/*...*/ construction.

SELECT dname, age /* displays the dependent name and age */

Creating a Table

the CREATE TABLE command is used to create a table

CREATE TABLE Tablename


(column_name type, column_name, type, .....)
CREATE TABLE Employee (names VARCHAR(20),
address VARCHAR(20),
employee_number INT)

Inserting Values into a Table

There are several ways to insert values into a table using SQL in SQL Server 2005.
We will illustrate the two most commonly used ways: using INSERT INTO ..
VALUES and using INSERT INTO .. SELECT.
You may INSERT a row with less than all the columns by naming the columns you
want to insert into, like this:

INSERT INTO Employee (names, address)


VALUES ('Joe Smith', '123 4th St.')

Using INSERT INTO .. SELECT

With the INSERT INTO .. VALUES option, you insert only one row at a time into a
table. With the INSERT INTO .. SELECT option, you may (and usually do) insert
many rows into a table at one time.

INSERT INTO Emp1(addr, sal, empno)


SELECT address, salary, employee_number
FROM Employee

The UPDATE Command

Another common command used for setting/changing data values in a table is the The
general format for the UPDATE command is:

UPDATE TableName
SET fieldname...

The ALTER TABLE Command

Adding a Column to a Table

You may add columns to a table with little difficulty. The general syntax for adding a
column to a table is:

ALTER TABLE
Tablename
ADD column-name type

. Changing a Column's Data Type in a Table

ALTER TABLE Tablename


ALTER COLUMN column-name new_type

Deleting a Column from a Table

The following is the general syntax for deleting a column from a table:

ALTER TABLE Tablename


DROP column column-name

Deleting a Table

The general syntax to delete or remove an entire table and its contents is:
DROP TABLE Tablename

Column Types in Joins

Joins have to be performed on "compatible" columns; that is, a character column may
be joined to another character column, a numeric column may be joined to another
numeric column, and so forth. So, for example, a CHAR column can be joined to a
VARCHAR column (both being character columns), or an INT column can be joined to a
REAL column (both being numeric columns).

The Cartesian Product

In a SQL statement, a Cartesian product is where every row of the first table in the
FROM clause is joined with each and every row of the second table in the FROM clause.

CROSS JOIN Used to Generate a Cartesian Product

In SQL Server, a CROSS JOIN can be used to return a Cartesian product of two tables.
The form of the CROSS JOIN is:

SELECT *
FROM Table1 CROSS JOIN Table2

In SQL Server 2000 we have three types of joins


1. Inner join
2. Outer Join
3. Cross Join
1. Inner Join: Inner Join is the default type of join, it will producesses the result set,
which contains matched rows only.
syntax: select * from table1<innerjoin>table2

2. Outer Join: Outer join produces the results, which contains matched rows and
unmatched rows.
here we have three types of joins,
1.Left Outer Join 2.Right Outer Join 3.Full Outer Join
Left Outer Join: Left Outer Join producesses the results,
which contains all the rows from Left table and matched
rows from Right Table.
syntax: select * from table1<leftouterjoin>table2

Right Outer Join: Right Outer Join producesses the


resultset, which contains all the rows from right table and
matched rows from left table.
syntax:select * from table1<right outer join>table2
Full Outer Join: Full Outer Join producesses the resultset,
which contains all the rows from left table and all the
rows from right table.
syntax:select * from table1<fullouterjoin>table2

3.Cross Join: A join without having any condition is known


as Cross Join, in cross join every row in first table is
joins with every row in second table.
syntax: select * from table1<cross join>table2

Self Join: A join joins withitself is called self join


working with self joins we use Alias tables.

Join Types:
1. INNER JOIN - Joins two tables and returns only those records that match
between the 2 tables.
2. LEFT OUTER JOIN - Joins two tables and returns all records from the first table
with or without matching records on the second table.
3. RIGHT OUTER JOIN - Joins two tables and returns all records from
the second table with or without matching records on the first table.
FULL OUTER JOIN - Joins two tables and returns all records from both
tables even if there's no matching record between them.

CROSS JOIN
In cross joins, each row from first table joins with all the rows of another table.

Strings
A string is a character or a combination of characters.

Creating a Table With SQL


CREATE TABLE TableName

Temporary Tables
To create a temporary table, start its name with #,
followed by the desired name. Once the table has
been created, it would be available as long as you are
using the same connection to the server.

Deleting a Table
DROP TABLE TableName

Modifying a Column
ALTER TABLE TableName
ADD ColumnName Properties

Deleting a Column
ALTER TABLE TableName
DROP COLUMN ColumnName

DML

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store,

modify, delete, insert and update data in database.

Examples: SELECT, UPDATE, INSERT statements

DDL

DDL is abbreviation of Data Definition Language. It is used to create and modify the

structure of database objects in database.

Examples: CREATE, ALTER, DROP statements

DCL

DCL is abbreviation of Data Control Language. It is used to create roles, permissions,

and referential integrity as well it is used to control access to database by securing it.

Examples: GRANT, REVOKE statements

TCL

TCL is abbreviation of Transactional Control Language. It is used to manage different

transactions occurring within a database.

Examples: COMMIT, ROLLBACK statements


Functions: units of code that perform an action and return a value

Built in functions

User defined functions

Different categories

Scalar functions: operate on single value and return a single value

Types: date / time , string, mathematical, and security(info on users n roles)


functions e.g , len(), upper()

Aggregate functions: perform operations that combine multiple values into one
value e.g, count(), sum(),avg()

Rowset Function: return objects that can be placed of table

• Entities People, places, items, or concepts


• Attributes Properties of an entity
• Relationships Connections between entities

String Attributes

Users also need to store string attributes in the database.

To store such attributes, SQL Server 2005 provides four different datatypes: char,
nchar, varchar, and nvarchar.

String Datatype Terminology


Stringc Types Character Unicode
Fixed char nchar
Variable varchar nvarchar

The main advantage of character datatypes is efficiency. In general, character


datatypes are more efficient than unicode datatypes because most collations use one
byte per character, while their unicode counterpart uses two bytes per character.

Fixed and variable-length datatypes Another option to consider when using string
datatypes is whether to use fixed or variable-length datatypes. Fixed datatypes (char,
nchar) use a permanent amount of space regardless of the value of the column or
variable. For example, if you declare a column as type char(10) and it has the value of
“Test,” it will employ ten bytes, even though Test has only four letters. This occurs
because SQL Server 2005 will add six spaces after the word Test, thus always filling
in the ten characters. The same column defined as nchar(10) will employ twenty
bytes. This behavior is known as right padding.

In contrast, variable-length datatypes adjust their storage to accommodate the value


of the column, but require two additional bytes to control the length of the value.
Therefore, if you declare a column as type varchar(10) and a row has the value of
“Test,” it will employ six bytes to store the value, two bytes for length control, and
four bytes to store the actual value. The same column using nvarchar(10) will use ten
bytes (two for length, eight for the actual value), and SQL Server 2005 will not add
additional spaces.

Binary Data

Some applications need to store images (such as JPG, GIF, and BMP files) or
documents (such as Microsoft Excel workbooks or Microsoft Word documents). To
support those needs, SQL Server 2005 supports binary datatypes. Binary datatypes
are raw sequences of bytes that SQL Server 2005 does not try to encode or decode as
it does with string datatypes. Binary information can be stored in three datatypes:
binary(n), varbinary(n), and varbinary(max),