SlideShare a Scribd company logo
1 of 8
7/9/2013 SQL Server Basics
Yousuf Ibn Akhtar Sultan
Yousuf Ibn Akhtar Sultan
SQL SERVER BASICS
SQL BASICS
CREATE statement – to create a new table
SYNTAX:
For creating a Database - CREATE DATABASE database_name
For creating a Table –
CREATE TABLE table_name
( column_name1 datatype,
Column_name2 datatype,
.
.
.
)
DROP statement – to drop a table
SYNTAX:
For deleting a table – DROP TABLE table_name
For deleting a database – DROP DATABASE database_name
TRUNCATING a Table – TRUNCATE TABLE table_name
Difference between DROP and TRUNCATE is that DROP is used to delete the entire table along with its
data whereas TRUNCATE is used to just delete the data from the table and the structure remains the
same.
ALTER statement – to add, delete or modify columns in a table
SYNTAX:
To add a column: ALTER TABLE table_name ADD column_name datatype
To delete a column: ALTER TABLE table_name DROP COLUMN column_name
To change data type: ALTER TABLE table_name ALTER COLUMN column_name datatype
To create a PRIMARY KEY after table has been created:
ALTER TABLE table_name
ADD PRIMARY KEY (column_name)
If you want to give a name for the primary key:
ALTER TABLE table_name
ADD CONSTRAINT primary_key_name
PRIMARY KEY (column_name)
To drop a PRIMARY KEY with a name: ALTER TABLE table_name
DROP CONSTRAINT primary_key_name
To create a FOREIGN KEY after the table has been created:
ALTER TABLE table_name
ADD FOREIGN KEY (column_name)
REFERENCES table_name(target_references_primary_key)
To create a FOREIGN KEY with a name: ALTER TABLE table_name
ADD CONSTRAINT foreign_key_name
FOREIGN KEY column_name
Yousuf Ibn Akhtar Sultan
SQL SERVER BASICS
REFERENCES table_name(target_references_primary_key)
To drop a FOREIGN KEY: ALTER TABLE table_name
DROP CONSTRAINT foreign_key_name
SP_HELP – to check the structure of the table, e.g, the column names, the data types, the constraints,
etc.
INSERT statements: used to INSERT data into table
SYNTAX:
INSERT INTO table_name VALUES (column1_value, column2_value,……., column’n’_value)
DELETE statements: used to DELETE a row from a table
SYNTAX:
DELETE FROM table_name
WHERE <condition/s>
To delete all data from a table
SYNTAX:
DELETE FROM table_name OR DELETE * FROM table_name
**This query has a similar functionality as TRUNCATE statement
UPDATE statements: used to update an existing record
SYNTAX:
UPDATE table_name
SET column1 = value, column2 = value, ……
WHERE <condition>
SELECT statements: used to select data from database. The result is stored in a result table, called as
result-set. There are different types of SELECTs
Type 1: (Simple SELECT without any conditions)
SYNTAX:
SELECT column_name/s
FROM table_name
If you want to see all the column names, you can either give all the column names in the SELECT clause
or use the following:
SELECT * FROM table_name
Type 2: SELECT DISTINCT – this would display only the distinct values if a column has a duplicate value.
SYNTAX:
SELECT DISTINCT column_name/s
FROM table_name
Type 3: SELECT statement with a WHERE clause – to extract those records depending on a condition
SYNTAX:
SELECT column_name/s
FROM table_name
WHERE <condition/s>
Yousuf Ibn Akhtar Sultan
SQL SERVER BASICS
Type 4: SELECT with ORDER BY clause – to sort the result-set by one or more columns
SYNTAX:
SELECT column/s
FROM table_name
WHERE <condition/s>
ORDER BY column_name/s ASC|DESC
*ASC – Ascending, DESC – Descending
** Default sorting order is ascending, if you don’t mention anything in the ORDER BY clause
Type 5: SELECT TOP – used to specify the number of records to return
SYNTAX:
SELECT TOP number|percent column_name
FROM table_name
Type 6: SELECT with LIKE operator – used to search for a specified pattern in a column
SYNTAX:
SELECT column_name/s
FROM table_name
WHERE column_name LIKE pattern
e.g.
SELECT *
FROM contact
WHERE name LIKE ‘S%’ – this would return all contacts whose name begins with S
Type 7: SELECT with IN operator – allows to specify multiple values in the WHERE clause
SYNTAX:
SELECT column_name/s
FROM table_name
WHERE column_name IN (value/s)
e.g
SELECT *
FROM contact
WHERE city IN (‘Kalimpong’,’Kolkata’) – this would return all contacts who are from the cities
Kalimpong and Kolkata
Type 8: SELECT with BETWEEN operator – this selects a value within a range. The values can be number,
text or dates
SYNTAX:
SELECT column_name/s
FROM table_name
WHERE column_name BETWEEN value1 AND value2
e.g.
SELECT *
FROM products
WHERE price BETWEEN 50 AND 150
Yousuf Ibn Akhtar Sultan
SQL SERVER BASICS
NOT BETWEEN operator
e.g.
SELECT * FROM products WHERE price NOT BETWEEN 50 AND 150
BETWEEN operator with IN
e.g.
SELECT * FROM products
WHERE (price BETWEEN 10 AND 20) AND NOT categoryID NOT IN (1,2,3)
Aggregate Functions
• AVG() – returns the average value
• COUNT() – returns the number of rows
• MAX() – returns the largest value
• MIN() – returns the smallest value
• SUM() – returns the sum
SELECT with GROUP BY clause – used along with the aggregate functions to group the result set by one
or more columns
SYNTAX:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE <condition>
GROUP BY column_name
e.g.
SELECT deptno,count(deptno)
FROM emp
GROUP BY deptno
SELECT with HAVING clause – it is used as a filter to the GROUP BY clause and it cannot be used without
an aggregate function
SYNTAX:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE <condition/s>
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
e.g.
SELECT deptno,count(deptno)
FROM emp
GROUP BY deptno
HAVING count(deptno) > 4
Yousuf Ibn Akhtar Sultan
SQL SERVER BASICS
SELECT INTO statement – used to copy information from one table to another. It copies data from one
table and inserts into a new table
SYNTAX:
SELECT column_name/s
INTO new_table_name
FROM old_table_name
Eg.
SELECT *
INTO emp_new
FROM emp
INSERT INTO statement – used to copy columns from one table to another existing table
SYNTAX:
INSERT INTO table2_name
SELECT column_name/s FROM table1_name
NOT NULL constraint – it enforces a column NOT to accept a NULL value
UNIQUE constraint – it uniquely identifies each record in a database table
ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column_name/s)
ALTER TABLE table_name ADD CONSTRAINT constraint_name
CHECK constraint – is used to limit the range value that can be placed in a column
e.g
CREATE TABLE persons
( p_id int,
Last_name varchar(30),
First_name varchar(30),
Gender varchar(1),
CHECK (Gender IN (‘M’,’F’)))
ALTER TABLE table_name
ADD CHECK (condition/s)
ALTER TABLE table_name
ADD CONSTRAINT constraint_name CHECK (condition/s)
ALTER TABLE table_name
DROP CONSTRAINT constraint_name
To check the structure of a table: SP_HELP table_name
To check the tables in a database: SELECT name FROM sys.tables
SQL syntax to get an output using ESCAPE clause
E.g. if you want to get a output from a table where a name has a ‘%’ symbol in it.
SYNTAX: SELECT * FROM emp
WHERE ename LIKE (‘%%%’) ESCAPE ‘’
Yousuf Ibn Akhtar Sultan
SQL SERVER BASICS
JOINS
SQL JOIN is used to combine rows from two or more tables based on the common column field between
them.
The different types of JOINs are: -
I) INNER JOIN: Returns all rows when there is at least one match in BOTH tables
II) LEFT OUTER JOIN: Return all rows from the left table, and the matched rows from the right
table
III) RIGHT OUTER JOIN: Return all rows from the right table, and the matched rows from the
left table
IV) FULL OUTER JOIN: Return all rows when there is a match in ONE of the tables
INNER JOIN: selects all rows from both tables as long as there is a match between the columns in both
tables.
SYNTAX FOR INNER JOIN:
SELECT column_name/s
FROM table1 INNER JOIN table2
WHERE table1.column_name = table2.column_name
LEFT OUTER JOIN: returns all rows from the left table (table1), with the matching rows in the right table
(table2). The result is NULL in the right side when there is no match.
SYNTAX FOR LEFT OUTER JOIN:
SELECT column_name/s
FROM table1 LEFT OUTER JOIN table2
WHERE table1.column_name = table2.column_name
RIGHT OUTER JOIN: returns all rows from the right table (table2), with the matching rows in the left
table (table1). The result is NULL in the left side when there is no match.
SYNTAX FOR RIGHT OUTER JOIN:
SELECT column_name/s
FROM table1 RIGHT OUTER JOIN table2
WHERE table1.column_name = table2.column_name
FULL OUTER JOIN: returns all rows from the left table (table1) and from the right table (table2). The
FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
SYNTAX FOR FULL OUTER JOIN:
SELECT column_name/s
FROM table1 FULL OUTER JOIN table2
WHERE table1.column_name = table2.column_name
UNION: 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.
SYNTAX FOR UNION:
SELECT column_name/s FROM table1
UNION
SELECT column_name/s FROM table2
Yousuf Ibn Akhtar Sultan
SQL SERVER BASICS
VIEWS
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more
real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data
were coming from one single table.
SYNTAX FOR CREATING A VIEW:
CREATE VIEW view_name AS
SELECT statement
SYNTAX FOR DROPPING A VIEW:
DROP VIEW view_name
SYNONYM
Synonyms are objects in SQL Server that gives an Alias name to a table or a view. There happens
sometimes that the table names are very long and difficult to remember, in such cases we can give an
Alias name for the table using Synonyms.
SYNTAX FOR CREATING A SYNONYM:
CREATE [PUBLIC/PRIVATE] SYNONYM new_name FOR old_name
To Re-name a table:
SP_RENAME ‘old_table_name’ ’new_table_name’
To Re-name a column:
SP_RENAME ‘table_name.column_name’ ‘new_column_name’

