SlideShare a Scribd company logo
Introduction to
Microsoft SQL
Server
Presented by Abdelhay
WHAT IS SQL?
What is SQL?
SQL – Stands for Structured Query Language. SQL is used to
communicate a database. SQL statements are used to perform tasks
such as, update data in the database, retrieve data from the database.
• There are standard SQL commands such as, Insert, update, delete, select, create, drop
can be used to accomplish almost everything that one needs to do with the database.
01
What SQL can do?
With SQL you can:
• Execute queries against the database.
• Perform CRUD functions.
• CREATE – New database , new table in a database, new records
• READ – Retrieve data from the database
• UPDATE – Update existing records from the database
• DELETE – Delete records from the database
SQL Statements fit into two broad
categories
Data Definition Language (DDL) – Used to
define data structures and used to build and
modify the structures of your table and
other objects in the database. Use these
statement to Create, alter or drop data
structures from instance of the SQL server.
Data Manipulation Language (DML)
Statements are used to work with data
in tables. These statement includes,
Select, Insert, Update and Delete.
Script Examples of DDL and DML
CREATE – This statement creates database, tables, index etc.
CREATE TABLE <table name> (
<column_name 1> <data type 1>,
< column_name 2> <data type 2>);
ALTER – This statement used to modify data in the table.
ALTER TABLE <table name>
ADD CONSTRAINT <constraint name> PRIMARY KEY (<column_name>);
DROP – This statement used to drop existing table in a database.
DROP <table name> or
ALTER TABLE <table name>
DROP CONSTRAINT <constraint name>;
This Illustrates example statement of DDL
Script Examples of DDL and DML (Continued)
INSERT – Insert statement used to add new rows to the table.
E.g INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
The comma-delimited list of values must match the table structure exactly the numbers of columns.
Character data type should always enclosed in single quote.
UPDATE – The update statement is used to change values that are already in a table.
E.g UPDATE <table name>
SET <column> = <value>
WHERE <condition>;
DELETE – The delete statement does just that. (Be-careful on this statement)
E.g DELETE FROM <table name>
WHERE <condition>;
If the WHERE clause is omitted, then every row of the table is deleted (which usually not what we
want to do)
Script Examples of DDL and DML (Continued)
SELECT – This statement used to retrieve information from the table.
SELECT column1, column2, ...
FROM table_name;
If you want to select all the fields available in the table use this statement. The (*)
selects all the fields(columns) in the table.
SELECT * from table_name
(where clause) - The where clause (optional) specifies which data values or rows will
be returned or displayed, based on the criteria described after the keyword where.
SELECT * from table_name
Where column = <condition>
SQL Data Types
Data Type – specify what the
type of data for particular column. If
a column called first_name, that
column should be varchar (variable-
length character). This are the few
data types we use in a daily basis
CHAR – The character data type
accepts character strings including
Unicode of fixed length. E.g –
racecar, 12345 etc..
VARCHAR – accepts variable
character strings including Unicode
of variable length. E.g – first_name1,
lastname_2
BOOLEAN – Supports the storage
of two values. Either TRUE or FALSE.
SMALLINT – Accepts numeric
values with an implied scale of zero.
E.g an integer of 2 bytes.
INTEGER or INT - Accepts
numeric values with an implied scale
of zero. E.g an integer of 4 bytes.
DATETIME – Accepts the date
values.
SQL NULL & NOT NULL Values
 NULL – value is an empty or no value in a field. In NULL field we can
always insert new records.
 For example, to return the field with NULL value, we can use the following
SELECT statement. (IS NULL) recommended comparison operator.
E.g SELECT * FROM person
WHERE country IS NULL;
 NOT NULL – Returns a non_NULL value. Which means it contains an actual
records or it is not empty.
E.g SELECT * FROM person
WHERE country IS NOT NULL;
SQL DISTINCT Clause
 DISTINCT – In most cases, the SQL database tables may contain
duplicated values. The Distinct clause is used to remove duplicated rows
from the result-set of a SELECT statement.
 DISTINCT clause does not ignore null values. In the following example, we
want to select only the distinct values from the column named “country”
from person table.
 DISTINCT Syntax
E.g SELECT DISTINCT country
FROM person
• Operators allowed in the where clause.
With the where clause the following operators can be used.
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
Between Between in an inclusive range
Like Search for a pattern
IN If you know the exact value you want to return for at least one of the
columns
SQL AND & OR Operators
 The AND & OR operators are used to filter records based on more than one
condition.
 The AND operator displays a record if both the first and the second condition is
true.
 The OR operator displays a record if either the first or the second condition is true.
AND Operator Example
SELECT * from <table name>
Where column_name = ‘’ AND column_name = ‘’
OR Operator Example
SELECT * from <table name>
Where column_name = ‘’ OR column_name = ‘’
ORDER BY
 The ORDER BY Keyword is used to sort the result-set. We can return the
result set by ascending or descending order. However, the result-set sort
records in ascending order by default.
E.g SELECT * from <table name>
ORDER BY <column_name>
 To return the result-set in Descending order, we can use the following
example.
E.g SELECT * from <table name>
ORDER BY <column_name> DESC
 We can also return the result-set using several columns.
E.g SELECT * from <table name>
ORDER BY <column_name>, <column_name>,
<column_name>
INSERT INTO Statement
 The INSERT INTO statement is used to insert new records in a table.
