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

PPTX
SQL - DML and DDL Commands
DOC
80 different SQL Queries with output
PPT
SQL Tutorial - Basic Commands
PPT
SQL subquery
PDF
[APJ] Common Table Expressions (CTEs) in SQL
 
PDF
SQL Joins and Query Optimization
PDF
SQL JOINS
PPT
Mysql
SQL - DML and DDL Commands
80 different SQL Queries with output
SQL Tutorial - Basic Commands
SQL subquery
[APJ] Common Table Expressions (CTEs) in SQL
 
SQL Joins and Query Optimization
SQL JOINS
Mysql

What's hot (20)

PPTX
PPT
PPTX
PPTX
PLSQL Tutorial
PPTX
NESTED SUBQUERY.pptx
PPTX
Oracle sql analytic functions
PPT
Sql joins
PPTX
Sql queries presentation
PPT
Introduction to-sql
PPSX
MS SQL Server
PPTX
SQL Functions
PPTX
Oracle: DML
PPTX
PPTX
SQL JOIN
ODP
PPTX
Database constraints
PPT
Sql join
PPT
Displaying Data from Multiple Tables - Oracle Data Base
PPT
Sql operators & functions 3
PPTX
Sql(structured query language)
PLSQL Tutorial
NESTED SUBQUERY.pptx
Oracle sql analytic functions
Sql joins
Sql queries presentation
Introduction to-sql
MS SQL Server
SQL Functions
Oracle: DML
SQL JOIN
Database constraints
Sql join
Displaying Data from Multiple Tables - Oracle Data Base
Sql operators & functions 3
Sql(structured query language)
Ad

Similar to SQL Tutorial for Beginners (20)

PPTX
PPTX
06.01 sql select distinct
DOC
ORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDS
PPT
CE 279 - WRITING SQL QUERIES umat edition.ppt
PPT
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
DOCX
SQL Language
DOCX
SQL report
PPTX
SAMPLE QUESTION PAPER (THEORY) CLASS: XII SESSION: 2024-25 COMPUTER SCIENCE...
PPTX
SQL.pptx SAMPLE QUESTION PAPER (THEORY) CLASS: XII SESSION: 2024-25 COMPUTE...
PDF
full detailled SQL notesquestion bank (1).pdf
DOC
PPTX
Sql slid
PPTX
MYSQL-database basic queries for good understanding
PPTX
Lesson-02 (1).pptx
PDF
Chapter – 6 SQL Lab Tutorial.pdf
PPTX
SQl data base management and design
PPTX
SQL Query
DOCX
PDF
SQL notes 1.pdf
PPT
MY SQL
06.01 sql select distinct
ORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDS
CE 279 - WRITING SQL QUERIES umat edition.ppt
asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd
SQL Language
SQL report
SAMPLE QUESTION PAPER (THEORY) CLASS: XII SESSION: 2024-25 COMPUTER SCIENCE...
SQL.pptx SAMPLE QUESTION PAPER (THEORY) CLASS: XII SESSION: 2024-25 COMPUTE...
full detailled SQL notesquestion bank (1).pdf
Sql slid
MYSQL-database basic queries for good understanding
Lesson-02 (1).pptx
Chapter – 6 SQL Lab Tutorial.pdf
SQl data base management and design
SQL Query
SQL notes 1.pdf
MY SQL
Ad

Recently uploaded (20)

PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
Teaching material agriculture food technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Empathic Computing: Creating Shared Understanding
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
sap open course for s4hana steps from ECC to s4
PDF
cuic standard and advanced reporting.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
“AI and Expert System Decision Support & Business Intelligence Systems”
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Teaching material agriculture food technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Empathic Computing: Creating Shared Understanding
Unlocking AI with Model Context Protocol (MCP)
The Rise and Fall of 3GPP – Time for a Sabbatical?
Programs and apps: productivity, graphics, security and other tools
sap open course for s4hana steps from ECC to s4
cuic standard and advanced reporting.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
MIND Revenue Release Quarter 2 2025 Press Release
Per capita expenditure prediction using model stacking based on satellite ima...

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.