More Related Content

What's hot

SQL : Structured Query Language
SQL : Structured Query LanguageSQL : Structured Query Language
SQL : Structured Query LanguageAbhishek Gautam
 
Excel Tutorials - VLOOKUP and HLOOKUP Functions
Excel Tutorials - VLOOKUP and HLOOKUP FunctionsExcel Tutorials - VLOOKUP and HLOOKUP Functions
Excel Tutorials - VLOOKUP and HLOOKUP FunctionsMerve Nur Taş
 
Data Definition Language (DDL)
Data Definition Language (DDL) Data Definition Language (DDL)
Data Definition Language (DDL) Mohd Tousif
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL FundamentalsBrian Foote
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)Ishucs
 
MIRCROSOFT EXCEL- brief and useful for beginners by RISHABH BANSAL
MIRCROSOFT EXCEL- brief and useful for beginners by RISHABH BANSALMIRCROSOFT EXCEL- brief and useful for beginners by RISHABH BANSAL
MIRCROSOFT EXCEL- brief and useful for beginners by RISHABH BANSALRishabh Bansal
 
Solutions manual for guide to sql 9th edition by pratt
Solutions manual for guide to sql 9th edition by prattSolutions manual for guide to sql 9th edition by pratt
Solutions manual for guide to sql 9th edition by prattAldis8862
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1Swapnali Pawar
 