INSERT INTO syntax
 We can use INSERT INTO syntax in two ways.
1. The first way is to specify both the column names and values to be inserted.
E.g INSERT INTO <table name> (column1, column2, column3)
VALUES (value1, value2, value3)
Note – If we put the values in char or varchar data type, we should use the values
in a single note.
2. The second way is to ignore the columns and add the values only. However,
we have to make sure the order of the values must be the same order as the
column.
E.g INSERT INTO <table name>
VALUES (value1, value2, value3)
INSERT INTO (Continued)
 INSERT INTO can be combined with a SELECT to insert records into a
table. The method is to copy some of or all of the columns from the table.
 The general syntax for INSERT INTO with SELECT
E.g INSERT INTO <table2>
SELECT * FROM <table1>
WHERE condition;
 0r to copy some of the columns,
E.g INSERT INTO <table2> (column1, column2, column3 )
SELECT column1, column2, column3 FROM <table1>
WHERE condition;
The UPDATE Statement
 The UPDATE statement is used to modify/update existing record in a table.
 UPDATE Syntax
E.g UPDATE <table name>
SET <column_name> = value
WHERE condition;
We can also update multiple columns in one syntax
E.g UPDATE <table name>
SET <column1> = value1, <column2> = value2, <column3> = value3
WHERE condition;
NOTE – Be careful updating records. If we do not use the where clause all the records in the
table will be updated.
The SELECT TOP clause
 The SELECT TOP clause is used to return the TOP x amount of records in a
table or x percent(%) row of the table.
 In this statement WHERE clause is an optional to use.
 MSSQL SELECT TOP syntax
E.g SELECT TOP 20 <column_name(s)>
FROM <table_name>
WHERE condition;
Or
E.g SELECT TOP 50% <column_name(s)>
FROM <table_name>
WHERE condition;
The SELECT TOP clause(continued)
 NOTE – Not all database systems support The TOP clause. It will be
different on MySQL and Oracle database.
 MySQL Syntax (LIMIT)
E.g SELECT column_names(s)
FROM <table name>
LIMIT 20
 Oracle SQL Syntax
E.g SELECT column_names(s)
FROM <table name>
WHERE ROWNUM = 20
SQL Wildcards with LIKE Condition
 SQL LIKE condition is used to perform pattern matching with syntax and it is used in a WHERE
clause.
 SQL LIKE condition allows to use wildcards to perform pattern matching in the query. In the
statement, you can use the following wildcards.
 % Syntax (I’m going to use sample table called person)
 E.g SELECT * from person
WHERE first_name LIKE ‘A%’
 This result returns from person table where first names starts with A
Wildcard Name Explanation
% Percent Represents to match any string (zero, one or multiple character)
_ Underscore Represents to match a single character.
[] charlist Represents to find any single character in charlist
[!] Not charlist Represents to find any single character not in charlist
SQL LIKE Condition (continued)
 We can also use NOT LIKE condition. This will be returning rows of character
that does not mention in the LIKE operator.
E.g SELECT * FROM person
WHERE first_name NOT LIKE ‘%a’
SQL IN condition
 The SQL IN condition allows to easily specify an expression that matches
any value in a list of values.
E.g SELECT * FROM persons
WHERE city IN (berlin, paris, rome)
We can also use NOT IN operator
E.g SELECT * FROM persons
WHERE city NOT IN (berlin, paris, rome)
 Another way of using IN condition. The following example selects all
persons that are the same city as the address
E.g SELECT * FROM persons
WHERE city IN (SELECT city FROM address)
 The BETWEEN operator selects values within a given range. The values can
be numbers or dates etc..
 BETWEEN Syntax
E.g SELECT * FROM persons
WHERE date_of_birth BETWEEN ‘1970-01-01’ AND ‘2000-01-01’
 In most cases we use single quotes for the values we are calling.
 To display the date_of_birth out side the range of the values use the
following example,
E.g SELECT * FROM persons
WHERE date_of_birth BETWEEN ‘1970-01-01’ AND ‘2000-01-01’
 We can also use BETWEEN with IN operator
E.g SELECT * FROM persons
WHERE (age BETWEEN 21 AND 60)
AND NOT person_id IN (1,2,3);
SQL BETWEEN Operator
SQL ALIASES
 ALIASES mean simply giving temporary names for the tables or columns. It
makes columns easier to read and shorten table names if we use join
statements.
 ALIASES are not going to be stored in the database.
ALIASES Syntax
E.g SELECT person_id AS ID, date_of_birth AS dob, Gender AS sex
FROM person AS p
 ALIASES can be used in JOIN statements
E.g SELECT p.person_id AS ID, p.date_of_birth AS dob
, a.city, a.zipcode
FROM person AS p
INNER JOIN address AS a
ON p.person_id = a.person.id
SQL JOINS - A Join clause is used to combine rows from two or more tables
based on a related column between them.
UNION & UNION ALL Operator
 UNION operator is used to combine the result set of 2 or more SELECT
statements. In UNION operator it removes duplicated rows between the
SELECT statements.
 UNION operator must have the same number of columns and data types
and the same orders between the SELECT (selected) tables.
E.g SELECT * (columns) FROM Table A
UNION
SELECT * (columns) FROM Table B
 UNION ALL – does not removes duplicate rows
E.g SELECT * (columns) FROM Table A
UNION ALL
SELECT * (columns) FROM Table B
SQL TRUNCATE TABLE
 The TRUNCATE TABLE statements removes all the records from existing
