0% found this document useful (0 votes)
9 views34 pages

SQL_4

The document covers querying databases using MS SQL Server, detailing input requirements, output formatting, data sources, and various query types and operators. It explains the client/server architecture, the structure of SQL including DDL, DML, DQL, and DCL, and provides insights into functions for string, date, and mathematical operations. Additionally, it discusses joins, subqueries, and set operators, along with practical examples for executing queries and creating new tables.

Uploaded by

Nidhi Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
9 views34 pages

SQL_4

The document covers querying databases using MS SQL Server, detailing input requirements, output formatting, data sources, and various query types and operators. It explains the client/server architecture, the structure of SQL including DDL, DML, DQL, and DCL, and provides insights into functions for string, date, and mathematical operations. Additionally, it discusses joins, subqueries, and set operators, along with practical examples for executing queries and creating new tables.

Uploaded by

Nidhi Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 34

MS SQL SERVER

Session # 4:
Querying database
Focus Points :
 Identify the input requirements for a query.
 Plan and create a format for the query output.
 Identify and use sources of data for a query.
 Identify and use different types of queries.
 Use different types of operators.
 Use aggregate functions in querries.
 Sort the query output.
 Group the query output.
 Use the top keyword.
 Calculate and display totals and subtotals.
 Use string functions.
 Use date functions.
 Use mathematical functions.
 Use wild cards.
 Use the distinct keyword in a query.
 Use the querries with different types of joins.
 Use different types of subquerries.
Contents

 Concept of client/server architecture.


 Structured query language sql – ddl,dml,dql,dcl
 Using select , using alias for column name
 Using with operators –
 Where,
 Arithmetic, relational,
 In, and, or
 Is null/not null,

 Order by,
 Aggregate functions,
Contents

 Group by and having,


 Top,
 Compute,
 String functions,
 Datetime functions,
 Wildcard,
 Distinct,
 Join – inner, outer , cartesian, equi-join,
 Set Operators - Union, union all, except, intersect
 Subquery – single row or multiple rows
Concept of Client/Server Architecture

 In the MS SQL Server client/server architecture, the database


application and the database are separated into two parts:
 a front-end or client portion, and a back-end or server portion. The client
executes the database application that accesses database information
and interacts with a user through the keyboard, screen, and pointing
device such as a mouse.
 The server executes the MS SQL Server software and handles the
functions required for concurrent, shared data access to an MS SQL
Server database.
 Although the client application and MS SQL Server can be
executed on the same computer, it may be more efficient and
effective when the client portion(s) and server portion are
executed by different computers connected via a network.
Concept of Client/Server Architecture
Structure Query Language(SQL) –
DDL, DML, DQL and DCL

 The Structured Query Language (SQL) is the language of databases.


 All modern relational databases, including Access, FileMaker Pro,
Microsoft SQL Server and Oracle use SQL as their basic building
block.
 In fact, it’s often the only way that you can truly interact with the
database itself.
 All of the fancy graphical user interfaces that provide data entry and
manipulation functionality are nothing more than SQL translators.
They take the actions you perform graphically and convert them to
SQL commands understood by the database.
 SQL is Similar to English
 Fortunately, at its core, SQL is a simple language.
 It has a limited number of commands and those commands are very
readable and are almost structured like English sentences.
Structure Query Language(SQL) –
DDL, DML, DQL and DCL cont..

 SQL commands can be divided into two main


sublanguages.
 The Data Definition Language (DDL) contains the commands used to
create and destroy databases and database objects.
 Create,
 Alter,
 Drop,
 Truncate
 After the database structure is defined with DDL, database
administrators, users can utilize the Data Manipulation Language
(DML) to insert, retrieve and modify the data contained within it.
 Insert
 Update
 Delete
Structure Query Language(SQL) –
DDL, DML, DQL and DCL cont..

 Data Query Language (DQL) contains commands to perform


querying and retrieving data from table.
 Select
 While Data Control Language contains commands to secure
and control access to database and its objects.
 Grant,
 Deny,
 Revoke
Select, and using Alias

 Getting Started
 Start the Query Analyzer.
 Connect to the Server.
 Connect to the Database.
 Type the Query.
 Execute the query.
Select, and using Alias

 Getting all rows


 select * from tablename
 Getting all rows with all columns
 select * from tablename
 Getting all rows with specific columns
 Select [column1,column2,..] from tablename
 Getting all tows with specific columns with user-friendly
