SlideShare a Scribd company logo
T-SQL – 2nd sessionMedhatDawoudhttp://www.medhatdawoud.comMedhatDawoud@gmail.com@Med7atDawoud
AgendaSelect the DBMS we will useSelect Database to work onPUBS DatabaseDatabases and tablesConnecting to your databaseChange databasesSome rules for SQLOverview of PUBS databaseFirst Select Command
Agenda cont.Concatenate two columnsAliasWhere & compound criteriaComparison operatorsRangeWild cardsEscape charactersPattern matchingNegation
Database Management SystemThere are many RDBMSs that is used such as:Oracle
SQL server
MySQL
SQLite
…
etc.In this class we will use the SQL serveras our DBMS, Because it’s the most interactive one in out case.
SQL server 2005 or 2008We need a SQLserver to interact with Database through queries as DBMS.Download from :http://www.microsoft.com/sqlserver/2005/en/us/express.aspxWe need any version of SQL server(2005 or 2008).
Select Database to work onI selected the Northwindsimple database to make our queries on.You can download it from:http://www.microsoft.com/downloads/en/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034
PUBS Database
DatabasesAt the most basic level a database is really just a file.
Databases come in all shapes and sizes.  Some are large and some are small.  But each database generally serves a particular purpose.
Examples:  Tracking employee payroll, sales data on a particular sales line, stock data for a particular industry
All databases are made up of objects.  The most important object (and the one we will learn how to use in this class) is a table.TablesA table is a storage structure made up of rows and columns.  (Sort of like a spreadsheet.)
Due to the differing terminologies, there are interchangeable sets of terms:Database	Mathematical	Data Processing	Table		Relation	File	Row		Tuple		Record	Column	Attribute		FieldThese terms are used interchangeably, but we will generally use the table – row – column terminologyConnectto a databaseA query as the term implies is a question we ask the database.
The same procedure gives the same result with the same database in any other DBMS.
Regardless of name, they all perform the same purpose.  This is to give you an interface for sending SQL statements and receiving results.SQL Server LoginStartup ISQL/WLogin windowA SQL Server can have many different databases running on it at the same time.  Database setup on the server Assign databasesYour first SQL statementuse <database>This tells the SQL Server what database you will be using to perform your queries.Example:  use PUBS1
Verify your databaseTo check the database you are accessing use:select db_name()Throughout this course some of the things we discuss will be MS SQL Server specific. The DBMS you are using should have a command or function similar to this, but not necessarily the same.
Basic syntax rulesSQL keywords (use, select, from, where, etc.) are case insensitive.
select is the same as SELECT is the same as SeLeCt, etc.
However depending on the DBMS (Database Management System), the columns might be case sensitive.
The databases we have setup on our server are case insensitive.Rules cont.Spacing does not matter (for the most part).
select CustomerID…is the same asselect  	CustomerID …However, you must still separate words.  You can not use the following:selectCustomerID…  This will give a syntax error, because SQL Server must be able to find your SQL keywords.
Rules cont.Carriage returns are ignored
select CustomerID from Customers	is the same asselect CustomerID	from CustomersThe spacing and carriage returns just make reading your SQL a lot easier.
The general format used by most people is to place the separate clausesof the statement on different linesPUBS DatabaseThis is the database for which you have an ER diagram for.
ER diagram explanation
You will generally get an ER diagram at each client when you begin work on a project.  If you don’t have one, ask for one.  This will save time in trying to determine what data is where and how everything is linked together.  If you can’t get one, don’t panic!  There are ways to get the database to tell you what it contains.PUBS Database example
Ok, Lets talk about commands (Queries)
SelectA select statement is used to retrieve data from a database.
In order to get information from the database, you must tell the database what you are looking for.  The first step along this journey is to get some simple information from the database.
select 'Mary had a little lamb.'--------------Mary had a little lamb.(1 row affected)
SelectAn asterisk (*) is used to designate all columns in a table.select *We also need to tell it which table to get the data from.select * from authorsThe main sections in every SQL statement are called clauses.  The three clauses we will focus on are the select, from, and where
We can limit the columns returned by specifying them instead of using *.select author_id , author_name from authors
ConcatenationWe can also combine data together.  This is called concatenation.