table without using WHERE clause.
 Truncating a table does not affect the table’s index, triggers..etc it only
removes the data from the table.
 WARNING – TRUNCATE TABLE perform same function as DELETE
statement. However, once we truncate a table we cannot be rolled
back in some databases.
 TRUNCATE TABLE Syntax
 E.g TRUNCATE TABLE table_name
AGGREGATE Functions (Count, Sum, Avg, Max, Min)
 COUNT – function is used to count the number of rows returned that matched in a
specified criteria.
E.g SELECT COUNT (order_id)
FROM orders
 SUM – function is used to return the sum of numeric item in a SELECT statement.
E.g SELECT SUM(salary) AS “Total_Salary”
FROM employees
WHERE salary > 50,000;
 AVG – function is used to return the average of numeric item in a SELECT statement.
E.g SELECT AVG(salary) AS “Avg_Salary”
FROM employees
WHERE title = ‘SQL DEVELOPER’;
 MAX – function is used to return the largest(Maximum) value of the
SELECT column.
E.g SELECT MAX (age)
FROM person
WHERE gender = ‘male’
ORDER by age DESC;
 MIN – function is used to return the smallest(Minimum) value of the
SELECT column.
E.g SELECT MAX (age)
FROM person
WHERE gender = ‘male’
ORDER by age DESC;
AGGREGATE Functions (Count, Sum, Avg, Max, Min)(continued)
SQL GROUP BY Clause
 The GROUP BY clause can be used to collect multiple records and group
the results by one or more columns.
 GROUP BY clause mostly used on aggregate functions (Count, Sum, Max,
Min, Avg).
 E.g SELECT person_id, dob, gender
FROM person
WHERE gender = ‘male’
GROUP BY person_id, dob, gender
ORDER BY person_id;
 We can also use GROUP BY clause in JOIN statements to group the result-
set by one or more columns
E.g SELECT p.person_id, COUNT(p.salary) AS salary
FROM person AS p
LEFT JOIN orders AS o
ON p.order_id = o.order_id
GROUP BY p.person_id;
SQL HAVING Clause
 HAVING clause is used to restrict the group of returned rows because we
cannot use aggregate functions on WHERE clause. However, we can use
HAVING clause in aggregate functions(Count, Sum, Avg, Max, Min).
 HAVING Syntax
E.g SELECT person_id, age, dob, AVG(salary)
FROM person
WHERE title = ‘SQL Developer’
GROUP BY person_id, age, dob
HAVING AVG(salary) > 55,000
ORDER BY AVG(salary) DESC;
SQL EXISTS Operator & Subqueries
 The EXISTS operator can be used to find the existence of records in a
subquery. In EXISTS condition is met if subquery returns at least one row.
E.g SELECT first_name
FROM person AS p
WHERE EXISTS (SELECT city FROM Address WHERE address_id = p.address_id AND postal_code=20001);
 Subqueries are a tool for performing select operation in multiple steps.
Subqueries also known as (inner queries or nested queries)
 SQL Subqueries usually added in the WHERE clause of SQL statement
 Subqueries are another way of returning data from multiple tables.
E.g SELECT o.order_name, o.order_date
, (SELECT sum(product_price)
FROM products
WHERE product_id = 20) AS total_price
FROM orders AS o where o.order_id = 20
SQL WHERE ANY & ALL Operators
 In SQL ANY and ALL are used with WHERE or HAVING clause.
 ANY operator returns true if any of the subquery value meet the condition.
E.g SELECT order_name
FROM orders
WHERE order_id = ANY (SELECT order_id FROM OrderDetails WHERE Quantity = 30);
 ALL operator returns true if all of the subquery value meet the condition.
E.g SELECT order_name
FROM orders
WHERE order_id = ALL (SELECT order_id FROM OrderDetails WHERE Quantity = 30);
SQL SELECT INTO
 SELECT INTO statement basically copies data from one table into new table.
 SELECT * INTO is another way of copying one table within the same database.
E.g SELECT * INTO <new_table>
FROM <old_table>
WHERE condtion<>;
 We can also copy some of the columns from one table to another
E.g SELECT column1, column2, column3, ...
INTO <new_table>
FROM <old_table>
WHERE condition<>;
 In addition, we can copy table from one database to another using IN clause.
E.g SELECT * INTO <new_table> IN <‘another_database’>
FROM <old_table>
SQL Constraints
 Constraints are used to specify rules in SQL server for the data in a table.
 We can specify constraints when we first CREATE TABLE or we can use
them after creating table with ALTER TABLE statement.
 In SQL the following constrains are commonly used.
 NOT NULL - Ensures that a column cannot have a NULL value
 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
 FOREIGN KEY - Uniquely identifies a row/record in another table
 CHECK - Ensures that all values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column when no value is specified
 INDEX- Used to create and retrieve data from the database very quickly
SQL Constraints(Continued)
 NOT NULL Syntax – NULL constraints can also be added using ALTER TABLE
statement, if the table has already been created.
E.g CREATE TABLE customers (
customer_id int NOT NULL,
last_name varchar(255) NOT NULL,
first_name varchar(255) NOT NULL,
dob datetime);
 UNIQUE Syntax – We can have many UNIQUE constraints in a table but one