names (alias)
 Select [column1 [as] ‘columnname’,…] from tablename
Where clause, Order By

 Filtering
 Select [column1,..] [*] from tablename where [clause]
 Some usefull operators
 Relational operators >, <, >=,<=,!>,!<,<>,=,!=
 In , between (Range Operator)
 And , or (logical operator) , not
 is null/not null
 Order By
 Select [column1,..] [*] from tablename order by [column1,..]
where [clause]
Aggregate Functions

 max()
 min()
 count()
 avg()
 sum()
Group by with having

 The GROUP BY clause groups summary data that meets


the WHERE clause criteria to be returned as single rows.
The HAVING clause sets the criteria to determine which
rows will be returned by the GROUP BY clause. For
example, you could find out which books have more than
one author and then return the book title and the authors
for each book.
 The HAVING clause has the same effect on the GROUP
BY clause as the WHERE clause has on
the SELECT statement.
Top

 Select top [n] [*] [column1,…] from tablename [where]


[order by]
 Compute by
 The COMPUTE and COMPUTE BY clauses produce new
rows of nonrelational data; therefore, they cannot be used
with the SELECT INTO statement to create new tables. This
also makes them nearly impossible to use
programmatically.
String Functions

+ (expression, Concatenates two or more character strings


expression)
ASCII (char_ex ASCII code value of left-most character
pr)
CHAR (integer_ Character equivalent of ASCII code value
expr)
CHARINDEX (p Returns starting position of specified patern
attern,
expression)
DIFFERENCE ( Compares two strings and evaluates their similarity; returns a value
char_expr1, from 0 to 4, 4 being the best match
char_exr2)
LEFT( char_exp Returns character string starting from the left and
r, integer_expr ) preceding integer_expr characters
LOWER (char_e Converts to lowercase
xpr)
LTRIM (char_e Returns data without leading blanks
xpr)
String Functions