More Related Content

What's hot (20)

PPT
Sql intro & ddl 1
Dr. C.V. Suresh Babu
 
DOC
Database queries
IIUM
 
PPTX
New T-SQL Features in SQL Server 2012
Richie Rump
 
PPTX
SQL Commands
Sachidananda M H
 
PDF
Using T-SQL
Antonios Chatzipavlis
 
PDF
Sql a practical introduction
Hasan Kata
 
PPTX
SQL - Structured query language introduction
Smriti Jain
 
PPTX
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Basic SQL and History
SomeshwarMoholkar
 
DOCX
SQL Differences SQL Interview Questions
MLR Institute of Technology
 
PDF
Sql commands
Prof. Dr. K. Adisesha
 
PPTX
Sql basics
Raghu nath
 
PPTX
SQL commands
GirdharRatne
 
PPTX
Introduction to mysql part 1
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Introduction to SQL
Ehsan Hamzei
 
PPTX
What is SQL Server?
CPD INDIA
 
PPTX
SQL for interview
Aditya Kumar Tripathy
 
PPTX
Sql Basics And Advanced
rainynovember12
 
PPT
Introduction to-sql
BG Java EE Course
 
Sql intro & ddl 1
Dr. C.V. Suresh Babu
 
Database queries
IIUM
 
New T-SQL Features in SQL Server 2012
Richie Rump
 
SQL Commands
Sachidananda M H
 
Using T-SQL
Antonios Chatzipavlis
 
Sql a practical introduction
Hasan Kata
 
SQL - Structured query language introduction
Smriti Jain
 
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Basic SQL and History
SomeshwarMoholkar
 
SQL Differences SQL Interview Questions
MLR Institute of Technology
 
Sql commands
Prof. Dr. K. Adisesha
 
Sql basics
Raghu nath
 
SQL commands
GirdharRatne
 
Introduction to SQL
Ehsan Hamzei
 
What is SQL Server?
CPD INDIA
 
SQL for interview
Aditya Kumar Tripathy
 
Sql Basics And Advanced
rainynovember12
 
Introduction to-sql
BG Java EE Course
 

Viewers also liked (6)

PPT
Dating Game - T-SQL for High School Girls
Lynn Langit
 
PPTX
MS SQL SERVER: Getting Started With Sql Server 2008
sqlserver content
 
PPT
Mcts chapter 2
Sadegh Nakhjavani
 
PPTX
70-461 Querying Microsoft SQL Server 2012
siphocha
 
PDF
Writing and optimizing T-SQL
Vatroslav Mileusnić
 
PPTX
10 Ways To Abuse T-SQL
Tracy McKibben
 
Dating Game - T-SQL for High School Girls
Lynn Langit
 
MS SQL SERVER: Getting Started With Sql Server 2008
sqlserver content
 
Mcts chapter 2
Sadegh Nakhjavani
 
70-461 Querying Microsoft SQL Server 2012
siphocha
 
Writing and optimizing T-SQL
Vatroslav Mileusnić
 
10 Ways To Abuse T-SQL
Tracy McKibben
 
Ad

Similar to Intro to T-SQL – 2nd session (20)

PPT
Intro To TSQL - Unit 1
iccma
 
PPT
Intro to tsql unit 1
Syed Asrarali
 
PPT
Intro to tsql unit 2
Syed Asrarali
 
PPT
Intro To TSQL - Unit 2
iccma
 
DOCX
Learning sql from w3schools
farhan516
 
PPTX
Practical 03 (1).pptx
solangiirfan92
 
DOC
Introduction to sql
SARVESH KUMAR
 
PPT
The Basic of Standard Query Language Statements.ppt
HajarMeseehYaseen
 