PRIMARY KEY constraints in a table
E.g CREATE TABLE customers (
customer_id int NOT NULL UNIQUE,
last_name varchar(255) NOT NULL,
first_name varchar(255) NOT NULL,
dob datetime);
 PRIMARY KEY Syntax – Cannot contain null values and may consist multiple
column having one primary key in a table.
 E.g CREATE TABLE customers (
customer_id int NOT NULL PRIMARY KEY,
last_name varchar(255) NOT NULL,
first_name varchar(255) NOT NULL,
dob datetime);
 FOREIGN KEY Syntax – Mainly used to link two tables together. The table
containing the foreign key is called child table. The table containing the candidate
key is called referenced or parent table. E.g
CREATE TABLE products (
product_id int NOT NULL PRIMARY KEY,
customer_number int NOT NULL,
customer_id int FOREIGN KEY REFERENCES customers (customer_id));
 CHECK Syntax – The check constrains is used to limit the value range of specified
column.
E.g CREATE TABLE customers (
customer_id int NOT NULL PRIMARY KEY,
last_name varchar(255) NOT NULL,
first_name varchar(255) NOT NULL,
age int CHECK (age>=18));
SQL Constraints(Continued)
 DEFAULT – provides default value if INSERT INTO statement does not
provide specific value.
 E.g CREATE TABLE customers
( customer_id INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
SALARY REAL DEFAULT 5000.00));
 INDEX – The user cannot see the index. They’re just used to speed up
queries.
 E.g CREATE INDEX idx_lastname
ON Persons (LastName);
SQL Constraints(Continued)
SQL CREATE VIEW statement
 VIEW is a virtual table that does not physically exist. It is created by a SQL
statement that joins one or more tables. It contains a row and columns just
like the real table.
 VIEW Syntax
E.g CREATE VIEW <view_name> AS
SELECT column_name, column_name
FROM <table name>
WHERE condition;
 Then we can call the VIEW we just created using the following syntax.
E.g SELECT * FROM <view_name>
SQL AUTO INCREMENT Field
 AUTO INCREMENT – fields are used for auto generated values for
particular column whenever new row is inserted.
 Very often AUTO INCREMENT is used for Primary key to create the IDs
automatically every time we inserted new rows to the table.
 E.g CREATE TABLE customers (
customer_id int IDENTITY(1,1) PRIMARY KEY,
last_name varchar(255) NOT NULL,
first_name varchar(255) NOT NULL,
dob datetime);
 IDENTITY keyword performs an auto-increment feature
SQL Table Relationships
 Table relationship works by matching data in key columns.
 In most cases, the relationship matches the primary key from one table
with an entry of foreign key on another table.
 There are three types of table relationships
 One to One – Table A can have no more than one matching with Table B.
For example, in marriage, each spouse has only one other spouse. Which
means it does not use foreign key.
 One to Many – Single record in one table to be related to multiple records
to another table. For example, Mother to Children. Mother can have many
children and children cannot have many mother.
 Many to Many – Many records in a table can have many records to
another table. For example, each student can take many class and each
class can have many students. In this case many to many relationship
requires third table.
SQL Table
Relationships
(Continued)

More Related Content

What's hot

Packages - PL/SQL
Packages - PL/SQLPackages - PL/SQL
Packages - PL/SQL
Esmita Gupta
 
Fundamentos de SQL
Fundamentos de SQLFundamentos de SQL
Fundamentos de SQL
camposer
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
mohdoracle
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
Sabana Maharjan
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
Shrija Madhu
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
farwa waqar
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
Nitesh Singh
 
Sql
SqlSql
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functionsVikas Gupta
 
DML Commands
DML CommandsDML Commands
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
Edureka!
 
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsWriting Basic SQL SELECT Statements
Writing Basic SQL SELECT Statements
Salman Memon
 
Funciones y procedimientos en SQL
Funciones y procedimientos en SQLFunciones y procedimientos en SQL
Funciones y procedimientos en SQLRonald Rivas
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In SqlAnurag
 
Oracle Course
Oracle CourseOracle Course
Oracle Courserspaike
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
farhan516
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
Rumman Ansari
 
Programación 3: colas
Programación 3: colasProgramación 3: colas
Programación 3: colas
Angel Vázquez Patiño
 
Fundamentos de BD - Unidad 5 algebra relacional
Fundamentos de BD - Unidad 5 algebra relacionalFundamentos de BD - Unidad 5 algebra relacional
Fundamentos de BD - Unidad 5 algebra relacional
José Antonio Sandoval Acosta
 
Programacion de base de datos - unidad 3 Programacion de base de datos
Programacion de base de datos - unidad 3 Programacion de base de datosProgramacion de base de datos - unidad 3 Programacion de base de datos
Programacion de base de datos - unidad 3 Programacion de base de datos
José Antonio Sandoval Acosta
 

What's hot (20)

Packages - PL/SQL
Packages - PL/SQLPackages - PL/SQL
Packages - PL/SQL
 
Fundamentos de SQL
Fundamentos de SQLFundamentos de SQL
Fundamentos de SQL
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
Sql
SqlSql
Sql
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
DML Commands
DML CommandsDML Commands
DML Commands
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
 
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsWriting Basic SQL SELECT Statements
Writing Basic SQL SELECT Statements
 
