Sie sind auf Seite 1von 137

SQL TUTORIAL

What is SQL?
SQL is Structured Query Language,
which is a computer language for
storing, manipulating and retrieving data
stored in relational database.
SQL is a language of database, it
includes database creation, deletion,
fetching rows and modifying rows etc.
SQL is an ANSI (American National
Standards Institute) standard but there
are many different versions of the SQL
language.
SQL is the standard language for Relation
Database System. All relational database
management systems like MySQL, MS Access,
Oracle, Sybase, Informix and SQL Server use
SQL as standard database language.
Also, they are using different dialects, such as:
• MS SQL Server using T-SQL,
• Oracle using PL/SQL,
• MS Access version of SQL is called JET SQL
(native format) etc.
Why SQL?
• Allows users to access data in relational
database management systems.
• Allows users to describe the data.
• Allows users to define the data in database and
manipulate that data.
• Allows to embed within other languages using
SQL modules, libraries & pre-compilers.
• Allows users to create and drop databases and
tables.
• Allows users to create view, stored procedure,
functions in a database.
• Allows users to set permissions on tables,
History:
• 1970 -- Dr. Edgar F. "Ted" Codd of IBM is known
as the father of relational databases. He
described a relational model for databases.
• 1974 -- Structured Query Language appeared.
• 1978 -- IBM worked to develop Codd's ideas and
released a product named System/R.
• 1986 -- IBM developed the first prototype of
relational database and standardized by ANSI.
The first relational database was released by
Relational Software and its later becoming
Oracle.
Codd’s 12 Rules
Dr Edgar F. Codd, after his extensive research on
the Relational Model of database systems, came
up with twelve rules of his own, which according
to him, a database must obey in order to be
regarded as a true relational database.
These rules can be applied on any database
system that manages stored data using only its
relational capabilities. This is a foundation rule,
which acts as a base for all the other rules.
Rule 1: Information Rule
The data stored in a database, may it be user
data or metadata, must be a value of some table
cell. Everything in a database must be stored in
a table format.
Rule 2: Guaranteed Access Rule
Every single data element (value) is guaranteed
to be accessible logically with a combination of
table-name, primary-key (row value), and
attribute-name (column value). No other means,
such as pointers, can be used to access data.
Rule 3: Systematic Treatment of NULL Values
The NULL values in a database must be given a
systematic and uniform treatment. This is a very
important rule because a NULL can be
interpreted as one the following − data is
missing, data is not known, or data is not
applicable.
Rule 4: Active Online Catalog
The structure description of the entire database
must be stored in an online catalog, known
as data dictionary, which can be accessed by
authorized users. Users can use the same query
language to access the catalog which they use to
access the database itself.
Rule 5: Comprehensive Data Sub-Language Rule
A database can only be accessed using a
language having linear syntax that supports data
definition, data manipulation, and transaction
management operations. This language can be
used directly or by means of some application. If
the database allows access to data without any
help of this language, then it is considered as a
violation.
Rule 6: View Updating Rule
All the views of a database, which can
theoretically be updated, must also be
updatable by the system.
Rule 7: High-Level Insert, Update, and Delete
Rule
A database must support high-level insertion,
update, and deletion. This must not be limited
to a single row, that is, it must also support
union, intersection and minus operations to
yield sets of data records.
Rule 8: Physical Data Independence
The data stored in a database must be
independent of the applications that access the
database. Any change in the physical structure
of a database must not have any impact on how
the data is being accessed by external
applications.
Rule 9: Logical Data Independence
The logical data in a database must be
independent of its user’s view (application). Any
change in logical data must not affect the
applications using it. For example, if two tables
are merged or one is split into two different
tables, there should be no impact or change on
the user application. This is one of the most
difficult rule to apply.
Rule 10: Integrity Independence
A database must be independent of the
application that uses it. All its integrity
constraints can be independently modified
without the need of any change in the
application. This rule makes a database
independent of the front-end application and its
interface.
Rule 11: Distribution Independence
The end-user must not be able to see that the
data is distributed over various locations. Users
should always get the impression that the data
is located at one site only. This rule has been
regarded as the foundation of distributed
database systems.
Rule 12: Non-Subversion Rule
If a system has an interface that provides access
to low-level records, then the interface must not
be able to subvert the system and bypass
security and integrity constraints.
SQL Commands:
The standard SQL commands to interact with
relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These
commands can be classified into groups based
on their nature:
DDL - Data Definition Language:
- Create/alter/delete tables and their attributes
Command Description
CREATE Creates a new table, a view of

a table, or other object in database.


ALTER Modifies an existing database
object, such as a table.
DROP Deletes an entire table, a view
of a table or other object in the database.

DML - Data Manipulation Language:


– Query one or more tables
– Insert/delete/modify tuples in tables
Command Description
SELECT Retrieves certain records
from one or more tables
INSERT Creates a record
UPDATE Modifies records
DELETE Deletes records
Table name Attribute names
Tables in SQL
Product

PName Price Category Manufacturer

Gizmo $19.99 Gadgets GizmoWorks

Powergizmo $29.99 Gadgets GizmoWorks

SingleTouch $149.99 Photography Canon

MultiTouch $203.99 Household Hitachi

Tuples or rows
Tables Explained

• The schema of a table is the table name and


its attributes:
Product(PName, Price, Category, Manfacturer)

• A key is an attribute whose values are unique;


we underline a key

Product(PName, Price, Category, Manfacturer)


Data Types in SQL
• Atomic types:
– Characters: CHAR(20), VARCHAR(50)
– Numbers: INT, BIGINT, SMALLINT, FLOAT
– Others: MONEY, DATETIME, …

• Every attribute must have an atomic type


– Hence tables are flat
Tables Explained
• A tuple = a record
– Restriction: all attributes are of atomic type

• A table = a set of tuples


– Like a list…
– …but it is unorderd:
no first(), no next(), no last().
What is table?
The data in RDBMS is stored in database objects
called tables. The table is a collection of related
data entries and it consists of columns and rows.
Remember, a table is the most common and
simplest form of data storage in a relational
database.
What is RDBMS?
RDBMS stands for Relational  Management
System.
RDBMS is the basis for SQL, and for all modern
database systems like MS SQL Server, IBM
DB2, Oracle, MySQL, and Microsoft Access.
A Relational database management system
(RDBMS) is a database management system
(DBMS) that is based on the relational model as
introduced by E. F. Codd.
What is NULL value?
A NULL value in a table is a value in a field that
appears to be blank, which means a field with a
NULL value is a field with no value.
It is very important to understand that a NULL
value is different than a zero value or a field that
contains spaces. A field with a NULL value is
one that has been left blank during record
creation.
SQL Constraints:
Constraints are the rules enforced on data
columns on table. These are used to limit the
type of data that can go into a table. This
ensures the accuracy and reliability of the data
in the database.
Constraints could be column level or table level.
Column level constraints are applied only to one
column where as table level constraints are
applied to the whole table.
Following are commonly used constraints available
in SQL:
NOT NULL Constraint: Ensures that a column
cannot have NULL value.
DEFAULT Constraint: Provides a default value for
a column when none is specified.
UNIQUE Constraint: Ensures that all values in a
column are different.
PRIMARY Key: Uniquely identified each
rows/records in a database table.
FOREIGN Key: Uniquely identified a rows/records
in any another database table.
CHECK Constraint: The CHECK constraint
ensures that all values in a column satisfy
certain conditions.
INDEX: Use to create and retrieve data from the
database very quickly.
Data Integrity:
The following categories of the data integrity exist
with each RDBMS:
Entity Integrity: There are no duplicate rows in a
table.
Domain Integrity: Enforces valid entries for a
given column by restricting the type, the format,
or the range of values.
Referential integrity: Rows cannot be deleted,
which are used by other records.
User-Defined Integrity: Enforces some specific
business rules that do not fall into entity, domain
or referential integrity.
• SQL Comments
Comments can be used to explain sections of SQL
statements.
Comments can also be used to prevent execution,
when testing alternative SQL statements.

Single Line Comments


Single line comments start with --.
Any line between -- and the end of the line will be
ignored (will not be executed).
Syntax
-- text_of_comment
Arguments
text_of_comment
Is the character string containing the text of the
comment.
Remarks
Use -- for single-line or nested comments.
Comments inserted with -- are delimited by the
newline character.
There is no maximum length for comments.
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored.
Operators
An operator is a symbol specifying an action that is
performed on one or more expressions.
• Arithmetic operators
• Assignment operator
• Comparison operators
• Logical operators
 Arithmetic Operators