PPT
Transact SQL (T-SQL) for Beginners (A New Hope)
Andrea Allred
 
DOCX
Sql
Archana Rout
 
PPTX
Sql intro
glubox
 
PDF
Basics of SELECT Statement - Oracle SQL
MuhammadWaheed44
 
PDF
Basic sqlstatements
Subash T
 
DOC
ORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDS
Newyorksys.com
 
PPTX
Lecture02_IDB.pptx
MostafizurRahaman41
 
PDF
COIS 420 - Practice01
Angel G Diaz
 
PDF
SQL Basics and Advanced for analytics.pdf
trg4294
 
PDF
SQL_BASIC AND ADVANCED.pdf
fayoyiwababajide
 
PPTX
Beginers guide for oracle sql
N.Jagadish Kumar
 
PPT
SQL select statement and functions
Vikas Gupta
 
Intro To TSQL - Unit 1
iccma
 
Intro to tsql unit 1
Syed Asrarali
 
Intro to tsql unit 2
Syed Asrarali
 
Intro To TSQL - Unit 2
iccma
 
Learning sql from w3schools
farhan516
 
Practical 03 (1).pptx
solangiirfan92
 
Introduction to sql
SARVESH KUMAR
 
The Basic of Standard Query Language Statements.ppt
HajarMeseehYaseen
 
Transact SQL (T-SQL) for Beginners (A New Hope)
Andrea Allred
 
Sql intro
glubox
 
Basics of SELECT Statement - Oracle SQL
MuhammadWaheed44
 
Basic sqlstatements
Subash T
 
ORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDS
Newyorksys.com
 
Lecture02_IDB.pptx
MostafizurRahaman41
 
COIS 420 - Practice01
Angel G Diaz
 
SQL Basics and Advanced for analytics.pdf
trg4294
 
SQL_BASIC AND ADVANCED.pdf
fayoyiwababajide
 
Beginers guide for oracle sql
N.Jagadish Kumar
 
SQL select statement and functions
Vikas Gupta
 
Ad

More from Medhat Dawoud (11)

PDF
Real time web
Medhat Dawoud
 
PPTX
Using Git and BitBucket
Medhat Dawoud
 
PDF
Introduction to linux
Medhat Dawoud
 
PPTX
Select your career
Medhat Dawoud
 
PPTX
Mesh cloud (road to mongoDB)
Medhat Dawoud
 
PPTX
Before start
Medhat Dawoud
 
PPTX
DevMix Startup
Medhat Dawoud
 
PPTX
Threading in C#
Medhat Dawoud
 
PPTX
How to python
Medhat Dawoud
 
PPTX
Program threats
Medhat Dawoud
 
PPTX
Unusual C# - OOP
Medhat Dawoud
 
Real time web
Medhat Dawoud
 
Using Git and BitBucket
Medhat Dawoud
 
Introduction to linux
Medhat Dawoud
 
Select your career
Medhat Dawoud
 
Mesh cloud (road to mongoDB)
Medhat Dawoud
 
Before start
Medhat Dawoud
 
DevMix Startup
Medhat Dawoud
 
Threading in C#
Medhat Dawoud
 
How to python
Medhat Dawoud
 
Program threats
Medhat Dawoud
 
Unusual C# - OOP
Medhat Dawoud
 

Recently uploaded (20)

PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
community health nursing question paper 2.pdf
Prince kumar
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 