Funciones y procedimientos en SQL
Funciones y procedimientos en SQLFunciones y procedimientos en SQL
Funciones y procedimientos en SQL
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
Oracle Course
Oracle CourseOracle Course
Oracle Course
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Programación 3: colas
Programación 3: colasProgramación 3: colas
Programación 3: colas
 
Fundamentos de BD - Unidad 5 algebra relacional
Fundamentos de BD - Unidad 5 algebra relacionalFundamentos de BD - Unidad 5 algebra relacional
Fundamentos de BD - Unidad 5 algebra relacional
 
Programacion de base de datos - unidad 3 Programacion de base de datos
Programacion de base de datos - unidad 3 Programacion de base de datosProgramacion de base de datos - unidad 3 Programacion de base de datos
Programacion de base de datos - unidad 3 Programacion de base de datos
 

Similar to SQL Tutorial for Beginners

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
jainendraKUMAR55
 
SQL Query
SQL QuerySQL Query
SQL Query
Imam340267
 
Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01sagaroceanic11
 
SQL
SQLSQL
SQL
SQLSQL
SQL report
SQL reportSQL report
SQL report
Ahmad Zahid
 
MY SQL
MY SQLMY SQL
MY SQL
sundar
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
Brian Foote
 
Commands
CommandsCommands
Commands
Ayushi Goyal
 
Babitha2 Mysql
Babitha2 MysqlBabitha2 Mysql
Babitha2 Mysql
banubabitha
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
IMsKanchanaI
 
SQL : Structured Query Language
SQL : Structured Query LanguageSQL : Structured Query Language
SQL : Structured Query Language
Abhishek Gautam
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
Pooja Dixit
 
Sql commands
Sql commandsSql commands
Sql commands
Pooja Dixit
 
Lab1 select statement
Lab1 select statementLab1 select statement
Lab1 select statement
Balqees Al.Mubarak
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
Swapnali Pawar
 

Similar to SQL Tutorial for Beginners (20)

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 slid
Sql slidSql slid
Sql slid
 
SQL Query
SQL QuerySQL Query
SQL Query
 
Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01
 
SQL
SQLSQL
SQL
 
SQL
SQLSQL
SQL
 
SQL report
SQL reportSQL report
SQL report
 
MY SQL
MY SQLMY SQL
MY SQL
 
Sql
SqlSql
Sql
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
Commands
CommandsCommands
Commands
 
Babitha2.mysql
Babitha2.mysqlBabitha2.mysql
Babitha2.mysql
 
Babitha2 Mysql
Babitha2 MysqlBabitha2 Mysql
Babitha2 Mysql
 
SQL
SQLSQL
SQL
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
 
SQL : Structured Query Language
SQL : Structured Query LanguageSQL : Structured Query Language
SQL : Structured Query Language
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Sql commands
Sql commandsSql commands
Sql commands
 
Lab1 select statement
Lab1 select statementLab1 select statement
Lab1 select statement
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 

Recently uploaded

Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 

Recently uploaded (20)

Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 