Fill series. Data validation. Excel Tutorial
Fill series. Data validation. Excel TutorialFill series. Data validation. Excel Tutorial
Fill series. Data validation. Excel TutorialIlgar Zarbaliyev
 
Basic sqlstatements
Basic sqlstatementsBasic sqlstatements
Basic sqlstatementsAnjac
 

What's hot (20)

MULTIPLE TABLES
MULTIPLE TABLES MULTIPLE TABLES
MULTIPLE TABLES
 
SQL : Structured Query Language
SQL : Structured Query LanguageSQL : Structured Query Language
SQL : Structured Query Language
 
Excel Tutorials - VLOOKUP and HLOOKUP Functions
Excel Tutorials - VLOOKUP and HLOOKUP FunctionsExcel Tutorials - VLOOKUP and HLOOKUP Functions
Excel Tutorials - VLOOKUP and HLOOKUP Functions
 
Data Definition Language (DDL)
Data Definition Language (DDL) Data Definition Language (DDL)
Data Definition Language (DDL)
 
SQL
SQLSQL
SQL
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
Sql Tags
Sql TagsSql Tags
Sql Tags
 
Mastering Excel Formulas and Functions
Mastering Excel Formulas and FunctionsMastering Excel Formulas and Functions
Mastering Excel Formulas and Functions
 