Arithmetic operators perform mathematical
operations on two expressions of any of the data
types of the numeric data type category.
Operator Meaning
+ (Add) Addition.
- (Subtract) Subtraction.
* (Multiply) Multiplication.
/ (Divide) Division.
% (Modulo) Returns the integer remainder of a division.
For example, 12 % 5 = 2 because the
remainder of 12 divided by 5 is 2.
The plus (+) and minus (-) can also be used to
perform arithmetic operations on datetime and
smalldatetime values.
Assignment Operator
SQL has one assignment operator, the equals sign
(=). In this example, the @MyCounter variable
is created. Then, the assignment operator sets
@MyCounter to a value returned by an
expression.
DECLARE @MyCounter INT
SET @MyCounter = 1
Comparison Operators
Comparison operators test whether or not two
expressions are the same. Comparison
operators can be used on all expressions except
expressions of the text, ntext, or image data
types.
Operator Meaning
= (Equals) Equal to
> (Greater Than) Greater than
< (Less Than) Less than
>= (Greater Than Greater than or equal to
or Equal To)
<= (Less Than or Less than or equal to
Equal To)
<> (Not Equal To) Not equal to
The result of a comparison operator has the
Boolean data type, which has three values:
TRUE and FALSE. Expressions that return a
Boolean data type are known as Boolean
expressions.
Logical Operators
Logical operators test for the truth of some
condition. Logical operators, like comparison
operators, return a Boolean data type with a
value of TRUE or FALSE.
Operator Meaning
ALL TRUE if all of a set of comparisons are TRUE.
AND TRUE if both Boolean expressions are TRUE.
ANY TRUE if any one of a set of comparisons are
TRUE.
BETWEEN TRUE if the operand is within a range.
EXISTS TRUE if a subquery contains any rows.
IN TRUE if the operand is equal to one of a list of
expressions.
LIKE TRUE if the operand matches a pattern.
NOT Reverses the value of any other Boolean
operator.
OR TRUE if either Boolean expression is TRUE.
SOME TRUE if some of a set of comparisons are
TRUE.
Operator Precedence
When a complex expression has multiple
operators, operator precedence determines the
sequence in which the operations are
performed. The order of execution can
significantly affect the resulting value.
Operators have these precedence levels. An
operator on higher levels is evaluated before an
operator on a lower level:
• * (Multiply), / (Division), % (Modulo)
• + (Add), - (Subtract)
• =,  >,  <,  >=,  <=,  <>,  !=,  !>,  !< (Comparison
operators)
• NOT
• AND
• ALL, ANY, BETWEEN, IN, LIKE, OR, SOME
• = (Assignment)
String Functions
• ASCII
Returns the ASCII code value of the leftmost
character of a character expression.
Syntax
ASCII ( character_expression )
Arguments
character_expression
Is an expression of the type char or varchar.
Return Types
Int
Example
print ascii('A') answer: 65
• CHAR
A string function that converts an int ASCII code to
a character.
Syntax
CHAR ( integer_expression )
Arguments
integer_expression
Is an integer from 0 through 255. NULL is returned
if the integer expression is not in this range.
Return Types
char(1)
 
Remarks
CHAR can be used to insert control characters into
character strings. The table shows some
commonly used control characters.
Control character Value
Tab CHAR(9)
Line feed CHAR(10)
Carriage return CHAR(13)
Example
 print char(65) answer: A
• LEFT
Returns the part of a character string starting at a
specified number of characters from the left.
Syntax
LEFT( character_expression , integer_expression )
Arguments
character_expression
Is an expression of character or binary data.
character_expression can be a constant,
variable, or column. character_expression must
be of a data type that can be implicitly
convertible to varchar.
Otherwise, use the CAST function to explicitly
convert character_expression.
integer_expression
Is a positive whole number. If integer_expression
is negative, a null string is returned.
Return Types
Varchar
Example
print left(‘san juan’) answer: san j
• LEN
Returns the number of characters, rather than the
number of bytes, of the given string expression,
excluding trailing blanks.
Syntax
LEN ( string_expression )
Arguments
string_expression
Is the string expression to be evaluated.
Return Types
int
Example
print len(‘san juan’) answer: 8
• LOWER
Returns a character expression after converting
uppercase character data to lowercase.
Syntax
LOWER ( character_expression )
Arguments
character_expression
Is an expression of character or binary data.
character_expression can be a constant, variable,
or column. character_expression must be of a
data type that is implicitly convertible to varchar.
 