SQL Tutorial for Beginners

  • 2. What is SQL? SQL – Stands for Structured Query Language. SQL is used to communicate a database. SQL statements are used to perform tasks such as, update data in the database, retrieve data from the database. • There are standard SQL commands such as, Insert, update, delete, select, create, drop can be used to accomplish almost everything that one needs to do with the database. 01
  • 3. What SQL can do? With SQL you can: • Execute queries against the database. • Perform CRUD functions. • CREATE – New database , new table in a database, new records • READ – Retrieve data from the database • UPDATE – Update existing records from the database • DELETE – Delete records from the database
  • 4. SQL Statements fit into two broad categories Data Definition Language (DDL) – Used to define data structures and used to build and modify the structures of your table and other objects in the database. Use these statement to Create, alter or drop data structures from instance of the SQL server. Data Manipulation Language (DML) Statements are used to work with data in tables. These statement includes, Select, Insert, Update and Delete.
  • 5. Script Examples of DDL and DML CREATE – This statement creates database, tables, index etc. CREATE TABLE <table name> ( <column_name 1> <data type 1>, < column_name 2> <data type 2>); ALTER – This statement used to modify data in the table. ALTER TABLE <table name> ADD CONSTRAINT <constraint name> PRIMARY KEY (<column_name>); DROP – This statement used to drop existing table in a database. DROP <table name> or ALTER TABLE <table name> DROP CONSTRAINT <constraint name>; This Illustrates example statement of DDL
  • 6. Script Examples of DDL and DML (Continued) INSERT – Insert statement used to add new rows to the table. E.g INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...); The comma-delimited list of values must match the table structure exactly the numbers of columns. Character data type should always enclosed in single quote. UPDATE – The update statement is used to change values that are already in a table. E.g UPDATE <table name> SET <column> = <value> WHERE <condition>; DELETE – The delete statement does just that. (Be-careful on this statement) E.g DELETE FROM <table name> WHERE <condition>; If the WHERE clause is omitted, then every row of the table is deleted (which usually not what we want to do)
  • 7. Script Examples of DDL and DML (Continued) SELECT – This statement used to retrieve information from the table. SELECT column1, column2, ... FROM table_name; If you want to select all the fields available in the table use this statement. The (*) selects all the fields(columns) in the table. SELECT * from table_name (where clause) - The where clause (optional) specifies which data values or rows will be returned or displayed, based on the criteria described after the keyword where. SELECT * from table_name Where column = <condition>
  • 8. SQL Data Types Data Type – specify what the type of data for particular column. If a column called first_name, that column should be varchar (variable- length character). This are the few data types we use in a daily basis CHAR – The character data type accepts character strings including Unicode of fixed length. E.g – racecar, 12345 etc.. VARCHAR – accepts variable character strings including Unicode of variable length. E.g – first_name1, lastname_2 BOOLEAN – Supports the storage of two values. Either TRUE or FALSE. SMALLINT – Accepts numeric values with an implied scale of zero. E.g an integer of 2 bytes. INTEGER or INT - Accepts numeric values with an implied scale of zero. E.g an integer of 4 bytes. DATETIME – Accepts the date values.
  • 9. SQL NULL & NOT NULL Values  NULL – value is an empty or no value in a field. In NULL field we can always insert new records.  For example, to return the field with NULL value, we can use the following SELECT statement. (IS NULL) recommended comparison operator. E.g SELECT * FROM person WHERE country IS NULL;  NOT NULL – Returns a non_NULL value. Which means it contains an actual records or it is not empty. E.g SELECT * FROM person WHERE country IS NOT NULL;
  • 10. SQL DISTINCT Clause  DISTINCT – In most cases, the SQL database tables may contain duplicated values. The Distinct clause is used to remove duplicated rows from the result-set of a SELECT statement.  DISTINCT clause does not ignore null values. In the following example, we want to select only the distinct values from the column named “country” from person table.  DISTINCT Syntax E.g SELECT DISTINCT country FROM person
  • 11. • Operators allowed in the where clause. With the where clause the following operators can be used. Operator Description = Equal <> Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal Between Between in an inclusive range Like Search for a pattern IN If you know the exact value you want to return for at least one of the columns
  • 12. SQL AND & OR Operators  The AND & OR operators are used to filter records based on more than one condition.  The AND operator displays a record if both the first and the second condition is true.  The OR operator displays a record if either the first or the second condition is true. AND Operator Example SELECT * from <table name> Where column_name = ‘’ AND column_name = ‘’ OR Operator Example SELECT * from <table name> Where column_name = ‘’ OR column_name = ‘’
  • 13. ORDER BY  The ORDER BY Keyword is used to sort the result-set. We can return the result set by ascending or descending order. However, the result-set sort records in ascending order by default. E.g SELECT * from <table name> ORDER BY <column_name>  To return the result-set in Descending order, we can use the following example. E.g SELECT * from <table name> ORDER BY <column_name> DESC  We can also return the result-set using several columns. E.g SELECT * from <table name> ORDER BY <column_name>, <column_name>, <column_name>
  • 14. INSERT INTO Statement  The INSERT INTO statement is used to insert new records in a table. INSERT INTO syntax  We can use INSERT INTO syntax in two ways. 1. The first way is to specify both the column names and values to be inserted. E.g INSERT INTO <table name> (column1, column2, column3) VALUES (value1, value2, value3) Note – If we put the values in char or varchar data type, we should use the values in a single note. 2. The second way is to ignore the columns and add the values only. However, we have to make sure the order of the values must be the same order as the column. E.g INSERT INTO <table name> VALUES (value1, value2, value3)
  • 15. INSERT INTO (Continued)  INSERT INTO can be combined with a SELECT to insert records into a table. The method is to copy some of or all of the columns from the table.  The general syntax for INSERT INTO with SELECT E.g INSERT INTO <table2> SELECT * FROM <table1> WHERE condition;  0r to copy some of the columns, E.g INSERT INTO <table2> (column1, column2, column3 ) SELECT column1, column2, column3 FROM <table1> WHERE condition;
  • 16. The UPDATE Statement  The UPDATE statement is used to modify/update existing record in a table.  UPDATE Syntax E.g UPDATE <table name> SET <column_name> = value WHERE condition; We can also update multiple columns in one syntax E.g UPDATE <table name> SET <column1> = value1, <column2> = value2, <column3> = value3 WHERE condition; NOTE – Be careful updating records. If we do not use the where clause all the records in the table will be updated.
  • 17. The SELECT TOP clause  The SELECT TOP clause is used to return the TOP x amount of records in a table or x percent(%) row of the table.  In this statement WHERE clause is an optional to use.  MSSQL SELECT TOP syntax E.g SELECT TOP 20 <column_name(s)> FROM <table_name> WHERE condition; Or E.g SELECT TOP 50% <column_name(s)> FROM <table_name> WHERE condition;
  • 18. The SELECT TOP clause(continued)  NOTE – Not all database systems support The TOP clause. It will be different on MySQL and Oracle database.  MySQL Syntax (LIMIT) E.g SELECT column_names(s) FROM <table name> LIMIT 20  Oracle SQL Syntax E.g SELECT column_names(s) FROM <table name> WHERE ROWNUM = 20
  • 19. SQL Wildcards with LIKE Condition  SQL LIKE condition is used to perform pattern matching with syntax and it is used in a WHERE clause.  SQL LIKE condition allows to use wildcards to perform pattern matching in the query. In the statement, you can use the following wildcards.  % Syntax (I’m going to use sample table called person)  E.g SELECT * from person WHERE first_name LIKE ‘A%’  This result returns from person table where first names starts with A Wildcard Name Explanation % Percent Represents to match any string (zero, one or multiple character) _ Underscore Represents to match a single character. [] charlist Represents to find any single character in charlist [!] Not charlist Represents to find any single character not in charlist
  • 20. SQL LIKE Condition (continued)  We can also use NOT LIKE condition. This will be returning rows of character that does not mention in the LIKE operator. E.g SELECT * FROM person WHERE first_name NOT LIKE ‘%a’
  • 21. SQL IN condition  The SQL IN condition allows to easily specify an expression that matches any value in a list of values. E.g SELECT * FROM persons WHERE city IN (berlin, paris, rome) We can also use NOT IN operator E.g SELECT * FROM persons WHERE city NOT IN (berlin, paris, rome)  Another way of using IN condition. The following example selects all persons that are the same city as the address E.g SELECT * FROM persons WHERE city IN (SELECT city FROM address)
  • 22.  The BETWEEN operator selects values within a given range. The values can be numbers or dates etc..  BETWEEN Syntax E.g SELECT * FROM persons WHERE date_of_birth BETWEEN ‘1970-01-01’ AND ‘2000-01-01’  In most cases we use single quotes for the values we are calling.  To display the date_of_birth out side the range of the values use the following example, E.g SELECT * FROM persons WHERE date_of_birth BETWEEN ‘1970-01-01’ AND ‘2000-01-01’  We can also use BETWEEN with IN operator E.g SELECT * FROM persons WHERE (age BETWEEN 21 AND 60) AND NOT person_id IN (1,2,3); SQL BETWEEN Operator
  • 23. SQL ALIASES  ALIASES mean simply giving temporary names for the tables or columns. It makes columns easier to read and shorten table names if we use join statements.  ALIASES are not going to be stored in the database. ALIASES Syntax E.g SELECT person_id AS ID, date_of_birth AS dob, Gender AS sex FROM person AS p  ALIASES can be used in JOIN statements E.g SELECT p.person_id AS ID, p.date_of_birth AS dob , a.city, a.zipcode FROM person AS p INNER JOIN address AS a ON p.person_id = a.person.id
  • 24. SQL JOINS - A Join clause is used to combine rows from two or more tables based on a related column between them.
  • 25. UNION & UNION ALL Operator  UNION operator is used to combine the result set of 2 or more SELECT statements. In UNION operator it removes duplicated rows between the SELECT statements.  UNION operator must have the same number of columns and data types and the same orders between the SELECT (selected) tables. E.g SELECT * (columns) FROM Table A UNION SELECT * (columns) FROM Table B  UNION ALL – does not removes duplicate rows E.g SELECT * (columns) FROM Table A UNION ALL SELECT * (columns) FROM Table B
  • 26. SQL TRUNCATE TABLE  The TRUNCATE TABLE statements removes all the records from existing table without using WHERE clause.  Truncating a table does not affect the table’s index, triggers..etc it only removes the data from the table.  WARNING – TRUNCATE TABLE perform same function as DELETE statement. However, once we truncate a table we cannot be rolled back in some databases.  TRUNCATE TABLE Syntax  E.g TRUNCATE TABLE table_name
  • 27. AGGREGATE Functions (Count, Sum, Avg, Max, Min)  COUNT – function is used to count the number of rows returned that matched in a specified criteria. E.g SELECT COUNT (order_id) FROM orders  SUM – function is used to return the sum of numeric item in a SELECT statement. E.g SELECT SUM(salary) AS “Total_Salary” FROM employees WHERE salary > 50,000;  AVG – function is used to return the average of numeric item in a SELECT statement. E.g SELECT AVG(salary) AS “Avg_Salary” FROM employees WHERE title = ‘SQL DEVELOPER’;
  • 28.  MAX – function is used to return the largest(Maximum) value of the SELECT column. E.g SELECT MAX (age) FROM person WHERE gender = ‘male’ ORDER by age DESC;  MIN – function is used to return the smallest(Minimum) value of the SELECT column. E.g SELECT MAX (age) FROM person WHERE gender = ‘male’ ORDER by age DESC; AGGREGATE Functions (Count, Sum, Avg, Max, Min)(continued)
  • 29. SQL GROUP BY Clause  The GROUP BY clause can be used to collect multiple records and group the results by one or more columns.  GROUP BY clause mostly used on aggregate functions (Count, Sum, Max, Min, Avg).  E.g SELECT person_id, dob, gender FROM person WHERE gender = ‘male’ GROUP BY person_id, dob, gender ORDER BY person_id;  We can also use GROUP BY clause in JOIN statements to group the result- set by one or more columns E.g SELECT p.person_id, COUNT(p.salary) AS salary FROM person AS p LEFT JOIN orders AS o ON p.order_id = o.order_id GROUP BY p.person_id;
  • 30. SQL HAVING Clause  HAVING clause is used to restrict the group of returned rows because we cannot use aggregate functions on WHERE clause. However, we can use HAVING clause in aggregate functions(Count, Sum, Avg, Max, Min).  HAVING Syntax E.g SELECT person_id, age, dob, AVG(salary) FROM person WHERE title = ‘SQL Developer’ GROUP BY person_id, age, dob HAVING AVG(salary) > 55,000 ORDER BY AVG(salary) DESC;
  • 31. SQL EXISTS Operator & Subqueries  The EXISTS operator can be used to find the existence of records in a subquery. In EXISTS condition is met if subquery returns at least one row. E.g SELECT first_name FROM person AS p WHERE EXISTS (SELECT city FROM Address WHERE address_id = p.address_id AND postal_code=20001);  Subqueries are a tool for performing select operation in multiple steps. Subqueries also known as (inner queries or nested queries)  SQL Subqueries usually added in the WHERE clause of SQL statement  Subqueries are another way of returning data from multiple tables. E.g SELECT o.order_name, o.order_date , (SELECT sum(product_price) FROM products WHERE product_id = 20) AS total_price FROM orders AS o where o.order_id = 20
  • 32. SQL WHERE ANY & ALL Operators  In SQL ANY and ALL are used with WHERE or HAVING clause.  ANY operator returns true if any of the subquery value meet the condition. E.g SELECT order_name FROM orders WHERE order_id = ANY (SELECT order_id FROM OrderDetails WHERE Quantity = 30);  ALL operator returns true if all of the subquery value meet the condition. E.g SELECT order_name FROM orders WHERE order_id = ALL (SELECT order_id FROM OrderDetails WHERE Quantity = 30);
  • 33. SQL SELECT INTO  SELECT INTO statement basically copies data from one table into new table.  SELECT * INTO is another way of copying one table within the same database. E.g SELECT * INTO <new_table> FROM <old_table> WHERE condtion<>;  We can also copy some of the columns from one table to another E.g SELECT column1, column2, column3, ... INTO <new_table> FROM <old_table> WHERE condition<>;  In addition, we can copy table from one database to another using IN clause. E.g SELECT * INTO <new_table> IN <‘another_database’> FROM <old_table>
  • 34. SQL Constraints  Constraints are used to specify rules in SQL server for the data in a table.  We can specify constraints when we first CREATE TABLE or we can use them after creating table with ALTER TABLE statement.  In SQL the following constrains are commonly used.  NOT NULL - Ensures that a column cannot have a NULL value  UNIQUE - Ensures that all values in a column are different  PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table  FOREIGN KEY - Uniquely identifies a row/record in another table  CHECK - Ensures that all values in a column satisfies a specific condition  DEFAULT - Sets a default value for a column when no value is specified  INDEX- Used to create and retrieve data from the database very quickly
  • 35. SQL Constraints(Continued)  NOT NULL Syntax – NULL constraints can also be added using ALTER TABLE statement, if the table has already been created. E.g CREATE TABLE customers ( customer_id int NOT NULL, last_name varchar(255) NOT NULL, first_name varchar(255) NOT NULL, dob datetime);  UNIQUE Syntax – We can have many UNIQUE constraints in a table but one PRIMARY KEY constraints in a table E.g CREATE TABLE customers ( customer_id int NOT NULL UNIQUE, last_name varchar(255) NOT NULL, first_name varchar(255) NOT NULL, dob datetime);  PRIMARY KEY Syntax – Cannot contain null values and may consist multiple column having one primary key in a table.  E.g CREATE TABLE customers ( customer_id int NOT NULL PRIMARY KEY, last_name varchar(255) NOT NULL, first_name varchar(255) NOT NULL, dob datetime);
  • 36.  FOREIGN KEY Syntax – Mainly used to link two tables together. The table containing the foreign key is called child table. The table containing the candidate key is called referenced or parent table. E.g CREATE TABLE products ( product_id int NOT NULL PRIMARY KEY, customer_number int NOT NULL, customer_id int FOREIGN KEY REFERENCES customers (customer_id));  CHECK Syntax – The check constrains is used to limit the value range of specified column. E.g CREATE TABLE customers ( customer_id int NOT NULL PRIMARY KEY, last_name varchar(255) NOT NULL, first_name varchar(255) NOT NULL, age int CHECK (age>=18)); SQL Constraints(Continued)
  • 37.  DEFAULT – provides default value if INSERT INTO statement does not provide specific value.  E.g CREATE TABLE customers ( customer_id INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, SALARY REAL DEFAULT 5000.00));  INDEX – The user cannot see the index. They’re just used to speed up queries.  E.g CREATE INDEX idx_lastname ON Persons (LastName); SQL Constraints(Continued)
  • 38. SQL CREATE VIEW statement  VIEW is a virtual table that does not physically exist. It is created by a SQL statement that joins one or more tables. It contains a row and columns just like the real table.  VIEW Syntax E.g CREATE VIEW <view_name> AS SELECT column_name, column_name FROM <table name> WHERE condition;  Then we can call the VIEW we just created using the following syntax. E.g SELECT * FROM <view_name>
  • 39. SQL AUTO INCREMENT Field  AUTO INCREMENT – fields are used for auto generated values for particular column whenever new row is inserted.  Very often AUTO INCREMENT is used for Primary key to create the IDs automatically every time we inserted new rows to the table.  E.g CREATE TABLE customers ( customer_id int IDENTITY(1,1) PRIMARY KEY, last_name varchar(255) NOT NULL, first_name varchar(255) NOT NULL, dob datetime);  IDENTITY keyword performs an auto-increment feature
  • 40. SQL Table Relationships  Table relationship works by matching data in key columns.  In most cases, the relationship matches the primary key from one table with an entry of foreign key on another table.  There are three types of table relationships  One to One – Table A can have no more than one matching with Table B. For example, in marriage, each spouse has only one other spouse. Which means it does not use foreign key.  One to Many – Single record in one table to be related to multiple records to another table. For example, Mother to Children. Mother can have many children and children cannot have many mother.  Many to Many – Many records in a table can have many records to another table. For example, each student can take many class and each class can have many students. In this case many to many relationship requires third table.