SQL UNION
SQL UNIONSQL UNION
SQL UNION
 
MIRCROSOFT EXCEL- brief and useful for beginners by RISHABH BANSAL
MIRCROSOFT EXCEL- brief and useful for beginners by RISHABH BANSALMIRCROSOFT EXCEL- brief and useful for beginners by RISHABH BANSAL
MIRCROSOFT EXCEL- brief and useful for beginners by RISHABH BANSAL
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Ddl commands
Ddl commandsDdl commands
Ddl commands
 
Solutions manual for guide to sql 9th edition by pratt
Solutions manual for guide to sql 9th edition by prattSolutions manual for guide to sql 9th edition by pratt
Solutions manual for guide to sql 9th edition by pratt
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 
Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
 
Fill series. Data validation. Excel Tutorial
Fill series. Data validation. Excel TutorialFill series. Data validation. Excel Tutorial
Fill series. Data validation. Excel Tutorial
 
Sql reference from w3 schools
Sql reference from w3 schools Sql reference from w3 schools
Sql reference from w3 schools
 
MySQL JOIN & UNION
MySQL JOIN & UNIONMySQL JOIN & UNION
MySQL JOIN & UNION
 
Basic sqlstatements
Basic sqlstatementsBasic sqlstatements
Basic sqlstatements
 

Viewers also liked

Bases de datos access
Bases de datos accessBases de datos access
Bases de datos accessChars Orden
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handoutsjhe04
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)MongoDB
 
Optimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and CreativityOptimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and CreativityMongoDB
 

Viewers also liked (9)

Bases de datos access
Bases de datos accessBases de datos access
Bases de datos access
 
SQL
SQLSQL
SQL
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handouts
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)
 
Optimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and CreativityOptimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and Creativity
 
Sql intro
Sql introSql intro
Sql intro
 
Access
AccessAccess
Access
 
Sql
SqlSql
Sql
 
Consultas en access
Consultas en accessConsultas en access
Consultas en access
 

Similar to Sql basics v2

Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01sagaroceanic11
 
SQL Tutorial for Beginners
SQL Tutorial for BeginnersSQL Tutorial for Beginners
SQL Tutorial for BeginnersAbdelhay Shafi
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries Prabu Cse
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxjainendraKUMAR55
 
SQL COMMANDS WITH EXAMPLES.pptx
SQL COMMANDS WITH EXAMPLES.pptxSQL COMMANDS WITH EXAMPLES.pptx
SQL COMMANDS WITH EXAMPLES.pptxBikalpa Thapa
 
