This tutorial will give you a quick start to SQL including examples. It covers most of the topics required for a basic understanding of SQL and to get a feel of how it works.
Clauses in Sql(Structured Query Language), distinct clause, where clause, where clause, order by clause, group by clause, having clause, Relational Database Management System
Consists of the explanations of the basics of SQL and commands of SQL.Helpful for II PU NCERT students and also degree studeents to understand some basic things.
Clauses in Sql(Structured Query Language), distinct clause, where clause, where clause, order by clause, group by clause, having clause, Relational Database Management System
Consists of the explanations of the basics of SQL and commands of SQL.Helpful for II PU NCERT students and also degree studeents to understand some basic things.
(** MYSQL DBA Certification Training https://www.edureka.co/mysql-dba **)
This Edureka PPT on SQL Joins will discuss the various types of Joins used in SQL Server with examples. The following topics will be covered in this PPT:
Introduction to SQL
What are Joins?
Types of Joins
FAQs about Joins
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
After completing this lesson, you should be able to
do the following:
List the capabilities of SQL SELECT statements
Execute a basic SELECT statement
Differentiate between SQL statements and iSQL*Plus commands
http://phpexecutor.com
(** MYSQL DBA Certification Training https://www.edureka.co/mysql-dba **)
This Edureka PPT on SQL Joins will discuss the various types of Joins used in SQL Server with examples. The following topics will be covered in this PPT:
Introduction to SQL
What are Joins?
Types of Joins
FAQs about Joins
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
After completing this lesson, you should be able to
do the following:
List the capabilities of SQL SELECT statements
Execute a basic SELECT statement
Differentiate between SQL statements and iSQL*Plus commands
http://phpexecutor.com
This is a word file for SQL COMMANDS and including some basic information regarding SQL. I hope it will help you a lot while doing SQL and its functions and commands.
Its about a sql topic for basic structured query languageIMsKanchanaI
this is containning about structured query language and database concepts , commands, queries and queries to create and database and inserting values and rows. rows cannot be inserted at a time. only one row can be inserted at a time.
SQL stands for Structured Query Language.
SQL is a database management language for relational databases.
SQL lets you access and manipulate databases.
(INNER) JOIN: , LEFT (OUTER) JOIN: ,RIGHT (OUTER) JOIN: , FULL (OUTER) JOIN: , SQL UNION Operator, SQL GROUP BY HAVING statement, The SQL EXISTS Operator, The SQL ANY and ALL Operators, The SQL SELECT INTO Statement, The SQL INSERT INTO SELECT StatementThe SQL INSERT INTO SELECT Statement
Data Definition Language (DDL), Data Definition Language (DDL), Data Manipulation Language (DML) , Transaction Control Language (TCL) , Data Control Language (DCL) - , SQL Constraints
A. Table Basic Data Types- Char, varchar/varchar2, long, number, Fixed Commands to create table Commands for table handling- Alter table, Drop table, Insert records B. Commands for record handling Update, Delete Select with operators like arithmetic, comparison, logical Query Expression operators Ordering the records with orderby Grouping the records C. SQL functions Date, Numeric, Character, conversion Group functions avg, max, min, sum, count Set operations- Union, Union all, intersect, minu
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
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.