+ (expression, Concatenates two or more character strings


expression)
NCHAR( integer Returns the Unicode character corresponding to the integer_expr
_expr )
PATINDEX ('%p Returns starting position of first occurrence in Expression
attern%' ,expres
sion)
QUOTENAME (' Returns a Unicode string (nvarchar(129)) with valid SQL Server
string1' ,'quote_ delimiters
char')
REPLACE( 'stri Replaces all occurrences of 'string3')string2 in string1 with string3
ng1' ,'string2' ,
REPLICATE (ch Repeats char_expr integer_expr number of times
ar_expr,
integer_expr)
REVERSE (char Returns reverse of char_expr
_expr)
String Functions

+ (expression, Concatenates two or more character strings


expression)
RIGHT (char_e Returns character string starting integer_expr characters from right
xpr,
integer_expr)
RTRIM (char_e Data without trailing blanks
xpr)
SOUNDEX (cha Returns a four-digit (SOUNDEX) code to evaluate the similarity of two
r_expr) character strings
SPACE (integer Returns a string of repeated spaces equal to integer_expr
_expr)
STR (float_expr Returns character data [,decimal]]) converted from numeric
[,length data; length is the total length anddecimal is the number of spaces to
the right of the decimal
STUFF (char_ex Deletes length characters from char expr1 at start and
pr1, start, inserts char_expr2 at start
length, char_ex
pr2)
String Functions

+ (expression, Concatenates two or more character strings


expression)
SUBSTRING (ex Returns part of a character or binary string
pression,
start, length)
UNICODE ('nch Returns the Unicode integer value of the first character
ar_string') of 'nchar_string'
UPPER (char_e Converts to uppercase
xpr)
Datetime Functions

DATEADD( Adds the number of dateparts to the date


datepart,
number,
date )
DATEDIFF( d Number of dateparts between two dates
atepart, date1,
date2 )
DATENAME( Returns ASCII value for specified datepart for date listed
datepart,
date )
DATEPART( d Returns integer value for specified datepart for date listed
atepart, date )
GETDATE() Current date and time in internal format
Datetime Functions

datepart Abbreviat Values


ion
day dd 1–31
day of year dy 1–366
hour hh 0–23
millisecond ms 0–999
minute mi 0–59
month mm 1–12
quarter qq 1–4
second ss 0–59
week wk 0–53
weekday dw 1–7 (Sun–Sat)
year yy 1753–9999
Math Functions

Function Results
ABS( numeric Absolute value
_expr )
ACOS, Angle in radians whose cosine, sine, or tangent is a floating-
ASIN ATAN point value
( float_expr )
ATN2( float_e Returns the angle in radians whose tangent is
xpr1 , float_ex between float1 and float2
pr2 )
COS, Cosine, sine, or tangent of the angle (in radians)
SIN COT,
TAN( float_ex
pr )
CEILING( nu Smallest integer greater than or equal to specified value
meric_expr )
Math Functions

Function Results
DEGREES( nu Conversion from radians to degrees
meric_expr )
EXP( float_ex Exponential value of specified value
pr )
FLOOR( nume Largest integer less than or equal to specified value
ric_expr )
LOG( float_ex Natural log
pr )
LOG10( float_ Base-10 log
expr )
PI() Constant 3.141592653589793
POWER( num Value of numeric_expr to the power of y
eric_expr , y )
Math Functions

Function Results
RADIANS( nu Conversion from degrees to radians
meric_expr )
RAND([seed]) Random float number between 0 and 1
ROUND( num Numeric_exp rounded to the specified length, length in an
eric_expr,len ) integer value
SIGN( numeri Positive, negative, or zero
c_expr )
SQUARE( floa Squares the specified value
t_expr )
SQRT(float_ex Square root of specified value
pr)
Wildcard

 The available wildcards are


 %— String of zero or more characters
 _— Single character
 []— Single character within the specified range
 [^]— Single character not within specified range
Distinct

 Returning unique values


Joins

 Joins connect two tables based on a join condition


producing results as a new table, with the rows that
satisfy the join condition.
 Inner Join
 Inner joins produce information when matching
information is found in both tables. The most common
types of inner joins are equijoins and natural joins.
 Natural Joins
 In a natural join, column values are compared for equality,
but redundant columns are eliminated from the columns in
the result set.
 Equi Join
 In an equijoin, column values are compared for equality, and
redundant columns are displayed as columns in the result
set;
Joins

 Self Join
 a self join correlates rows of a table with other rows in the
same table. Comparison queries for the same information
are used the most for self joins.
 Cross or Unrestricted Joins
 Cross or unrestricted joins return a combination of all
rows of all tables in the join as the result set. A cross or
unrestricted join is created not by using the WHERE clause
in the SQL Server join of two or more tables, but by using
the CROSS JOIN keyword.
 Combining all rows from all tables involved in the join
yields what is known as a Cartesian product.
Joins

 Outer Joins
 You can restrict rows from one table while allowing all rows
from another table as your result set by using outer joins. One
of the most common uses for this type of join is to search for
orphan records. The outer join operators and keywords are as
follows:
 Includes all rows from the first table and only the matching rows
in the second table – Left outer Join
 Includes all rows from the second table and only the matching
rows in the first table – Right outer Join
 Includes all nonmatching rows from both tables – Full outer
Join
Set Operators

 Union , Union All


 You can combine the results of two or more queries into a
single result set by using the UNION operator. By default,
duplicate rows are eliminated; however, using UNION with
the ALL keyword returns all rows, including duplicates.
 Intersect
 You can combine the results of two or more queries into a
single result set to get the common by using,
the intersect operator.
 Except
 You can combine the results of two or more queries into a
single result set to get only the result of first set, by using
the intersect operator.
Subquerry

 Subquerries
 A SELECT statement nested inside another SELECT statement
is commonly referred to as a subquery. Subquerries can
produce the same results as a join operation.
 Single Row Subquerry
 A subquery can return a single column or single value
anywhere a single value expression can be used and can be
compared against using the following operators: =, <, >, <=,
>=, <>, !>, and !<.
 It can return single column/many values that can be used with
the IN list comparison operator in the WHERE clause.
Subquerry

 Multi-Row Subquerry
 A subquery can also return many rows that will be used for an
existence check by using the EXISTS keyword in
the WHERE clause.
Select into

 The SELECT INTO statement enables you to create a new


table based on query results. The new table is based on the
columns you specify in the select list, the tables you name
in the FROM clause, and the rows you choose in
the WHERE clause. There are two types of tables you can
create with a SELECT INTO statement: permanent and
temporary.
Summary

 Client/Server Architecture
 Where
 Order by
 Group by
 wildcard
 Set Operators
 Join
 Subquerry
 Select into

You might also like