Join in SQL - Inner, Self, Outer Join
Join in SQL - Inner, Self, Outer JoinJoin in SQL - Inner, Self, Outer Join
Join in SQL - Inner, Self, Outer JoinSouma Maiti
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commandsBelle Wx
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive TechandMate
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)Huda Alameen
 
Mysql Statments
Mysql StatmentsMysql Statments
Mysql StatmentsSHC
 

Similar to Sql basics v2 (20)

Babitha2.mysql
Babitha2.mysqlBabitha2.mysql
Babitha2.mysql
 
Babitha2 Mysql
Babitha2 MysqlBabitha2 Mysql
Babitha2 Mysql
 
Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01
 
SQL Tutorial for Beginners
SQL Tutorial for BeginnersSQL Tutorial for Beginners
SQL Tutorial for Beginners
 
MY SQL
MY SQLMY SQL
MY SQL
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries
 
SQL
SQLSQL
SQL
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
 
SQL COMMANDS WITH EXAMPLES.pptx
SQL COMMANDS WITH EXAMPLES.pptxSQL COMMANDS WITH EXAMPLES.pptx
SQL COMMANDS WITH EXAMPLES.pptx
 
DBMS.pdf
DBMS.pdfDBMS.pdf
DBMS.pdf
 
Join in SQL - Inner, Self, Outer Join
Join in SQL - Inner, Self, Outer JoinJoin in SQL - Inner, Self, Outer Join
Join in SQL - Inner, Self, Outer Join
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Sql commands
Sql commandsSql commands
Sql commands
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)
 
Mysql cheatsheet
Mysql cheatsheetMysql cheatsheet
Mysql cheatsheet
 
Mysql Statments
Mysql StatmentsMysql Statments
Mysql Statments
 
Query
QueryQuery
Query
 
dbms.pdf
dbms.pdfdbms.pdf
dbms.pdf
 

Recently uploaded

Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 

Recently uploaded (20)

Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 