Return Types
varchar
Example
print lower(‘SAN JUAN’) answer: san juan
• LTRIM
Returns a character expression after removing
leading blanks.
Syntax
LTRIM ( character_expression )
Arguments
character_expression
Is an expression of character or binary data.
character_expression can be a constant,
variable, or column. character_expression must
be of a data type that is implicitly convertible to
varchar. Otherwise, use CAST to explicitly
convert character_expression.
Return Type
varchar
Example
print ltrim('san juan')+ltrim(' bautista')
answer: san juanbautista
• REPLICATE
Repeats a character expression for a specified
number of times.
Syntax
REPLICATE ( character_expression ,
integer_expression )
Arguments
character_expression
Is an alphanumeric expression of character data.
character_expression can be a constant,
variable, or column of either character or binary
data.
integer_expression
Is a positive whole number. If integer_expression
is negative, a null string is returned.
Return Types
varchar
character_expression must be of a data type that
is implicitly convertible to varchar. Otherwise,
use the CAST function to convert explicitly
character_expression.
Example
print replicate(‘nyc',5)
answer:nycnycnycnycnyc
• REVERSE
Returns the reverse of a character expression.
Syntax
REVERSE ( character_expression )
Arguments
character_expression
Is an expression of character data.
character_expression can be a constant,
variable, or column of either character or binary
data.
Return Types
varchar
Remarks
character_expression must be of a data type that
is implicitly convertible to varchar. Otherwise,
use CAST to explicitly convert
character_expression.
Example
print reverse (‘nyc’) answer: cyn
 
RIGHT
Returns the part of a character string starting a
specified number of integer_expression
characters from the right.
Syntax
RIGHT ( character_expression ,
integer_expression )
Arguments
character_expression
Is an expression of character data.
character_expression can be a constant,
variable, or column of either character or binary
data.
integer_expression
Is the starting position, expressed as a positive
whole number. If integer_expression is negative,
an error is returned.
Return Types
varchar
character_expression must be of a data type that is
implicitly convertible to varchar. Otherwise, use
CAST to explicitly convert character_expression.
Example
print right(‘san juan’,3) answer: uan
 
• RTRIM
Returns a character string after truncating all
trailing blanks.
Syntax
RTRIM ( character_expression )
Arguments
character_expression
Is an expression of character data.
character_expression can be a constant,
variable, or column of either character or binary
data.
Return Types
varchar
Remarks
character_expression must be of a data type that
is implicitly convertible to varchar. Otherwise,
use the CAST function to explicitly convert
character_expression.
Example
print rtrim(‘san juan ‘)+’bautista’
answer: san juanbautista
SPACE
Returns a string of repeated spaces.
Syntax
SPACE ( integer_expression )
Arguments
integer_expression
Is a positive integer that indicates the number of
spaces. If integer_expression is negative, a null
string is returned.
Return Types
char
 
Remarks
To include spaces in Unicode data, use
REPLICATE instead of SPACE.
Example
print ‘san juan’ + space(10)+’bautista
answer: san juan bautista
• SUBSTRING
Returns part of a character, binary, text, or image
expression.
Syntax
SUBSTRING ( expression , start , length )
Arguments
expression
Is a character string, binary string, text, image, a
column, or an expression that includes a
column. Do not use expressions that include
aggregate functions.
start
Is an integer that specifies where the substring
begins.
length
Is an integer that specifies the length of the
substring (the number of characters or bytes to
return).
Return Types
Returns character data if expression is one of the
supported character data types.
Example
print substring(‘san juan bautista’,3,5)
answer: n jua
UPPER
Returns a character expression with lowercase
character data converted to uppercase.
Syntax
UPPER ( character_expression )
Arguments
character_expression
Is an expression of character data.
character_expression can be a constant,
variable, or column of either character or binary
data.
Return Types
varchar
Remarks
character_expression must be of a data type that
is implicitly convertible to varchar. Otherwise,
use the CAST function to explicitly convert
character_expression.
Example
print upper(‘san juan’) answer: SAN JUAN
DATE FUNCTIONS
• DATEDIFF
Returns the number of date and time boundaries
crossed between two specified dates.
Syntax
DATEDIFF ( datepart , startdate , enddate )
Arguments
datepart
Is the parameter that specifies on which part of the
date to calculate the difference.
The table lists dateparts and abbreviations.
Datepart Abbreviations
Year yy, yyyy
quarter qq, q
Month mm, m
dayofyear dy, y
Day dd, d
Week wk, ww
Hour hh
minute mi, n
second ss, s
millisecond ms
startdate
Is the beginning date for the calculation. startdate
is an expression that returns a datetime or
smalldatetime value, or a character string in a
date format.
enddate
Is the ending date for the calculation. enddate is
an expression that returns a datetime or
smalldatetime value, or a character string in a
date format.
Return Types
integer
Remarks
startdate is subtracted from enddate. If startdate is
later than enddate, a negative value is returned.
Example
print datediff(yy,'9/1/2004','9/1/2005') answer: 1
print datediff(qq,'9/1/2004','9/1/2005') answer: 4
print datediff(mm,'9/1/2004','9/1/2005') answer: 12
print datediff(dy,'9/1/2004','9/1/2005') answer: 365
print datediff(dd,'9/1/2004','9/1/2005') answer: 365
print datediff(wk,'9/1/2004','9/1/2005') answer: 52
print datediff(hh,'9/1/2004','9/1/2005') answer: 8760
print datediff(mi,'9/1/2004','9/1/2005‘)
answer: 525600
print datediff(ss,'9/1/2004','9/1/2005‘)
answer: 31536000
print datediff(ms,'8/31/2005','9/1/2005')
answer: 86400000
 
• DATEPART
Returns an integer representing the specified
datepart of the specified date.
Syntax
DATEPART ( datepart , date )
Arguments
datepart
Is the parameter that specifies the part of the date
to return.
The table lists dateparts and abbreviations.
Datepart Abbreviations
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw
hour hh
minute mi, n
second ss, s
millisecond ms
The week (wk, ww) datepart reflects changes
made to SET DATEFIRST. January 1 of any
year defines the starting number for the week
datepart, for example: DATEPART(wk, 'Jan 1,
xxxx') = 1, where xxxx is any year.
The weekday (dw) datepart returns a number that
corresponds to the day of the week, for example:
Sunday = 1, Saturday = 7. The number
produced by the weekday datepart depends on
the value set by SET DATEFIRST, which sets
the first day of the week.
date
Is an expression that returns a datetime or
smalldatetime value, or a character string in a
date format. Use the datetime data type only for
dates after January 1, 1753.
Return Types
int
Remarks
The DAY, MONTH, and YEAR functions are
synonyms for DATEPART(dd, date),
DATEPART(mm, date), and DATEPART(yy,
date), respectively.
The GETDATE function returns the current date;
however, the complete date is not always the
information needed for comparison (often only a
portion of the date is compared).
Example
print datepart(yy,'9/1/2005') answer: 2005
print datepart(yy,'9/1/2005') answer: 3
print datepart(mm,'9/1/2005') answer: 9
print datepart(dy,'9/1/2005') answer: 244
print datepart(dd,'9/1/2005') answer: 1
print datepart(wk,'9/1/2005') answer: 36
print datepart(dw,'9/1/2005') answer: 5
print datepart(hh,getdate()) answer: 10
print datepart(mi,getdate()) answer: 11
print datepart(ss,getdate()) answer: 41
print datepart(ms,getdate()) answer: 300
• DATENAME
Returns a character string representing the
specified datepart of the specified date.
Syntax
DATENAME ( datepart , date )
Arguments
datepart
Is the parameter that specifies the part of the date
to return.
• The table lists dateparts and abbreviations.
Datepart Abbreviations
Year yy, yyyy
Quarter qq, q
Month mm, m
Dayofyear dy, y
Day dd, d
Week wk, ww
weekday dw
hour hh
minute mi, n
second ss, s
millisecond ms
The weekday (dw) datepart returns the day of the
week (Sunday, Monday, and so on).
Return Types
nvarchar
Example
print datename(yy,'9/1/2005') answer: 2005
print datename(qq,'9/1/2005') answer: 3
print datename(mm,'9/1/2005') answer:
September
print datename(dy,'9/1/2005') answer: 244
print datename(dd,'9/1/2005') answer: 1
print datename(wk,'9/1/2005') answer: 36
print datename(dw,'9/1/2005') answer: Thursday
 
 
Mathematical Functions
• These scalar functions perform a calculation,
usually based on input values provided as
arguments, and return a numeric value.
• ABS
Returns the absolute, positive value of the given
numeric expression.
Syntax
ABS ( numeric_expression )
Arguments
numeric_expression
Is an expression of the exact numeric or
approximate numeric data type category, except
for the bit data type.
Return Types
Returns the same type as numeric_expression.
Example
print abs(-5) answer: 5
• CEILING
Returns the smallest integer greater than, or equal
to, the given numeric expression.
Syntax
CEILING ( numeric_expression )
Arguments
numeric_expression
Is an expression of the exact numeric or
approximate numeric data type category, except
for the bit data type.
 Return Types
Returns the same type as numeric_expression.
Example
print ceiling(9.4) answer: 10
• FLOOR
Returns the largest integer less than or equal to
the given numeric expression.
Syntax
FLOOR ( numeric_expression )
Arguments
numeric_expression
Is an expression of the exact numeric or
approximate numeric data type category, except
for the bit data type.
Return Types
Returns the same type as numeric_expression.
Example
print floor(9.4) answer: 9
• POWER
Returns the value of the given expression to the
specified power.
Syntax
POWER ( numeric_expression , y )
Arguments
numeric_expression
Is an expression of the exact numeric or
approximate numeric data type category, except
for the bit data type.
y
Is the power to which to raise numeric_expression.
y can be an expression of the exact numeric or
approximate numeric data type category, except
for the bit data type.
Return Types
Same as numeric_expression.
Example
print power(2,3) answer: 8
• ROUND
Returns a numeric expression, rounded to the
specified length or precision.
Syntax
ROUND ( numeric_expression , length [ , function ]
)
Arguments
numeric_expression
Is an expression of the exact numeric or
approximate numeric data type category, except
for the bit data type.
length
Is the precision to which numeric_expression is to
be rounded. length must be tinyint, smallint, or
int. When length is a positive number,
numeric_expression is rounded to the number of
decimal places specified by length. When length
is a negative number, numeric_expression is
rounded on the left side of the decimal point, as
specified by length.
function
Is the type of operation to perform. function must
be tinyint, smallint, or int. When function is
omitted or has a value of 0 (default),
numeric_expression is rounded. When a value
other than 0 is specified, numeric_expression is
truncated.
Return Types
Returns the same type as numeric_expression.
Remarks
ROUND always returns a value. If length is
negative and larger than the number of digits
before the decimal point, ROUND returns 0.
Example Result
ROUND(748.58, -4) 0
ROUND returns a rounded numeric_expression,
regardless of data type, when length is a
negative number.
Example Result
ROUND(748.58, -1) 750.00
ROUND(748.58, -2) 700.00
ROUND(748.58, -3) 1000.00
Example
print round(3.456,2) answer: 3.460
• SQUARE
Returns the square of the given expression.
Syntax
SQUARE ( float_expression )
Arguments
float_expression
Is an expression of type float.
Return Types
float
Example
print square(5) answer: 25
• SQRT
Returns the square root of the given expression.
Syntax
SQRT ( float_expression )
Arguments
float_expression
Is an expression of type float.
Return Types
float
Example
print sqrt(3) answer: 1.73205
SQL - CREATE Database

The SQL CREATE DATABASE statement is used


to create new SQL database.
Syntax:
Basic syntax of CREATE DATABASE statement is
as follows:
CREATE DATABASE DatabaseName;
Database name should always be unique within
the RDBMS.
Example
CREATE DATABASE my_db;
SQL - DROP or DELETE Database
The SQL DROP DATABASE statement is used to
drop an existing database in SQL schema.
Syntax:
Basic syntax of DROP DATABASE statement is as
follows:
DROP DATABASE DatabaseName;
Example
DROP DATABASE my_db;
SQL - SELECT Database, USE Statement
When you have multiple databases in your SQL
Schema, then before starting your operation,
you would need to select a database where all
the operations would be performed.
The SQL USE statement is used to select any
existing database in SQL schema.
Syntax:
Basic syntax of USE statement is as follows:
USE DatabaseName;
SQL - CREATE Table
Creating a basic table involves naming the table
and defining its columns and each column's data
type.
The SQL CREATE TABLE statement is used to
create a new table.
Syntax:
Basic syntax of CREATE TABLE statement is as
follows:
CREATE TABLE table_name( column1
datatype(size), column2 datatype(size), column3
datatype(size), ..... columnN datatype(size),
PRIMARY KEY( one or more columns ) );
Example:
Following is an example, which creates a
CUSTOMERS table with ID as primary key and
NOT NULL are the constraints showing that
these fields can not be NULL while creating
records in this table:
CREATE TABLE CUSTOMERS( ID INT NOT
NULL UNIQUE CHECK(ID>0),
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) DEFAULT ‘MANILA’,
SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
SQL - DROP or DELETE Table
The SQL DROP TABLE statement is used to
remove a table definition and all data, indexes,
triggers, constraints, and permission
specifications for that table.
NOTE: You have to be careful while using this
command because once a table is deleted then
all the information available in the table would
also be lost forever.
Syntax:
Basic syntax of DROP TABLE statement is as
follows:
DROP TABLE table_name;
Example: DROP TABLE CUSTOMERS;
SQL SELECT INTO Statement
With SQL, you can copy information from one
table into another.
The SELECT INTO statement copies data from
one table and inserts it into a new table.
The SQL SELECT INTO Statement
The SELECT INTO statement selects data from
one table and inserts it into a new table.
SQL SELECT INTO Syntax
We can copy all columns into the new table:
SELECT *
INTO newtable [IN externaldb]
FROM table1;
Or we can copy only the columns we want into the
new table:
SELECT column_name(s)
INTO newtable [IN externaldb]
FROM table1;
The new table will be created with the column-
names and types as defined in the SELECT
statement. You can apply new names using the
AS clause.
SQL SELECT INTO Examples
Create a backup copy of Customers:
SELECT *
INTO CustomersBackup2013
FROM Customers;
SQL INSERT INTO SELECT Statement
The INSERT INTO SELECT statement copies data
from one table and inserts it into an existing
table.
The SQL INSERT INTO SELECT Statement
The INSERT INTO SELECT statement selects
data from one table and inserts it into an existing
table. Any existing rows in the target table are
unaffected.
SQL INSERT INTO SELECT Syntax
We can copy all columns from one table to
another, existing table:
INSERT INTO table2
SELECT * FROM table1;
Or we can copy only the columns we want to into
another, existing table:
INSERT INTO table2
(column_name(s))
SELECT column_name(s)
FROM table1;
SQL INSERT INTO SELECT Examples
Copy only a few columns from "Suppliers" into
"Customers":
Example
INSERT INTO Customers (CustomerName,
Country)
SELECT SupplierName, Country FROM Suppliers;
SQL - INSERT Query
The SQL INSERT INTO Statement is used to add
new rows of data to a table in the database.
Syntax:
There are two basic syntaxes of INSERT INTO
statement as follows:
INSERT INTO TABLE_NAME (column1, column2,
column3,...columnN)] VALUES (value1, value2,
value3,...valueN);Here, column1,
column2,...columnN are the names of the
columns in the table into which you want to
insert data.
You may not need to specify the column(s) name
in the SQL query if you are adding values for all
the columns of the table. But make sure the
order of the values is in the same order as the
columns in the table. The SQL INSERT INTO
syntax would be as follows:
INSERT INTO TABLE_NAME VALUES
(value1,value2,value3,...valueN);
Example:
Following statements would create six records in
CUSTOMERS table:
INSERT INTO CUSTOMERS
(ID,NAME,AGE,ADDRESS,SALARY) VALUES (1,
'Ramesh', 32, 'Ahmedabad', 2000.00 );
INSERT INTO CUSTOMERS
(ID,NAME,AGE,ADDRESS,SALARY) VALUES (2,
'Khilan', 25, 'Delhi', 1500.00 );
INSERT INTO CUSTOMERS
(ID,NAME,AGE,ADDRESS,SALARY) VALUES (3,
'kaushik', 23, 'Kota', 2000.00 );
INSERT INTO CUSTOMERS
(ID,NAME,AGE,ADDRESS,SALARY) VALUES (4,
'Chaitali', 25, 'Mumbai', 6500.00 );
INSERT INTO CUSTOMERS
(ID,NAME,AGE,ADDRESS,SALARY) VALUES (5,
'Hardik', 27, 'Bhopal', 8500.00 );
INSERT INTO CUSTOMERS
(ID,NAME,AGE,ADDRESS,SALARY) VALUES (6,
'Komal', 22, 'MP', 4500.00 );
You can create a record in CUSTOMERS table
using second syntax as follows:
INSERT INTO CUSTOMERS VALUES (7, 'Muffy',
24, 'Indore', 10000.00 );
SQL - UPDATE Query
The SQL UPDATE Query is used to modify the
existing records in a table.
You can use WHERE clause with UPDATE query
to update selected rows otherwise all the rows
would be affected.
Syntax:
The basic syntax of UPDATE query with WHERE
clause is as follows:
UPDATE table_name SET column1 = value1,
column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using
AND or OR operators.
Example:
UPDATE CUSTOMERS SET ADDRESS = ‘Manila'
WHERE ID = 6;
SQL - DELETE Query
The SQL DELETE Query is used to delete the
existing records from a table.
You can use WHERE clause with DELETE query
to delete selected rows, otherwise all the records
would be deleted.
Syntax:
The basic syntax of DELETE query with WHERE
clause is as follows:
DELETE FROM table_name WHERE [condition];
You can combine N number of conditions using
AND or OR operators.
Example:
DELETE FROM CUSTOMERS WHERE ID = 6;
SQL - WHERE Clause
The SQL WHERE clause is used to specify a
condition while fetching the data from single
table or joining with multiple tables.
If the given condition is satisfied then only it
returns specific value from the table. You would
use WHERE clause to filter the records and
fetching only necessary records.
The WHERE clause is not only used in SELECT
statement, but it is also used in UPDATE,
DELETE statement, etc.
Syntax:
The basic syntax of SELECT statement with
WHERE clause is as follows:
SELECT column1, column2, columnN FROM
table_name WHERE [condition]You can specify
a condition using comparison or logical
operators like >, <, =, LIKE, NOT, etc.
Example:
SELECT ID, NAME, SALARY FROM
CUSTOMERS WHERE SALARY > 2000
SQL - AND and OR Conjunctive Operators
The SQL AND and OR operators are used to
combine multiple conditions to narrow data in an
SQL statement. These two operators are called
conjunctive operators.
These operators provide a means to make multiple
comparisons with different operators in the same
SQL statement.
The AND Operator:
The AND operator allows the existence of multiple
conditions in an SQL statement's WHERE
clause.
Syntax:
The basic syntax of AND operator with WHERE
clause is as follows:
SELECT column1, column2, columnN FROM
table_name WHERE [condition1] AND
[condition2]...AND [conditionN];
Example:
SELECT ID, NAME, SALARY FROM
CUSTOMERS WHERE SALARY > 2000 AND
age < 25;
The OR Operator:
The OR operator is used to combine multiple
conditions in an SQL statement's WHERE
clause.
Syntax:
The basic syntax of OR operator with WHERE
clause is as follows:
SELECT column1, column2, columnN FROM
table_name WHERE [condition1] OR
[condition2]...OR [conditionN]
Example:
SELECT ID, NAME, SALARY FROM
CUSTOMERS WHERE SALARY > 2000 OR age
< 25;
SQL - LIKE Clause
The SQL LIKE clause is used to compare a value
to similar values using wildcard operators. There
are two wildcards used in conjunction with the
LIKE operator:
The percent sign (%)
The underscore (_)
The percent sign represents zero, one, or multiple
characters. The underscore represents a single
number or character. The symbols can be used
in combinations.
Syntax:
The basic syntax of % and _ is as follows:
SELECT FROM table_name WHERE column LIKE
• The IN Operator
The IN operator allows you to specify multiple
values in a WHERE clause.
• SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
SQL - TOP, LIMIT or ROWNUM Clause
The SQL TOP clause is used to fetch a TOP N
number or X percent records from a table.
Note: All the databases do not support TOP
clause. For example MySQL
supports LIMIT clause to fetch limited number of
records and Oracle usesROWNUM to fetch
limited number of records.
Syntax:
The basic syntax of TOP clause with SELECT
statement would be as follows:
SELECT TOP number|percent column_name(s)
FROM table_name WHERE [condition]
• Example:
• SELECT TOP 3 * FROM CUSTOMERS;
• SELECT * FROM CUSTOMERS LIMIT 3;
• SELECT * FROM CUSTOMERS WHERE
ROWNUM <= 3;
SQL - ORDER BY Clause
The SQL ORDER BY clause is used to sort the
data in ascending or descending order, based
on one or more columns. Some database sorts
query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause is as
follows:
SELECT column-list FROM table_name [WHERE
condition] [ORDER BY column1, column2, ..
columnN] [ASC | DESC];You can use more than
one column in the ORDER BY clause. Make
sure whatever column you are using to sort, that
column should be in column-list.
Example:
SELECT * FROM CUSTOMERS ORDER BY
NAME DESC;
SQL - Group By
The SQL GROUP BY clause is used in
collaboration with the SELECT statement to
arrange identical data into groups.
The GROUP BY clause follows the WHERE clause
in a SELECT statement and precedes the
ORDER BY clause.
Syntax:
The basic syntax of GROUP BY clause is given
below. The GROUP BY clause must follow the
conditions in the WHERE clause and must
precede the ORDER BY clause if one is used.
SELECT column1, column2 FROM table_name
WHERE [ conditions ] GROUP BY column1,
column2 ORDER BY column1, column2
Example:
SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;
SQL - Distinct Keyword
The SQL DISTINCT keyword is used in
conjunction with SELECT statement to eliminate
all the duplicate records and fetching only
unique records.
There may be a situation when you have multiple
duplicate records in a table. While fetching such
records, it makes more sense to fetch only
unique records instead of fetching duplicate
records.
Syntax:
The basic syntax of DISTINCT keyword to
eliminate duplicate records is as follows:
SELECT DISTINCT column1,
column2,.....columnN FROM table_name
WHERE [condition]
Example:
SELECT DISTINCT SALARY FROM
CUSTOMERS ORDER BY SALARY;
SQL - Using Joins
• The SQL Joins clause is used to combine
records from two or more tables in a database. A
JOIN is a means for combining fields from two
tables by using values common to each.
• The most common type of join is: SQL INNER
JOIN (simple join). An SQL INNER JOIN
returns all rows from multiple tables where the
join condition is met.
Example
SELECT Orders.OrderID,
Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
SQL - UNIONS CLAUSE
• The UNION operator is used to combine the
result-set of two or more SELECT statements.
Notice that each SELECT statement within the
UNION must have the same number of columns.
The columns must also have similar data types.
Also, the columns in each SELECT statement
must be in the same order.
• SQL UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s)  FROM table2;
SQL ALTER TABLE Statement
• The ALTER TABLE Statement
The ALTER TABLE statement is used to add,
delete, or modify columns in an existing table.
• SQL ALTER TABLE Syntax
To add a column in a table, use the following
syntax:
ALTER TABLE table_name
ADD column_name datatype
• SQL ALTER TABLE Example
ALTER TABLE Persons
ADD DateOfBirth date
SQL Functions
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated
from values in a column.
Useful aggregate functions:
• AVG() - Returns the average value
• COUNT() - Returns the number of rows
• FIRST() - Returns the first value
• LAST() - Returns the last value
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum
SQL Scalar functions
SQL scalar functions return a single value, based on
the input value.
Useful scalar functions:
• UCASE() - Converts a field to upper case
• LCASE() - Converts a field to lower case
• MID() - Extract characters from a text field
• LEN() - Returns the length of a text field
• ROUND() - Rounds a numeric field to the number
of decimals specified
• NOW() - Returns the current system date and time
• FORMAT() - Formats how a field is to be
displayed
REFERENCES

• https://www.tutorialspoint.com/sql/sql-overvi
ew.htm
• http://www.w3schools.com/sql/
• courses.cs.washington.edu/courses/cse544/0
6sp/lectures/lecture-sql.ppt

Das könnte Ihnen auch gefallen