Intro to T-SQL – 2nd session

  • 1. T-SQL – 2nd sessionMedhatDawoudhttp://[email protected]@Med7atDawoud
  • 2. AgendaSelect the DBMS we will useSelect Database to work onPUBS DatabaseDatabases and tablesConnecting to your databaseChange databasesSome rules for SQLOverview of PUBS databaseFirst Select Command
  • 3. Agenda cont.Concatenate two columnsAliasWhere & compound criteriaComparison operatorsRangeWild cardsEscape charactersPattern matchingNegation
  • 4. Database Management SystemThere are many RDBMSs that is used such as:Oracle
  • 8.
  • 9. etc.In this class we will use the SQL serveras our DBMS, Because it’s the most interactive one in out case.
  • 10. SQL server 2005 or 2008We need a SQLserver to interact with Database through queries as DBMS.Download from :http://www.microsoft.com/sqlserver/2005/en/us/express.aspxWe need any version of SQL server(2005 or 2008).
  • 11. Select Database to work onI selected the Northwindsimple database to make our queries on.You can download it from:http://www.microsoft.com/downloads/en/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034
  • 13. DatabasesAt the most basic level a database is really just a file.
  • 14. Databases come in all shapes and sizes. Some are large and some are small. But each database generally serves a particular purpose.
  • 15. Examples: Tracking employee payroll, sales data on a particular sales line, stock data for a particular industry
  • 16. All databases are made up of objects. The most important object (and the one we will learn how to use in this class) is a table.TablesA table is a storage structure made up of rows and columns. (Sort of like a spreadsheet.)
  • 17. Due to the differing terminologies, there are interchangeable sets of terms:Database Mathematical Data Processing Table Relation File Row Tuple Record Column Attribute FieldThese terms are used interchangeably, but we will generally use the table – row – column terminologyConnectto a databaseA query as the term implies is a question we ask the database.
  • 18. The same procedure gives the same result with the same database in any other DBMS.
  • 19. Regardless of name, they all perform the same purpose. This is to give you an interface for sending SQL statements and receiving results.SQL Server LoginStartup ISQL/WLogin windowA SQL Server can have many different databases running on it at the same time. Database setup on the server Assign databasesYour first SQL statementuse <database>This tells the SQL Server what database you will be using to perform your queries.Example: use PUBS1
  • 20. Verify your databaseTo check the database you are accessing use:select db_name()Throughout this course some of the things we discuss will be MS SQL Server specific. The DBMS you are using should have a command or function similar to this, but not necessarily the same.
  • 21. Basic syntax rulesSQL keywords (use, select, from, where, etc.) are case insensitive.
  • 22. select is the same as SELECT is the same as SeLeCt, etc.
  • 23. However depending on the DBMS (Database Management System), the columns might be case sensitive.
  • 24. The databases we have setup on our server are case insensitive.Rules cont.Spacing does not matter (for the most part).
  • 25. select CustomerID…is the same asselect CustomerID …However, you must still separate words. You can not use the following:selectCustomerID… This will give a syntax error, because SQL Server must be able to find your SQL keywords.
  • 27. select CustomerID from Customers is the same asselect CustomerID from CustomersThe spacing and carriage returns just make reading your SQL a lot easier.
  • 28. The general format used by most people is to place the separate clausesof the statement on different linesPUBS DatabaseThis is the database for which you have an ER diagram for.
  • 30. You will generally get an ER diagram at each client when you begin work on a project. If you don’t have one, ask for one. This will save time in trying to determine what data is where and how everything is linked together. If you can’t get one, don’t panic! There are ways to get the database to tell you what it contains.PUBS Database example
  • 31. Ok, Lets talk about commands (Queries)
  • 32. SelectA select statement is used to retrieve data from a database.
  • 33. In order to get information from the database, you must tell the database what you are looking for. The first step along this journey is to get some simple information from the database.
  • 34. select 'Mary had a little lamb.'--------------Mary had a little lamb.(1 row affected)
  • 35. SelectAn asterisk (*) is used to designate all columns in a table.select *We also need to tell it which table to get the data from.select * from authorsThe main sections in every SQL statement are called clauses. The three clauses we will focus on are the select, from, and where
  • 36. We can limit the columns returned by specifying them instead of using *.select author_id , author_name from authors
  • 37. ConcatenationWe can also combine data together. This is called concatenation.
  • 38. We really want to display the first name and the last name separated by a space and then the rest of the data. The plus symbol (+) is the most widely used symbol for concatenation.
  • 39. Concatenation is used for string (character) data. If a concatenation operator (+) is used on numeric data, the data is simply added together.The title for our previous result set isn't too informative, and we really don't want to display our formula.
  • 40. We can rename or alias a column in two ways
  • 41. Use a space and then the alias
  • 42. Specify the keyword as and then the alias
  • 43. We can apply aliases in two places within our SQL statements
  • 46. WhereSo far we have returned the entire contents of a table.This is usually not very practicalSuppose we wanted to see the authors that live in California.We could do a select * from authors and scroll through the result set looking for those where state = CAWhile feasible for a small table, this is not practical.
  • 47. Compound criteriaThis limited our result set to just those authors in CABut our list of authors could begin to get very large and we’re only looking for those authors with a last name of Green.We would do this with the following: select au_lname, au_fname, state from authors where state = 'CA' and lname = 'Green'Important Note : our DBMS might be case insensitive but the actual values of the data is case sensitive.So, Greennotequal to GREEN
  • 48. Compound criteriaNow that we know how to get just those authors who live in CA, how do we get the authors that live in KS also?We accomplish this through the use of an OR instead of an ANDselect * from authors where state = 'CA' or state = 'KS'
  • 49. Compound criteriaSo, what is the difference between using an ANDand an OR?The AND is exclusiveThis means that the row must meet all of the conditions in order to be selectedThe OR is inclusiveThis means that for a row to be selected, it has to meet just one of the criteria
  • 50. Compound criteriaYou group by using parenthesisThe proper SQL statement is as follows:select * from authors where (state = 'KS' and lname = 'Smith') or state = 'CA'Note that: this is differ from the group by clause that will be discussed later in this class
  • 51. ComparisonBesides using an =, you can also use any of the other comparison operators: >, <, <=, >=,<>.If you want to get employees whose salary greater than 2000.It will be:select * from employees where salary > 2000
  • 52. RangeSuppose we want to select all authors who live in CA, MI, KS, and UT.. What will you do ??Instead of using multiple ORs, we can use an INoperator select au_lname, state from authors where state in ('CA','KS','MI','UT')
  • 53. RangeWe now want to select all books that have a price greater than or equal to $10, but also less than or equal to $20.. What will you do ?SQL has given us a betweenoperatorselect title_id, price from titles where price between 10 and 20
  • 54. Wild CardsSQL has two wildcard charactersThe percent (%) symbol designates any string of zero or more charactersThe underscore (_) designates a single characterSuppose we wanted to select all authors whose first names start with Mselect au_fname, au_lname from authors where au_fname like 'M%'
  • 55. Escape CharactersBut what happens when we really want to find a % inside of the dataTo find this data we will employ an escape characterselect notes from titles where notes like '%@%%' escape '@'This tells the DBMS to treat the next character after the escape character (@) as a literal string
  • 56. Pattern MatchingSuppose we wanted to retrieve all of the authors whose last names started with either an L, M, or Sselect au_lname, au_fname from authors where au_lname like '[LMS]%‘We do not want to retrieve name names like McDayselect au_lname, au_fname from authors where au_lname like '[A-Z][a-z][a-z][a-z]'
  • 57. Pattern MatchingWe now want to retrieve just those authors whose first name is four characters longselect au_lname, au_fname from authors where au_fname like '____' (That's four underscore characters)---------------------------------------------------------------------select * from authors where au_fnamelike '[^ ] [^ ] [^ ] [^ ]‘The caret is a negation operator. The query above says to retrieve any first names that do not have a space as one of the four characters
  • 58. NegationWe briefly touched on negation a few slides before.The negation operator is NOT or in patterns a caret (^)select au_fname, au_lname from authors where au_fname not like '[^ ] [^ ] [^ ] [^ ]'Select all authors who do not live in CAselect * from authors where state <> 'CA'
  • 60. OkLets Query** Means to write queries in SQL server