Sql basics v2

  • 1. 7/9/2013 SQL Server Basics Yousuf Ibn Akhtar Sultan
  • 2. Yousuf Ibn Akhtar Sultan SQL SERVER BASICS SQL BASICS CREATE statement – to create a new table SYNTAX: For creating a Database - CREATE DATABASE database_name For creating a Table – CREATE TABLE table_name ( column_name1 datatype, Column_name2 datatype, . . . ) DROP statement – to drop a table SYNTAX: For deleting a table – DROP TABLE table_name For deleting a database – DROP DATABASE database_name TRUNCATING a Table – TRUNCATE TABLE table_name Difference between DROP and TRUNCATE is that DROP is used to delete the entire table along with its data whereas TRUNCATE is used to just delete the data from the table and the structure remains the same. ALTER statement – to add, delete or modify columns in a table SYNTAX: To add a column: ALTER TABLE table_name ADD column_name datatype To delete a column: ALTER TABLE table_name DROP COLUMN column_name To change data type: ALTER TABLE table_name ALTER COLUMN column_name datatype To create a PRIMARY KEY after table has been created: ALTER TABLE table_name ADD PRIMARY KEY (column_name) If you want to give a name for the primary key: ALTER TABLE table_name ADD CONSTRAINT primary_key_name PRIMARY KEY (column_name) To drop a PRIMARY KEY with a name: ALTER TABLE table_name DROP CONSTRAINT primary_key_name To create a FOREIGN KEY after the table has been created: ALTER TABLE table_name ADD FOREIGN KEY (column_name) REFERENCES table_name(target_references_primary_key) To create a FOREIGN KEY with a name: ALTER TABLE table_name ADD CONSTRAINT foreign_key_name FOREIGN KEY column_name
  • 3. Yousuf Ibn Akhtar Sultan SQL SERVER BASICS REFERENCES table_name(target_references_primary_key) To drop a FOREIGN KEY: ALTER TABLE table_name DROP CONSTRAINT foreign_key_name SP_HELP – to check the structure of the table, e.g, the column names, the data types, the constraints, etc. INSERT statements: used to INSERT data into table SYNTAX: INSERT INTO table_name VALUES (column1_value, column2_value,……., column’n’_value) DELETE statements: used to DELETE a row from a table SYNTAX: DELETE FROM table_name WHERE <condition/s> To delete all data from a table SYNTAX: DELETE FROM table_name OR DELETE * FROM table_name **This query has a similar functionality as TRUNCATE statement UPDATE statements: used to update an existing record SYNTAX: UPDATE table_name SET column1 = value, column2 = value, …… WHERE <condition> SELECT statements: used to select data from database. The result is stored in a result table, called as result-set. There are different types of SELECTs Type 1: (Simple SELECT without any conditions) SYNTAX: SELECT column_name/s FROM table_name If you want to see all the column names, you can either give all the column names in the SELECT clause or use the following: SELECT * FROM table_name Type 2: SELECT DISTINCT – this would display only the distinct values if a column has a duplicate value. SYNTAX: SELECT DISTINCT column_name/s FROM table_name Type 3: SELECT statement with a WHERE clause – to extract those records depending on a condition SYNTAX: SELECT column_name/s FROM table_name WHERE <condition/s>
  • 4. Yousuf Ibn Akhtar Sultan SQL SERVER BASICS Type 4: SELECT with ORDER BY clause – to sort the result-set by one or more columns SYNTAX: SELECT column/s FROM table_name WHERE <condition/s> ORDER BY column_name/s ASC|DESC *ASC – Ascending, DESC – Descending ** Default sorting order is ascending, if you don’t mention anything in the ORDER BY clause Type 5: SELECT TOP – used to specify the number of records to return SYNTAX: SELECT TOP number|percent column_name FROM table_name Type 6: SELECT with LIKE operator – used to search for a specified pattern in a column SYNTAX: SELECT column_name/s FROM table_name WHERE column_name LIKE pattern e.g. SELECT * FROM contact WHERE name LIKE ‘S%’ – this would return all contacts whose name begins with S Type 7: SELECT with IN operator – allows to specify multiple values in the WHERE clause SYNTAX: SELECT column_name/s FROM table_name WHERE column_name IN (value/s) e.g SELECT * FROM contact WHERE city IN (‘Kalimpong’,’Kolkata’) – this would return all contacts who are from the cities Kalimpong and Kolkata Type 8: SELECT with BETWEEN operator – this selects a value within a range. The values can be number, text or dates SYNTAX: SELECT column_name/s FROM table_name WHERE column_name BETWEEN value1 AND value2 e.g. SELECT * FROM products WHERE price BETWEEN 50 AND 150
  • 5. Yousuf Ibn Akhtar Sultan SQL SERVER BASICS NOT BETWEEN operator e.g. SELECT * FROM products WHERE price NOT BETWEEN 50 AND 150 BETWEEN operator with IN e.g. SELECT * FROM products WHERE (price BETWEEN 10 AND 20) AND NOT categoryID NOT IN (1,2,3) Aggregate Functions • AVG() – returns the average value • COUNT() – returns the number of rows • MAX() – returns the largest value • MIN() – returns the smallest value • SUM() – returns the sum SELECT with GROUP BY clause – used along with the aggregate functions to group the result set by one or more columns SYNTAX: SELECT column_name, aggregate_function(column_name) FROM table_name WHERE <condition> GROUP BY column_name e.g. SELECT deptno,count(deptno) FROM emp GROUP BY deptno SELECT with HAVING clause – it is used as a filter to the GROUP BY clause and it cannot be used without an aggregate function SYNTAX: SELECT column_name, aggregate_function(column_name) FROM table_name WHERE <condition/s> GROUP BY column_name HAVING aggregate_function(column_name) operator value e.g. SELECT deptno,count(deptno) FROM emp GROUP BY deptno HAVING count(deptno) > 4
  • 6. Yousuf Ibn Akhtar Sultan SQL SERVER BASICS SELECT INTO statement – used to copy information from one table to another. It copies data from one table and inserts into a new table SYNTAX: SELECT column_name/s INTO new_table_name FROM old_table_name Eg. SELECT * INTO emp_new FROM emp INSERT INTO statement – used to copy columns from one table to another existing table SYNTAX: INSERT INTO table2_name SELECT column_name/s FROM table1_name NOT NULL constraint – it enforces a column NOT to accept a NULL value UNIQUE constraint – it uniquely identifies each record in a database table ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column_name/s) ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK constraint – is used to limit the range value that can be placed in a column e.g CREATE TABLE persons ( p_id int, Last_name varchar(30), First_name varchar(30), Gender varchar(1), CHECK (Gender IN (‘M’,’F’))) ALTER TABLE table_name ADD CHECK (condition/s) ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK (condition/s) ALTER TABLE table_name DROP CONSTRAINT constraint_name To check the structure of a table: SP_HELP table_name To check the tables in a database: SELECT name FROM sys.tables SQL syntax to get an output using ESCAPE clause E.g. if you want to get a output from a table where a name has a ‘%’ symbol in it. SYNTAX: SELECT * FROM emp WHERE ename LIKE (‘%%%’) ESCAPE ‘’
  • 7. Yousuf Ibn Akhtar Sultan SQL SERVER BASICS JOINS SQL JOIN is used to combine rows from two or more tables based on the common column field between them. The different types of JOINs are: - I) INNER JOIN: Returns all rows when there is at least one match in BOTH tables II) LEFT OUTER JOIN: Return all rows from the left table, and the matched rows from the right table III) RIGHT OUTER JOIN: Return all rows from the right table, and the matched rows from the left table IV) FULL OUTER JOIN: Return all rows when there is a match in ONE of the tables INNER JOIN: selects all rows from both tables as long as there is a match between the columns in both tables. SYNTAX FOR INNER JOIN: SELECT column_name/s FROM table1 INNER JOIN table2 WHERE table1.column_name = table2.column_name LEFT OUTER JOIN: returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match. SYNTAX FOR LEFT OUTER JOIN: SELECT column_name/s FROM table1 LEFT OUTER JOIN table2 WHERE table1.column_name = table2.column_name RIGHT OUTER JOIN: returns all rows from the right table (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match. SYNTAX FOR RIGHT OUTER JOIN: SELECT column_name/s FROM table1 RIGHT OUTER JOIN table2 WHERE table1.column_name = table2.column_name FULL OUTER JOIN: returns all rows from the left table (table1) and from the right table (table2). The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins. SYNTAX FOR FULL OUTER JOIN: SELECT column_name/s FROM table1 FULL OUTER JOIN table2 WHERE table1.column_name = table2.column_name UNION: 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. SYNTAX FOR UNION: SELECT column_name/s FROM table1 UNION SELECT column_name/s FROM table2
  • 8. Yousuf Ibn Akhtar Sultan SQL SERVER BASICS VIEWS In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table. SYNTAX FOR CREATING A VIEW: CREATE VIEW view_name AS SELECT statement SYNTAX FOR DROPPING A VIEW: DROP VIEW view_name SYNONYM Synonyms are objects in SQL Server that gives an Alias name to a table or a view. There happens sometimes that the table names are very long and difficult to remember, in such cases we can give an Alias name for the table using Synonyms. SYNTAX FOR CREATING A SYNONYM: CREATE [PUBLIC/PRIVATE] SYNONYM new_name FOR old_name To Re-name a table: SP_RENAME ‘old_table_name’ ’new_table_name’ To Re-name a column: SP_RENAME ‘table_name.column_name’ ‘new_column_name’