SQL is a language used to retrieve and manipulate data stored in relational database tables. It allows users to perform operations like selecting data, inserting rows, updating records, and deleting data. The four fundamental SQL statements are SELECT, INSERT, UPDATE, and DELETE. SQL statements follow a basic syntax and include keywords like SELECT, FROM, WHERE to query data and sort results.
SQL constraints are rules that limit the type of data that can be stored in a table. They can be specified when a table is created or altered later. A primary key uniquely identifies each row and cannot be null. A composite key uses multiple columns as the primary key. A foreign key's values must exist in another table's primary key. Joins combine data from multiple tables and include inner, outer, cross, and other types of joins. Views are virtual tables that dynamically select data from other tables.
SQL is a standard language used to communicate with databases and manipulate data. It allows users to create and modify database objects like tables and queries, as well as perform data retrieval, insertion, updating and deletion. The core SQL statements are SELECT to query data, INSERT and UPDATE to modify data, and DELETE to remove data. Tables contain records made up of columns with specific data types.
This document discusses database integrity in SQL. It covers various methods for enforcing integrity like constraints, defaults, indexes, primary keys, foreign keys and referential integrity. It provides examples of using these features to define integrity when creating or altering tables. Key points covered include the different types of constraints, how data is stored and indexed, and how to get help or modify existing constraints.
This document provides an introduction to structured query language (SQL). It outlines the objectives of learning SQL, which are to use SQL for data administration and data manipulation. The agenda covers SQL concepts like data types, constraints, database relationships, queries, and commands. It discusses SQL database objects and how to retrieve, customize, group and join data. It also covers inserting, updating, deleting data and working with tables, views, constraints, stored procedures and functions.
SQL is a standard language for accessing and manipulating databases. It allows users to perform functions like querying data, inserting records, updating records, and deleting records. The main SQL statements are SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, and DROP. SQL also includes clauses like WHERE, ORDER BY, GROUP BY and JOIN that allow users to filter and sort query results. Common data definition language statements are used to create and modify database structures like tables, indexes, and relationships.
SQL is a standard language for accessing and manipulating relational databases. It allows users to define, manipulate, and control access to data in a database. Some key capabilities of SQL include executing queries to retrieve data, as well as inserting, updating, and deleting records. SQL databases typically contain tables made up of rows and columns that store data. Relationships between tables are defined through primary and foreign keys. Database management systems use SQL to maintain database objects like tables, indexes, and views.
The document provides an overview of the SQL language, including its Data Manipulation Language (DML) and Data Definition Language (DDL). It describes key SQL statements like SELECT, INSERT, UPDATE, DELETE and explains concepts like WHERE clauses, LIKE operators, and JOINs. Examples are provided to demonstrate how to retrieve, modify, and delete data from SQL database tables.
SQL constraints are rules that limit the type of data that can be stored in a table. They can be specified when a table is created or altered later. A primary key uniquely identifies each row and cannot be null. A composite key uses multiple columns as the primary key. A foreign key's values must exist in another table's primary key. Joins combine data from multiple tables and include inner, outer, cross, and other types of joins. Views are virtual tables that dynamically select data from other tables.
SQL is a standard language used to communicate with databases and manipulate data. It allows users to create and modify database objects like tables and queries, as well as perform data retrieval, insertion, updating and deletion. The core SQL statements are SELECT to query data, INSERT and UPDATE to modify data, and DELETE to remove data. Tables contain records made up of columns with specific data types.
This document discusses database integrity in SQL. It covers various methods for enforcing integrity like constraints, defaults, indexes, primary keys, foreign keys and referential integrity. It provides examples of using these features to define integrity when creating or altering tables. Key points covered include the different types of constraints, how data is stored and indexed, and how to get help or modify existing constraints.
This document provides an introduction to structured query language (SQL). It outlines the objectives of learning SQL, which are to use SQL for data administration and data manipulation. The agenda covers SQL concepts like data types, constraints, database relationships, queries, and commands. It discusses SQL database objects and how to retrieve, customize, group and join data. It also covers inserting, updating, deleting data and working with tables, views, constraints, stored procedures and functions.
SQL is a standard language for accessing and manipulating databases. It allows users to perform functions like querying data, inserting records, updating records, and deleting records. The main SQL statements are SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, and DROP. SQL also includes clauses like WHERE, ORDER BY, GROUP BY and JOIN that allow users to filter and sort query results. Common data definition language statements are used to create and modify database structures like tables, indexes, and relationships.
SQL is a standard language for accessing and manipulating relational databases. It allows users to define, manipulate, and control access to data in a database. Some key capabilities of SQL include executing queries to retrieve data, as well as inserting, updating, and deleting records. SQL databases typically contain tables made up of rows and columns that store data. Relationships between tables are defined through primary and foreign keys. Database management systems use SQL to maintain database objects like tables, indexes, and views.
The document provides an overview of the SQL language, including its Data Manipulation Language (DML) and Data Definition Language (DDL). It describes key SQL statements like SELECT, INSERT, UPDATE, DELETE and explains concepts like WHERE clauses, LIKE operators, and JOINs. Examples are provided to demonstrate how to retrieve, modify, and delete data from SQL database tables.
This document provides information about SQL queries and joins. It begins by introducing SQL (Structured Query Language) which is used to communicate with databases and retrieve required information. It describes the basic CRUD (Create, Read, Update, Delete) functions of SQL. It then discusses different types of SQL queries - aggregate function queries, scalar function queries, and join queries. It provides the syntax and explanation of inner joins, outer joins (left, right, full) which are used to query data from multiple tables based on relationships between columns. The document is presented by Hammad, Bilal and Awais.
The document provides an introduction to SQL and covers various SQL clauses and functions including:
- Data retrieval using SELECT statements with projections, selections, joins, and WHERE clauses
- Data manipulation using INSERT, DELETE, UPDATE statements
- Data definition using CREATE, ALTER, DROP statements
- Single row functions like concatenation and conversion and multirow functions like SUM and GROUP BY
The document discusses SQL JOIN statements. It defines an INNER JOIN as returning rows when there is at least one match between two tables. It provides an example of using INNER JOIN to combine data from Customers and Orders tables based on matching CustomerNumber columns. It also provides a simple example using INNER JOIN to extract customer names and total sales amounts from Customers and Sales tables by matching on CustomerID.
SQL is a standard language for managing relational databases and querying data. Key features of SQL include:
- SQL allows users to retrieve, insert, update and delete data in databases. Common commands include SELECT, UPDATE, DELETE, and INSERT.
- SQL queries use clauses like WHERE to filter records and return only the desired data. Operators like =, <, > can be used in the WHERE clause.
- SQL statements are divided into DML (Data Manipulation Language) for queries and DDL (Data Definition Language) for managing database structure.
An introduction to SQL standard language for beginners and non-technical information people. Mostly covers SELECT statement using standard clauses, Joins, Sub-Queries and ...
SQL is a standard language for storing, manipulating and retrieving data in databases. It allows users to access and manipulate data in databases. Some key functions of SQL include executing queries against a database, retrieving data from a database, inserting, updating and deleting records in a database, and creating, altering and dropping database objects like tables.
The document contains 10 questions regarding Transact-SQL queries on SQL Server databases. Each question provides a scenario and asks which T-SQL query should be used. The questions cover topics such as retrieving data in XML format, ranking students by average marks, retrieving the highest marks for each subject, creating indexed views, computed columns, and auditing column updates. Sample answers are provided for each question along with brief explanations or references.
SQL is a standard language for managing relational databases and querying data. Key features of SQL include retrieving, inserting, updating, and deleting data. The document provides examples of common SQL statements like SELECT, WHERE, ORDER BY, INSERT, UPDATE, and DELETE and how they can be used to work with data in database tables. It also explains concepts like SQL data manipulation language (DML) and data definition language (DDL) as well as SQL data types, operators, and syntax.
SQL is a standard language for accessing and manipulating database systems. It allows users to define, manipulate, and query data within a relational database. Key statements in SQL include SELECT to query data, INSERT to add new rows, UPDATE to modify rows, and DELETE to remove rows. SQL also supports functions like DISTINCT, WHERE, ORDER BY, and JOIN to filter, sort, and combine data across tables respectively.
This document provides an introduction to SQL (Structured Query Language). It defines SQL as a standard language for accessing and manipulating databases. The key points covered include:
- SQL lets you perform queries against a database to retrieve, insert, update, and delete data. It can also be used to create and modify database structures.
- Common SQL commands covered are SELECT, INSERT, UPDATE, DELETE, CREATE TABLE, ALTER TABLE, DROP TABLE.
- Additional SQL concepts explained are data types, WHERE clauses, ORDER BY clauses, GROUP BY clauses, and JOIN operations.
- RDBMS systems like MySQL, SQL Server, Oracle, etc. use SQL to communicate with the databases they manage.
Introduction to SQL (for Chicago Booth MBA technology club)Jennifer Berk
Introduction to SQL for MBA students, presented spring 2012 to the Chicago Booth technology club.
Why an MBA would want to know SQL, a sandbox to practice in, and the basics of SQL syntax so you can pull your own datasets to analyze.
SQL is a standard language for accessing and manipulating databases. It allows users to perform operations like querying data, inserting records, updating records and deleting records from databases. Some key SQL statements include SELECT to query data, INSERT INTO to insert new records, UPDATE to modify records and DELETE to remove records. SQL also supports clauses like WHERE to filter records and ORDER BY to sort the results.
The document discusses various SQL statements used for database, table, column, and record operations. It covers how to create, delete, and rename databases and tables. It also explains how to add, modify, and delete columns, set default values and unique constraints on columns. The document also covers creating indexes, procedures, functions, check constraints, and updating records.
This document discusses summary queries in SQL. It explains that summary queries are used to retrieve aggregate or summary information rather than details of individual records. It describes SQL column functions such as SUM, AVG, MIN, MAX, COUNT that can be used to summarize data. It also discusses GROUP BY and HAVING clauses that allow grouping and filtering of aggregated data. Subqueries and the CASE statement for conditional logic in SQL queries are also briefly covered.
The document discusses various SQL query concepts including:
1. Search conditions (predicates) in SQL queries including comparison tests, range tests, set membership tests, pattern matching tests, and null value tests.
2. The UNION feature allows combining the results of two or more queries into a single table. Query results combined with UNION can be sorted using an ORDER BY clause.
3. JOIN operations combine data from two or more tables by linking a column in one table with that in another table. Inner joins and outer joins are explained with examples.
This document provides an overview and goals for a book on advanced SQL tips and tricks. It discusses topics covered in the book such as scalar functions, analytic functions, complex subqueries, common table expressions, and XML tricks. The document also provides examples of SQL code snippets demonstrating various techniques, including finding values containing percentages, combining values into a single row, correlating vs simple subqueries, and using common table expressions.
The document provides an introduction to SQL, including:
- SQL is a standard language for accessing and manipulating databases. It allows users to execute queries, retrieve, insert, update and delete data from databases.
- RDBMS (Relational Database Management System) is the basis for SQL and modern database systems like MySQL, SQL Server, Oracle etc. Data is stored in database objects called tables which consist of columns and rows.
- The CREATE DATABASE and CREATE TABLE statements are used to create databases and tables. Columns are given data types and tables can be populated with data using the INSERT statement.
- Constraints like NOT NULL, UNIQUE, PRIMARY KEY etc are used to limit the type of data that
SQL is a standard language for accessing and manipulating databases. The document provides an introduction to SQL basics including SQL statements to select, insert, update and delete data from database tables. It explains key SQL components like the WHERE clause for filtering records and the ORDER BY clause for sorting query results. Examples are given for each SQL statement and concept discussed.
DDL(Data defination Language ) Using OracleFarhan Aslam
The document discusses DDL and DCL commands in Oracle including naming rules for objects, data types, creating tables, constraints, defining constraints, updating and violating constraints, creating tables using subqueries, altering tables, views, sequences, granting and revoking privileges, and dropping tables. It also discusses the Oracle data dictionary.
SQL is a standard language for accessing and manipulating databases. It allows users to retrieve, insert, update, and delete data as well as create new databases and tables. Common SQL statements include SELECT, UPDATE, DELETE, and INSERT. SQL uses clauses, operators, and wildcards to filter records based on conditions. Some key points are that SQL is an ANSI standard but different versions exist, it allows querying and modifying data in databases, and is essential for interacting with relational database systems.
The document provides an overview of database architecture and basic concepts such as what a database is, structured query language (SQL), and stored procedures. A database allows for structured storage and retrieval of complex data. SQL is used to manipulate and retrieve data from databases. Stored procedures are programs stored in databases that perform specific tasks like validating arguments. They provide benefits like improved performance and protection of database integrity.
This document provides information about SQL queries and joins. It begins by introducing SQL (Structured Query Language) which is used to communicate with databases and retrieve required information. It describes the basic CRUD (Create, Read, Update, Delete) functions of SQL. It then discusses different types of SQL queries - aggregate function queries, scalar function queries, and join queries. It provides the syntax and explanation of inner joins, outer joins (left, right, full) which are used to query data from multiple tables based on relationships between columns. The document is presented by Hammad, Bilal and Awais.
The document provides an introduction to SQL and covers various SQL clauses and functions including:
- Data retrieval using SELECT statements with projections, selections, joins, and WHERE clauses
- Data manipulation using INSERT, DELETE, UPDATE statements
- Data definition using CREATE, ALTER, DROP statements
- Single row functions like concatenation and conversion and multirow functions like SUM and GROUP BY
The document discusses SQL JOIN statements. It defines an INNER JOIN as returning rows when there is at least one match between two tables. It provides an example of using INNER JOIN to combine data from Customers and Orders tables based on matching CustomerNumber columns. It also provides a simple example using INNER JOIN to extract customer names and total sales amounts from Customers and Sales tables by matching on CustomerID.
SQL is a standard language for managing relational databases and querying data. Key features of SQL include:
- SQL allows users to retrieve, insert, update and delete data in databases. Common commands include SELECT, UPDATE, DELETE, and INSERT.
- SQL queries use clauses like WHERE to filter records and return only the desired data. Operators like =, <, > can be used in the WHERE clause.
- SQL statements are divided into DML (Data Manipulation Language) for queries and DDL (Data Definition Language) for managing database structure.
An introduction to SQL standard language for beginners and non-technical information people. Mostly covers SELECT statement using standard clauses, Joins, Sub-Queries and ...
SQL is a standard language for storing, manipulating and retrieving data in databases. It allows users to access and manipulate data in databases. Some key functions of SQL include executing queries against a database, retrieving data from a database, inserting, updating and deleting records in a database, and creating, altering and dropping database objects like tables.
The document contains 10 questions regarding Transact-SQL queries on SQL Server databases. Each question provides a scenario and asks which T-SQL query should be used. The questions cover topics such as retrieving data in XML format, ranking students by average marks, retrieving the highest marks for each subject, creating indexed views, computed columns, and auditing column updates. Sample answers are provided for each question along with brief explanations or references.
SQL is a standard language for managing relational databases and querying data. Key features of SQL include retrieving, inserting, updating, and deleting data. The document provides examples of common SQL statements like SELECT, WHERE, ORDER BY, INSERT, UPDATE, and DELETE and how they can be used to work with data in database tables. It also explains concepts like SQL data manipulation language (DML) and data definition language (DDL) as well as SQL data types, operators, and syntax.
SQL is a standard language for accessing and manipulating database systems. It allows users to define, manipulate, and query data within a relational database. Key statements in SQL include SELECT to query data, INSERT to add new rows, UPDATE to modify rows, and DELETE to remove rows. SQL also supports functions like DISTINCT, WHERE, ORDER BY, and JOIN to filter, sort, and combine data across tables respectively.
This document provides an introduction to SQL (Structured Query Language). It defines SQL as a standard language for accessing and manipulating databases. The key points covered include:
- SQL lets you perform queries against a database to retrieve, insert, update, and delete data. It can also be used to create and modify database structures.
- Common SQL commands covered are SELECT, INSERT, UPDATE, DELETE, CREATE TABLE, ALTER TABLE, DROP TABLE.
- Additional SQL concepts explained are data types, WHERE clauses, ORDER BY clauses, GROUP BY clauses, and JOIN operations.
- RDBMS systems like MySQL, SQL Server, Oracle, etc. use SQL to communicate with the databases they manage.
Introduction to SQL (for Chicago Booth MBA technology club)Jennifer Berk
Introduction to SQL for MBA students, presented spring 2012 to the Chicago Booth technology club.
Why an MBA would want to know SQL, a sandbox to practice in, and the basics of SQL syntax so you can pull your own datasets to analyze.
SQL is a standard language for accessing and manipulating databases. It allows users to perform operations like querying data, inserting records, updating records and deleting records from databases. Some key SQL statements include SELECT to query data, INSERT INTO to insert new records, UPDATE to modify records and DELETE to remove records. SQL also supports clauses like WHERE to filter records and ORDER BY to sort the results.
The document discusses various SQL statements used for database, table, column, and record operations. It covers how to create, delete, and rename databases and tables. It also explains how to add, modify, and delete columns, set default values and unique constraints on columns. The document also covers creating indexes, procedures, functions, check constraints, and updating records.
This document discusses summary queries in SQL. It explains that summary queries are used to retrieve aggregate or summary information rather than details of individual records. It describes SQL column functions such as SUM, AVG, MIN, MAX, COUNT that can be used to summarize data. It also discusses GROUP BY and HAVING clauses that allow grouping and filtering of aggregated data. Subqueries and the CASE statement for conditional logic in SQL queries are also briefly covered.
The document discusses various SQL query concepts including:
1. Search conditions (predicates) in SQL queries including comparison tests, range tests, set membership tests, pattern matching tests, and null value tests.
2. The UNION feature allows combining the results of two or more queries into a single table. Query results combined with UNION can be sorted using an ORDER BY clause.
3. JOIN operations combine data from two or more tables by linking a column in one table with that in another table. Inner joins and outer joins are explained with examples.
This document provides an overview and goals for a book on advanced SQL tips and tricks. It discusses topics covered in the book such as scalar functions, analytic functions, complex subqueries, common table expressions, and XML tricks. The document also provides examples of SQL code snippets demonstrating various techniques, including finding values containing percentages, combining values into a single row, correlating vs simple subqueries, and using common table expressions.
The document provides an introduction to SQL, including:
- SQL is a standard language for accessing and manipulating databases. It allows users to execute queries, retrieve, insert, update and delete data from databases.
- RDBMS (Relational Database Management System) is the basis for SQL and modern database systems like MySQL, SQL Server, Oracle etc. Data is stored in database objects called tables which consist of columns and rows.
- The CREATE DATABASE and CREATE TABLE statements are used to create databases and tables. Columns are given data types and tables can be populated with data using the INSERT statement.
- Constraints like NOT NULL, UNIQUE, PRIMARY KEY etc are used to limit the type of data that
SQL is a standard language for accessing and manipulating databases. The document provides an introduction to SQL basics including SQL statements to select, insert, update and delete data from database tables. It explains key SQL components like the WHERE clause for filtering records and the ORDER BY clause for sorting query results. Examples are given for each SQL statement and concept discussed.
DDL(Data defination Language ) Using OracleFarhan Aslam
The document discusses DDL and DCL commands in Oracle including naming rules for objects, data types, creating tables, constraints, defining constraints, updating and violating constraints, creating tables using subqueries, altering tables, views, sequences, granting and revoking privileges, and dropping tables. It also discusses the Oracle data dictionary.
SQL is a standard language for accessing and manipulating databases. It allows users to retrieve, insert, update, and delete data as well as create new databases and tables. Common SQL statements include SELECT, UPDATE, DELETE, and INSERT. SQL uses clauses, operators, and wildcards to filter records based on conditions. Some key points are that SQL is an ANSI standard but different versions exist, it allows querying and modifying data in databases, and is essential for interacting with relational database systems.
The document provides an overview of database architecture and basic concepts such as what a database is, structured query language (SQL), and stored procedures. A database allows for structured storage and retrieval of complex data. SQL is used to manipulate and retrieve data from databases. Stored procedures are programs stored in databases that perform specific tasks like validating arguments. They provide benefits like improved performance and protection of database integrity.
This document provides an overview of SQL (Structured Query Language) including key statements and concepts. It discusses the different types of SQL statements including DDL for definitions, DML for data manipulation, and DCL for access control. It also summarizes important SQL statements and clauses like SELECT, INSERT, UPDATE, DELETE, WHERE, GROUP BY, HAVING, ORDER BY and more. The document is intended as an introduction to the SQL language and relational database concepts.
The document provides an introduction to the SQL language, including its main components of DML (Data Manipulation Language) and DDL (Data Definition Language). It discusses SQL concepts such as creating tables with data types, defining primary and foreign keys, and using basic queries with SELECT, FROM, WHERE and ORDER BY clauses.
This document provides an overview of SQL (Structured Query Language) and its main components. It discusses SQL query types like SELECT, INSERT, UPDATE, and DELETE statements. It also covers SQL joins, aliases, clauses, functions, conditions, tables and views. Finally, it provides examples and practice exercises for the SELECT and INSERT statements.
SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems. SQL statements are used to retrieve and update data in a database. SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc.
NewyorkSys is one of the leading top Training and Consulting Company in US. Newyorksys have certified trainers. We will provide Online Training, Fast Track online training, with job assistance. We are providing excellent Training in all courses.
The document discusses the components of the SQL Server database engine and services. The database engine includes key processes like the algebrizer, query optimizer, query engine, storage engine, buffer manager, and lock manager. SQL Server services allow controlling and communicating with SQL Server, including the SQL Server Agent, Database Mail, and Distributed Transaction Coordinator. The document also covers SQL statements, query flow, joins, and including data with subqueries and common table expressions.
This book can teach you a variety of topics, depending on your level of experience with SQL Server and what you want to learn. Here are some of the topics that a typical MS SQL Server tutorial may cover:
Introduction to relational databases - A tutorial on MS SQL Server usually starts with an overview of the concepts and principles of relational databases, including tables, columns, rows, primary keys, and foreign keys.
Basic SQL queries - The tutorial may cover the basics of SQL syntax and teach you how to write simple SELECT, INSERT, UPDATE, and DELETE statements.
Advanced SQL queries - The tutorial may cover more complex SQL queries, including JOINs, subqueries, and aggregation functions.
Database design and normalization - The tutorial may cover the principles of database design and normalization, and teach you how to create and modify database schemas.
Stored procedures and functions - The tutorial may cover how to create and use stored procedures and functions to encapsulate SQL code and improve performance.
Database administration and security - The tutorial may cover topics related to database administration and security, including backups and restores, user permissions, and authentication modes.
These are just some of the topics that a MS SQL Server tutorial may cover. The specific content and level of detail will depend on the tutorial and the intended audience.
SQL is a relational database language used to define, manipulate, and control access to data in a relational database. SQL statements are used to perform tasks like data retrieval, insertion, deletion, updating and table/database management. The basic structure of an SQL query involves selecting data from one or more tables to display or use. SQL supports features like constraints, indexes, views, triggers that enforce data integrity and security.
The document provides information on various SQL commands used to create and manage databases and tables. It explains how to use SHOW, CREATE DATABASE, USE, SHOW TABLES, CREATE TABLE, DESCRIBE, ALTER TABLE, SELECT, UPDATE, DELETE, INSERT, CREATE VIEW commands. It also discusses table constraints like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY and provides examples of how to implement them in CREATE TABLE and ALTER TABLE statements.
This document provides an overview of SQL commands and examples, including SELECT, WHERE, ORDER BY, INSERT, UPDATE, DELETE, JOIN, UNION and more. Key points include:
- SQL is a standard language for accessing and manipulating databases and became an ANSI and ISO standard in the 1980s.
- Common SQL commands allow users to query data with SELECT, insert/update/delete records, and perform other data management tasks.
- Logical operators like WHERE, AND, OR, NOT allow for filtering query results.
- JOINs combine data from multiple tables by common columns.
- Aggregate functions like COUNT, SUM, AVG perform calculations across record sets.
- Examples
SQL is a standard language for managing relational databases and querying data. It allows users to perform tasks like retrieving, inserting, updating, and deleting data. Some key SQL statements include SELECT to query data, INSERT to add new records, UPDATE to modify existing records, and DELETE to remove records. SQL is widely used with database management systems like MySQL, SQL Server, and Oracle.
SQL (Structured Query Language) is a standard language for accessing and manipulating databases. It allows users to execute queries against a database, retrieve data from a database, insert records into a database, update records in a database, and delete records from a database. Common SQL statements include SELECT to retrieve data, INSERT to add data, UPDATE to modify data, DELETE to remove data, and CREATE/ALTER to manage tables and databases.
This document provides an introduction to SQL (Structured Query Language). It defines SQL as a standard language for accessing and manipulating databases. It describes some key SQL commands like SELECT, WHERE, AND, OR, NOT, ORDER BY and explains their usage and syntax. Examples are given using tables from the Northwind sample database to demonstrate how to retrieve, filter and sort data. The document also discusses using SQL with websites to display database content and some database concepts like tables, records and fields.
The document provides an overview of SQL (Structured Query Language) including its basic concepts, components, and capabilities. SQL is a non-procedural language used to query and manipulate data in relational database management systems. It allows users to select, insert, update, and delete data. The main components of SQL are the data definition language for defining database structure and the data manipulation language for retrieving and updating data.
This document provides an overview of Structured Query Language (SQL) and SQL Server by Brian Foote. It includes sections on SQL SELECT statements, joins, aggregate functions and more. The document covers basics like retrieving data from single and multiple tables, using ORDER BY, WHERE, and DISTINCT clauses. It also discusses aggregate functions like COUNT, MAX, MIN, AVG and SUM and using them with GROUP BY. Finally, it touches on other SQL topics like different join types, subqueries, temporary tables and exporting data to Excel.
The chapter Lifelines of National Economy in Class 10 Geography focuses on the various modes of transportation and communication that play a vital role in the economic development of a country. These lifelines are crucial for the movement of goods, services, and people, thereby connecting different regions and promoting economic activities.
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.pptHenry Hollis
The History of NZ 1870-1900.
Making of a Nation.
From the NZ Wars to Liberals,
Richard Seddon, George Grey,
Social Laboratory, New Zealand,
Confiscations, Kotahitanga, Kingitanga, Parliament, Suffrage, Repudiation, Economic Change, Agriculture, Gold Mining, Timber, Flax, Sheep, Dairying,
Temple of Asclepius in Thrace. Excavation resultsKrassimira Luka
The temple and the sanctuary around were dedicated to Asklepios Zmidrenus. This name has been known since 1875 when an inscription dedicated to him was discovered in Rome. The inscription is dated in 227 AD and was left by soldiers originating from the city of Philippopolis (modern Plovdiv).
How to Make a Field Mandatory in Odoo 17Celine George
In Odoo, making a field required can be done through both Python code and XML views. When you set the required attribute to True in Python code, it makes the field required across all views where it's used. Conversely, when you set the required attribute in XML views, it makes the field required only in the context of that particular view.
2. SQL Tutorial: Introduction
What is SQL?
SQL is a language used to retrieve and manipulate data in a RDMS.
SQL stands for Structured Query Language.
What is a Database?
A database is a place to store data.
A relational database system (RDMS) stores data in tables.
Relational Database Tables
A relational database stores data in tables. Each table has a number of rows and
columns.
The table below has 4 rows and 3 columns.
SQL and Relational Databases
A relational database contains tables which store data that is related in some way.
SQL is the language that allows retrieval and manipulation of table data in a
relational database.
The database below has 2 tables: one with data on Users and another with data
on Products.
3. .
Example database
This tutorial uses a database which is a modernized version of Microsoft's
Northwind database. Northwind is a fictitious store that sells specialty food
products from all over the world. The database has 5 tables.
Below are an Entity Relationship Diagram (ERD) which shows the tables and their
relationships.
4. SQL Syntax
The syntax of a language describes the language elements.
SQL statements are somewhat like simple English sentences.
Keywords include SELECT, UPDATE, WHERE, ORDER BY, etc.
ANSI Standard SQL is the lingua franca for relational databases.
The SQL Syntax
SQL was designed to be entered on a console and results would display back to a
screen.
Today, SQL is mostly used by programmers who use SQL inside their language to
build applications that access data in a database.
Four fundamental operations that apply to any database are:
1. Read the data -- SELECT
2. Insert new data -- INSERT
3. Update existing data -- UPDATE
4. Remove data -- DELETE
Collectively these are referred to as CRUD (Create, Read, Update, and Delete).
The general form for each of these 4 operations in SQL is presented next.
The SQL SELECT general form
1. SELECT column-names FROM table-name WHERE condition
ORDER BY sort-order
Example:
1. SELECT FirstName, LastName, City, Country FROM Customer
WHERE City = 'Paris' ORDER BY LastName
The SQL INSERT general form
1. INSERT table-name (column-names) VALUES (column-values)
Example:
1. INSERT Supplier (Name, ContactName, City, Country)
VALUES ('Oxford Trading', 'Ian Smith', 'Oxford', 'UK')
5. The SQL UPDATE general form
1. UPDATE table-name SET column-name = column-value WHERE condition
Example:
1. UPDATE OrderItem SET Quantity = 2 WHERE Id = 388
The SQL DELETE general form
1. DELETE table-name WHERE condition
Example:
1. DELETE Customer WHERE Email = 'alex@gmail.com'
SQL SELECT Statement
The SELECT statement retrieves data from a database.
The data is returned in a table-like structure called a result-set.
SELECT is the most frequently used action on a database.
The SQL SELECT syntax
The general syntax is:
1. SELECT column-names FROM table-name
USING *
1. SELECT * FROM table-name
SQL SELECT Examples
Problem: List all customers
1. SELECT * FROM Customer
Problem: List the first name, last name, and city of all customers
1. SELECT FirstName, LastName, City FROM Customer
6. SQL WHERE Clause
To limit the number of rows use the WHERE clause.
The WHERE clause filters for rows that meet certain criteria.
WHERE is followed by a condition that returns either true or false.
WHERE is used with SELECT, UPDATE, and DELETE.
The SQL WHERE syntax
A WHERE clause with a SELECT statement:
1. SELECT column-names FROM table-name WHERE condition
A WHERE clause with an UPDATE statement:
1. UPDATE table-name SET column-name = value WHERE condition
A WHERE clause with a DELETE statement:
1. DELETE table-name WHERE condition
SQL WHERE Clause Examples
Problem: List the customers in Sweden
1. SELECT Id, FirstName, LastName, City, Country, Phone FROM Customer
WHERE Country = 'Sweden'
Problem: Update the city to Sydney for supplier Pavlova, Ltd.
1. UPDATE Supplier SET City = 'Sydney' WHERE Name = 'Pavlova, Ltd.'
Problem: Delete all products with unit price higher than $50.
1. DELETE FROM Product WHERE UnitPrice > 50
Note: Referential integrity may prevent this deletion.
A better approach may be to discontinue the product, that is, set Is Discontinued
to true.
7. SQL INSERT INTO Statement
The INSERT INTO statement is used to add new data to a database.
The INSERT INTO statement adds a new record to a table.
INSERT INTO can contain values for some or all of its columns.
INSERT INTO can be combined with a SELECT to insert records.
The SQL INSERT INTO syntax
The general syntax is:
1. INSERT INTO table-name (column-names) VALUES (values) OR
2. INSERT INTO table-name VALUES (column-names)
SQL INSERT INTO Examples
Problem: Add a record for a new customer
1. INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
VALUES ('Craig', 'Smith', 'New York', 'USA', 1-01-993 2800)
OR
2. INSERT INTO Customer VALUES ('Craig', 'Smith', 'New York', 'USA', 1-01-
993 2800)
Problem: Add a new customer named Anita Coats to the database
1. INSERT INTO Customer (FirstName, LastName) VALUES ('Anita', 'Coats')
The SQL INSERT combined with a SELECT
The general syntax is:
1. INSERT INTO table-name (column-names) SELECT column-names
FROM table-name WHERE condition
SQL INSERT INTO with SELECT Example
Problem: The Bigfoot Brewery supplier is also a customer.
Add a customer record with values from the supplier table.
1. INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
SELECT LEFT (ContactName, CHARINDEX (' ',ContactName) - 1),
SUBSTRING (ContactName, CHARINDEX (' ',ContactName) + 1, 100),
City, Country, Phone FROM Supplier WHERE CompanyName = 'Bigfoot
Breweries'
8. Note: ContactName is parsed into FirstName and LastName.
Parsing takes place with built-in functions: LEFT, SUBSTRING, and CHARINDEX.
SQL UPDATE Statement
The UPDATE statement updates data values in a database.
UPDATE can update one or more records in a table.
Use the WHERE clause to UPDATE only specific records.
The SQL UPDATE syntax
1. UPDATE table-name SET column-name = value, column-name = value,
To limit the number of records to UPDATE append a WHERE clause:
1. UPDATE table-name SET column-name = value, column-name = value,
WHERE condition
SQL UPDATE Examples
Problem: discontinue all products in the database
1. UPDATE Product SET IsDiscontinued = 1
Note: the value 1 denotes true.
Problem: Discontinue products over $50.
1. UPDATE Product SET IsDiscontinued = 1 WHERE UnitPrice > 50
Note: the value 1 denotes true.
Problem: Discontinue product with Id = 46.
1. UPDATE Product SET IsDiscontinued = 1 WHERE Id = 46
This is a more common scenario in which a single record is updated.
Note: the value 1 denotes true.
Problem: Supplier Norske Meierier (Id = 15) has moved: update their city, phone
and fax.
1. UPDATE Supplier SET City = 'Oslo', Phone = '(0)1-953530',
Fax = '(0)1- 953555' WHERE Id = 15
This is a common scenario in which a single record is updated.
9. SQL DELETE Statement
DELETE permanently removes records from a table.
DELETE can delete one or more records in a table.
Use the WHERE clause to DELETE only specific records.
The SQL DELETE syntax
The general syntax is:
1. DELETE table-name
To delete specific records append a WHERE clause:
1. DELETE table-name WHERE condition
SQL DELETE Examples
Problem: Delete all products.
1. DELETE Product
Problem: Delete products over $50.
1. DELETE Product WHERE UnitPrice > 50
Problem: Delete customer with Id = 21.
1. DELETE Customer WHERE Id = 21
This is a more common scenario in which a single record is deleted.
SQL ORDER BY Clause
SELECT returns records in no particular order.
To ensure a specific order use the ORDER BY clause.
ORDER BY allows sorting by one or more columns.
Records can be returned in ascending or descending order.
The SQL ORDER BY syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE condition ORDER BY
Column-names
10. SQL ORDER BY Examples
Problem: List all suppliers in alphabetical order
1. SELECT CompanyName, ContactName, City, Country FROM Supplier
ORDER BY CompanyName
The default sort order is ascending, that is, low-high or 1-100
Problem: List all suppliers in reverse alphabetical order
1. SELECT CompanyName, ContactName, City, Country FROM Supplier
ORDER BY CompanyName DESC
The keyword DESC denotes descending, i.e., reverse order 100 - 1.
Problem: List all customers ordered by country, then by city within each country
ordering by one or more columns is possible.
1. SELECT FirstName, LastName, City, Country FROM Customer
ORDER BY Country, City
Problem: List all suppliers in the USA, Japan, and Germany, ordered by city,
then by company name in reverse order
1. SELECT Id, CompanyName, City, Country FROM Supplier WHERE Country
IN ('USA', 'Japan', 'Germany') ORDER BY Country ASC, CompanyName
DESC
This shows that you can order by more than one column.
ASC denotes ascending, but is optional as it is the default sort order.
Problem: Show all orders, sorted by total amount, the largest first, within each
year
1. SELECT Id, OrderDate, CustomerId, TotalAmount FROM [Order] ORDER
BY YEAR(OrderDate) ASC, TotalAmount DESC
Note: DESC means descending, but is optional as it is the default sort order.
[Order] must be bracketed because it also is a key work in SQL.
Notice the year breakpoints: 2012 - 2013 and 2013 - 2014. Each year starts with
the highest TotalAmounts.
11. This shows that other data types, such as numbers, dates, and bits can also be
sorted.
Note: YEAR is a built-in function which returns the year from a date.
SQL SELECT TOP Statement
The SELECT TOP statement returns a specified number of records.
SELECT TOP is useful when working with very large datasets.
Non SQL Server databases use keywords like LIMIT, OFFSET, and ROWNUM.
The SQL SELECT TOP syntax
The general syntax is:
1. SELECT TOP n column-names FROM table-name
SQL SELECT TOP
Problem: List top 10 most expensive products
1. SELECT TOP 10 Id, ProductName, UnitPrice, Package FROM Product
ORDER BY UnitPrice DESC
SQL OFFSET-FETCH Clause
OFFSET excludes the first set of records.
OFFSET can only be used with an ORDER BY clause.
OFFSET with FETCH NEXT returns a defined window of records.
OFFSET with FETCH NEXT is great for building pagination support.
The SQL ORDER BY OFFSET syntax
The general syntax to exclude first n records is:
1. SELECT column-names FROM table-name ORDER BY column-names
OFFSET n ROWS
To exclude first n records and return only the next m records:
1. SELECT column-names FROM table-name ORDER BY column-names
OFFSET n ROWS FETCH NEXT m ROWS ONLY
This will return only record (n + 1) to (n + 1 + m). See example below.
12. SQL OFFSET-FETCH Examples
Problem: Get all but the 10 most expensive products sorted by price
1. SELECT Id, ProductName, UnitPrice, Package FROM Product
ORDER BY UnitPrice DESC OFFSET 10 ROWS
Problem: Get the 10th to 15th most expensive products sorted by price
1. SELECT Id, ProductName, UnitPrice, Package FROM Product
ORDER BY UnitPrice DESC OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY
SQL SELECT DISTINCT Statement
SELECT DISTINCT returns only distinct (different) values.
SELECT DISTINCT eliminates duplicate records from the results.
DISTINCT can be used with aggregates: COUNT, AVG, MAX, etc.
DISTINCT operates on a single column. DISTINCT for multiple columns is not supported.
The SQL SELECT DISTINCT syntax
The general syntax is:
1. SELECT DISTINCT column-name FROM table-name
Can be used with COUNT and other aggregates
1. SELECT COUNT (DISTINCT column-name)FROM table-name
SQL SELECT Examples
Problem: List all supplier countries in alphabetical order.
1. SELECT DISTINCT Country FROM Supplier ORDER BY
COUNTRY
Problem: List the number of supplier countries
1. SELECT COUNT (DISTINCT Country) FROM Supplier
13. SQL SELECT MIN, MAX Statement
SELECT MIN returns the minimum value for a column.
SELECT MAX returns the maximum value for a column.
The SQL SELECT MIN and MAX syntax
The general MIN syntax is:
1. SELECT MIN(column-name) FROM table-name
The general MAX syntax is:
1. SELECT MAX(column-name) FROM table-name
SQL SELECT MAX and MIN Examples
Problem: Find the largest order placed in 2014
1. SELECT MAX(TotalAmount) FROM [Order] WHERE YEAR(OrderDate) =
2014
Problem: Find the last order date in 2013
1. SELECT MAX(OrderDate) FROM [Order] WHERE YEAR(OrderDate) =
2013 MIN and MAX can also be used with numeric and date types.
SQL SELECT COUNT, SUM, AVG
SELECT COUNT returns a count of the number of data values.
SELECT SUM returns the sum of the data values.
SELECT AVG returns the average of the data values.
The SQL SELECT COUNT, SUM, and AVG syntax
The general COUNT syntax is:
1. SELECT COUNT(column-name) FROM table-name
The general SUM syntax is:
1. SELECT SUM(column-name)FROM table-name
The general AVG syntax is:
1. SELECT AVG(column-name)FROM table-name
14. SQL SELECT COUNT, SUM, and AVG Examples
Problem: Find the number of customers
1. SELECT COUNT(Id)FROM Customer
Problem: Compute the total amount sold in 2013
1. SELECT SUM(TotalAmount) FROM [Order] WHERE YEAR(OrderDate) =
2013
Problem: Compute the average size of all orders
1. SELECT AVG(TotalAmount) FROM [Order]
SQL WHERE AND, OR, NOT Clause
WHERE conditions can be combined with AND, OR, and NOT.
A WHERE clause with AND requires that two conditions are true.
A WHERE clause with OR requires that one of two conditions is true.
A WHERE clause with NOT negates the specified condition.
The WHERE with AND, OR, NOT syntax
A WHERE clause with AND:
1. SELECT column-names FROM table-name WHERE condition1 AND
condition2
A WHERE clause with OR:
1. UPDATE table-name SET column-name = value WHERE condition1 OR
condition2
A WHERE clause with NOT:
1. DELETE table-name WHERE NOT condition
SQL WHERE with AND, OR, and NOT Examples
Problem: Get customer named Thomas Hardy
1. SELECT Id, FirstName, LastName, City, Country FROM Customer
WHERE FirstName = 'Thomas' AND LastName = 'Hardy'
15. Problem: List all customers from Spain or France
1. SELECT Id, FirstName, LastName, City, Country FROM Customer
WHERE Country = 'Spain' OR Country = 'France'
Problem: List all customers that are not from the USA
1. SELECT Id, FirstName, LastName, City, Country FROM Customer
WHERE NOT Country = 'USA'
Problem: List all orders that not between $50 and $15000
1. SELECT Id, OrderDate, CustomerId, TotalAmount FROM [Order]
WHERE NOT (TotalAmount >= 50 AND TotalAmount <= 15000) ORDER BY
TotalAmount DESC
SQL WHERE BETWEEN Clause
WHERE BETWEEN returns values that fall within a given range.
WHERE BETWEEN is a shorthand for >= AND <=.
BETWEEN operators is inclusive: begin and end values are included. The
definitive guide for data professionals
The SQL WHERE BETWEEN syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE column-name
BETWEEN value1 AND value2
SQL WHERE BETWEEN Examples
Problem: List all products between $10 and $20
1. SELECT Id, ProductName, UnitPrice FROM Product WHERE UnitPrice
BETWEEN 10 AND 20 ORDER BY UnitPrice
Problem: List all products not between $10 and $100 sorted by price.
1. SELECT Id, ProductName, UnitPrice FROM Product WHERE UnitPrice
NOT BETWEEN 5 AND 100 ORDER BY UnitPrice
16. Problem: Get the number of orders and amount sold between Jan 1, 2013 and Jan
31, 2013.
1. SELECT COUNT(Id), SUM(TotalAmount)FROM [Order] WHERE OrderDate
BETWEEN '1/1/2013' AND '1/31/2013'
SQL WHERE IN Clause
WHERE IN returns values that matches values in a list or sub query.
WHERE IN is a shorthand for multiple OR conditions.
The SQL WHERE IN syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE column-name IN
(values)
SQL WHERE IN Examples
Problem: List all suppliers from the USA, UK, OR Japan
1. SELECT Id, CompanyName, City, Country FROM Supplier WHERE Country
IN ('USA', 'UK', and ‘Japan’)
Problem: List all products that are not exactly $10, $20, $30, $40, or $50
1. SELECT Id, ProductName, UnitPrice FROM Product WHERE UnitPrice
NOT IN (10, 20, 30, 40, 50)
Problem: List all customers that are from the same countries as the suppliers.
1. SELECT Id, FirstName, LastName, Country FROM Customer WHERE
Country IN (SELECT Country FROM Supplier)
17. SQL WHERE LIKE Statement
WHERE LIKE determines if a character string matches a pattern.
Use WHERE LIKE when only a fragment of a text value is known.
WHERE LIKE supports two wildcard match options: % and _.
The SQL WHERE LIKE syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE column-
name LIKE value
Optional Wildcard characters allowed in 'value' are % (percent) and _
(underscore).
A % matches any string with zero or more characters.
An _ matches any single character.
SQL WHERE LIKE Examples
Problem: List all products with names that start with 'Ca'
1. SELECT Id, ProductName, UnitPrice, Package FROM Product WHERE
ProductName LIKE 'Ca%'
Problem: List all products that start with 'Cha' or 'Chan' and have one more
character.
1. SELECT Id, ProductName, UnitPrice, Package FROM Product
WHERE ProductName LIKE 'Cha_' OR ProductName LIKE 'Chan_'
SQL IS NULL Clause
NULL is a special value that signifies 'no value'.
Comparing a column to NULL using the = operator is undefined.
Instead, use WHERE IS NULL or WHERE IS NOT NULL.
The SQL WHERE IS NULL syntax
18. The general syntax is:
1. SELECT column-names FROM table-name WHERE column-name IS NULL
The general not null syntax is:
1. SELECT column-names FROM table-name WHERE column-name IS NOT
NULL
SQL WHERE IS NULL Examples
Problem: List all suppliers that have no fax number
1. SELECT Id, CompanyName, Phone, Fax FROM Supplier WHERE Fax IS
NULL
Problem: List all suppliers that do have a fax number
1. SELECT Id, CompanyName, Phone, Fax FROM Supplier WHERE Fax IS
NOT NULL
SQL GROUP BY Clause
The GROUP BY clause groups records into summary rows.
GROUP BY returns one records for each group.
GROUP BY typically also involves aggregates: COUNT, MAX, SUM, AVG, etc.
GROUP BY can group by one or more columns.
The SQL GROUP BY syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE condition GROUP BY
column-names
The general syntax with ORDER BY is:
1. SELECT column-names FROM table-name WHERE condition GROUP BY
column-names ORDER BY column-names
19. SQL GROUP BY Examples
Problem: List the number of customers in each country
1. SELECT COUNT(Id), Country FROM Customer GROUP BY Country
Problem: List the number of customers in each country sorted high to low
1. SELECT COUNT(Id), Country FROM Customer GROUP BY Country
ORDER BY COUNT(Id) DESC
Problem: List the total amount ordered for each customer
SELECT SUM(O.TotalPrice), C.FirstName, C.LastName FROM [Order] O
JOIN Customer C ON O.CustomerId = C.Id GROUP BY C.FirstName,
C.LastName ORDER BY SUM(O.TotalPrice) DESC
This query uses a JOIN with Customer to obtain customer names
SQL HAVING Clause
HAVING filters records that work on summarized GROUP BY results.
HAVING applies to summarized group records, whereas WHERE applies to
individual records.
Only the groups that meet the HAVING criteria will be returned.
HAVING requires that a GROUP BY clause is present.
WHERE and HAVING can be in the same query.
The SQL HAVING syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE condition
GROUP BY column-names HAVING condition
The general syntax with ORDER BY is:
1. SELECT column-names FROM table-name WHERE condition GROUP BY
column- names HAVING condition ORDER BY column-names
20. SQL GROUP BY Examples
Problem: List the number of customers in each country. Only include countries
with more than 10 customers.
1. SELECT COUNT(Id), Country FROM Customer GROUP BY Country
Problem: List the number of customers in each country, except the USA, sorted
high to low.
Only include countries with 9 or more customers.
1. SELECT COUNT(Id), Country FROM Customer WHERE Country <> 'USA'
GROUP BY Country HAVING COUNT (Id) >= 9 ORDER BY COUNT(Id) DESC
Problem: List all customer with average orders between $1000 and $1200.
SELECT AVG(TotalAmount), FirstName, LastName FROM [Order] O JOIN
Customer C ON O.CustomerId = C.Id GROUP BY FirstName, LastName
HAVING AVG(TotalAmount) BETWEEN 1000 AND 1200
SQLAlias
An Alias is a shorthand for a table or column name.
Aliases reduce the amount of typing required to enter a query.
Complex queries with aliases are generally easier to read.
Aliases are useful with JOINs and aggregates: SUM, COUNT, etc.
An Alias only exists for the duration of the query.
The SQL Alias syntax
The general syntax is:
1. SELECT column-name AS alias-name FROM table-name alias-name
WHERE condition
21. SQL Alias Examples
Problem: List total customers in each country.
Display results with easy to understand column headers.
1. SELECT COUNT (C.Id) AS TotalCustomers, C.Country AS Nation FROM
Customer C GROUP BY C.Country TotalCustomers and Nation are column
aliases.
The table alias (C) in this example is not particularly useful.
Problem: List the total amount ordered by customer
with easy to read column headers
1. SELECT C.Id AS Identifier, C.LastName + ', ' + C.FirstName AS CustomerName,
SUM(O.TotalAmount) AS TotalSpent FROM [Order] O JOIN Customer C ON
O.CustomerId = C.Id GROUP BY C.Id, C.LastName + ', ' + C.FirstName ORDER BY
TotalSpent DESC
The aliases significantly simplify writing the JOIN and ORDER BY clauses.
The C alias in C.Id helps identify the Customer Id rather then the Order Id.
SQL JOIN
A SQL JOIN combines records from two tables.
A JOIN locates related column values in the two tables.
A query can contain zero, one, or multiple JOIN operations.
INNER JOIN is the same as JOIN; the keyword INNER is optional.
Different types of JOINs
(INNER) JOIN: Select records that have matching values in both tables.
22. LEFT (OUTER) JOIN: Select records from the first (left-most) table with
matching right table records.
RIGHT (OUTER) JOIN: Select records from the second (right-most) table with
matching left table records.
FULL (OUTER) JOIN: Selects all records that match either left or right table
records.
All INNER and OUTER keywords are optional.
Details about the differences between these JOINs are available in subsequent tutorial pages.
The SQL JOIN syntax
The general syntax is:
1. SELECT column-names FROM table-name1 JOIN table-name2 ON
column-name1 = column-name2 WHERE condition
The general syntax with INNER is:
1. SELECT column-names FROM table-name1 INNER JOIN table-name2
ON column-name1 = column-name2 WHERE condition
Note: The INNER keyword is optional: it is the default as well as the most common
only used JOIN operation.
23. SQL JOIN Examples
Problem: List all orders with customer information
1. SELECT OrderNumber, TotalAmount, FirstName, LastName, City,
Country FROM [Order] JOIN Customer ON [Order].CustomerId =
Customer.Id
In this example using table aliases for [Order] and Customer might have been
useful.
Problem: List all orders with product names, quantities, and prices
1. SELECT O.OrderNumber, CONVERT(date,O.OrderDate) AS Date,
P.ProductName, I.Quantity, I.UnitPrice FROM [Order] O JOIN OrderItem I
ON O.Id = I.OrderId JOIN Product P ON P.Id = I.ProductId ORDER BY
O.OrderNumber
This query performs two JOIN operations with 3 tables.
The O, I, and P are table aliases. Date is a column alias.
SQL LEFT JOIN
LEFT JOIN performs a join starting with the first (left-most) table and then
any matching second (right-most) table records.
LEFT JOIN and LEFT OUTER JOIN are the same.
The SQL LEFT JOIN syntax
The general syntax is:
1. SELECT column-names FROM table-name1 LEFT JOIN table-name2
ON column-name1 = column-name2 WHERE condition
24. SQL LEFT JOIN Example
The general LEFT OUTER JOIN syntax is:
SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country
FROM Customer C LEFT JOIN [Order] O ON O.CustomerId = C.Id ORDER BY
TotalAmount
This will list all customers, whether they placed any order or not.
The ORDER BY TotalAmount shows the customers without orders first
(i.e.TotalMount is NULL).
SQL RIGHT JOIN
RIGHT JOIN performs a join starting with the second (right-most) table and
then any matching first (left-most) table records.
RIGHT JOIN and RIGHT OUTER JOIN are the same.
The SQL RIGHT JOIN syntax
The general syntax is:
1. SELECT column-names FROM table-name1 RIGHT JOIN table-name2
ON column-name1 = column-name2 WHERE condition
The general RIGHT OUTER JOIN syntax is:
1. SELECT column-names FROM table-name1 RIGHT OUTER JOIN table-
name2 ON column-name1 = column-name2 WHERE condition
SQL RIGHT JOIN Example
25. Problem: List customers that have not placed orders
1. SELECT TotalAmount, FirstName, LastName, City, Country FROM [Order]
O RIGHT JOIN Customer C ON O.CustomerId = C.Id WHERE TotalAmount IS
NULL
This returns customers that, when joined, have no matching order.
SQL FULL JOIN
FULL JOIN returns all matching records from both tables whether the other
table matches or not.
FULL JOIN can potentially return very large datasets.
FULL JOIN and FULL OUTER JOIN are the same.
The SQL FULL JOIN syntax
The general syntax is:
1. SELECT column-names FROM table-name1 FULL JOIN table-name2
ON column-name1 = column-name2 WHERE condition
The general FULL OUTER JOIN syntax is:
1. SELECT column-names FROM table-name1 FULL OUTER JOIN table-
name2 ON column-name1 = column-name2 WHERE condition
SQL FULL JOIN Examples
Problem: Match all customers and suppliers by country
1. SELECT C.FirstName, C.LastName, C.Country AS CustomerCountry,
S.Country AS SupplierCountry, S.CompanyName FROM Customer C FULL
JOIN Supplier S ON C.Country = S.Country ORDER BY C.Country, S.Country
26. This returns suppliers that have no customers in their country,
and customers that have no suppliers in their country,
and customers and suppliers that are from the same country.
SQL SELF JOIN
A self JOIN occurs when a table takes a 'selfie'.
A self JOIN is a regular join but the table is joined with itself.
This can be useful when modeling hierarchies.
They are also useful for comparisons within a table
The SQL Self JOIN syntax
The general syntax is:
1. SELECT column-names FROM table-name T1 JOIN table-name T2 WHERE
condition
T1 and T2 are different table aliases for the same table
SQL Self JOIN Examples
Problem: Match customers that are from the same city and country
1. SELECT B.FirstName AS FirstName1, B.LastName AS LastName1,
A.FirstName AS FirstName2, A.LastName AS LastName2,
B.City, B.Country FROM Customer A, Customer B WHERE A.Id <> B.Id
AND A.City = B.City AND A.Country = B.Country ORDER BY A.Country
A and B are aliases for the same Customer table.
SQL UNION Clause
UNION combines the result sets of two queries.
Column data types in the two queries must match.
UNION combines by column position rather than column name.
27. The SQL UNION syntax
The general syntax is:
1. SELECT column-names FROM table-name
UNION
SELECT column-names FROM table-name
SQL UNION Examples
Problem: List all contacts, i.e., suppliers and customers.
1. SELECT 'Customer' As Type, FirstName + ' ' + LastName AS ContactName,
City, Country, Phone FROM Customer
UNION
SELECT 'Supplier', ContactName, City, Country, Phone FROM Supplier
This is a simple example in which the table alias would be useful
SQL Subqueries
A subquery is a SQL query within a query.
Subqueries are nested queries that provide data to the enclosing query.
Subqueries can return individual values or a list of records
Subqueries must be enclosed with parenthesis
The SQL subquery syntax
There is no general syntax;
subqueries are regular queries placed inside parenthesis.
Subqueries can be used in different ways and at different locations inside a query:
Here is an subquery with the IN operator
1. SELECT column-names FROM table-name1 WHERE value IN (SELECT
column-name FROM table-name2 WHERE condition)
Subqueries can also assign column values for each record:
1. SELECT column1 = (SELECT column-name FROM table-
name WHERE condition),column-names FROM table-name
WEHRE condition
28. SQL Subquery Examples
Problem: List products with order quantities greater than 100.
1. SELECT ProductName FROM Product WHERE Id IN (SELECT ProductId
FROM OrderItem WHERE Quantity > 100)
SQL Subquery Examples
Problem: List all customers with their total number of orders
1. SELECT FirstName, LastName,OrderCount = (SELECT COUNT(O.Id) FROM
[Order] O WHERE O.CustomerId = C.Id)FROM Customer C
This is a correlated subquery because the subquery references the enclosing
query (i.e. the C.Id in the WHERE clause).
SQL WHERE ANY, ALL Clause
ANY and ALL keywords are used with a WHERE or HAVING clause.
ANY and ALL operate on subqueries that return multiple values.
ANY returns true if any of the subquery values meet the condition.
ALL returns true if all of the subquery values meet the condition.
The SQL WHERE ANY and ALL syntax
The general ANY syntax is:
1. SELECT column-names FROM table-name WHERE column-name
operator ANY (SELECT column-name FROM table-name WHERE condition)
The general ALL syntax is:
1. SELECT column-names FROM table-name WHERE column-name
operator ALL (SELECT column-name FROM table-name WHERE condition)
SQL ANY Example
Problem: Which products were sold by the unit (i.e. quantity = 1)
1. SELECT ProductName FROM Product WHERE Id = ANY (SELECT ProductId
FROM OrderItem WHERE Quantity = 1)
29. SQL ALL Example
Problem: List customers who placed orders that are
larger than the average of each customer order
1. SELECT DISTINCT FirstName + ' ' + LastName as CustomerName
FROM Customer, [Order] WHERE Customer.Id = [Order].CustomerId
AND TotalAmount > ALL (SELECT AVG(TotalAmount) FROM [Order]
GROUP BY CustomerId)
SQL WHERE EXISTS Statement
WHERE EXISTS tests for the existence of any records in a subquery.
EXISTS returns true if the subquery returns one or more records.
EXISTS is commonly used with correlated subqueries.
The SQL EXISTS syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE EXISTS
(SELECT column- name FROM table-name WHERE condition)
SQL EXISTS Example
Problem: Find suppliers with products over $100.
1. SELECT CompanyName FROM Supplier WHERE EXISTS (SELECT
ProductName FROM Product WHERE SupplierId = Supplier.Id
AND UnitPrice > 100)
This is a correlated subquery because the subquery references the enclosing
query (with Supplier.Id).
SQL SELECT INTO Statement
SELECT INTO copies data from one table into a new table.
SELECT INTO creates a new table located in the default file group.
The SQL SELECT INTO syntax
30. The general syntax is:
1. SELECT column-names INTO new-table-name FROM table-name
WHERE EXISTS (SELECT column-name FROM table-name WHERE
condition)
The new table will have column names as specified in the query.
SQL SELECT INTO Example
Problem: Copy all suppliers from USA to a new SupplierUSA table.
1. SELECT * INTO SupplierUSA FROM Supplier
WHERE Country = 'USA'
SQL INSERT INTO SELECT Statement
INSERT INTO SELECT copies data from one table to another table.
INSERT INTO SELECT requires that data types in source and target tables
match.
The SQL INSERT INTO SELECT syntax
The general syntax is:
1. INSERT INTO table-name (column-names)
SELECT column-names FROM table-name WHERE condition
SQL INSERT SELECT INTO
Problem: Copy all Canadian suppliers into the Customer table
INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
SELECT LEFT(ContactName, CHARINDEX(' ',ContactName) - 1) AS FirstName,
SUBSTRING(ContactName, CHARINDEX(' ',ContactName) + 1, 100) AS LastName,
City, Country, Phone FROM Supplier WHERE Country = 'Canada'
LEFT, CHARINDEX, and SUBSTRING are built-in functions.
These are the two new Customer records
31. SQL Injection
SQL Injection is a code injection technique.
It is the placement of malicious code in SQL strings.
SQL Injection is one of the most common web hacking techniques.
These attacks only work with apps that internally use SQL.
SQL Keywords
SQL Server uses reserved words for database operations.
Reserved keywords are part of the SQL Server T-SQL grammar.
SQL Server has claimed current and future reserved words.
Keywords can be used as identifiers by placing them between [].
Current T-SQL Keywords
ADD EXCEPT PERCENT
ALL EXEC PLAN
ALTER EXECUTE PRECISION
AND EXISTS PRIMARY
ANY EXIT PRINT
AS FETCH PROC
ASC FILE PROCEDURE
AUTHORIZATION FILLFACTOR PUBLIC
BACKUP FOR RAISERROR
BEGIN FOREIGN READ
BETWEEN FREETEXT READTEXT
BREAK FREETEXTTABLE RECONFIGURE
BROWSE FROM REFERENCES
BULK FULL REPLICATION
BY FUNCTION RESTORE
CASCADE GOTO RESTRICT
CASE GRANT RETURN
CHECK GROUP REVOKE
CHECKPOINT HAVING RIGHT
CLOSE HOLDLOCK ROLLBACK
CLUSTERED IDENTITY ROWCOUNT
COALESCE IDENTITY_INSERT ROWGUIDCOL
COLLATE IDENTITYCOL RULE
32. COLUMN IF SAVE
COMMIT IN SCHEMA
COMPUTE INDEX SELECT
CONSTRAINT INNER SESSION_USER
CONTAINS INSERT SET
CONTAINSTABLE INTERSECT SETUSER
CONTINUE INTO SHUTDOWN
CONVERT IS SOME
CREATE JOIN STATISTICS
CROSS KEY SYSTEM_USER
CURRENT KILL TABLE
CURRENT_DATE LEFT TEXTSIZE
CURRENT_TIME LIKE THEN
CURRENT_TIMESTAMP LINENO TO
CURRENT_USER LOAD TOP
CURSOR NATIONAL TRAN
DATABASE NOCHECK TRANSACTION
DBCC NONCLUSTERED TRIGGER
DEALLOCATE NOT TRUNCATE
DECLARE NULL TSEQUAL
DEFAULT NULLIF UNION
DELETE OF UNIQUE
DENY OFF UPDATE
DESC OFFSETS UPDATETEXT
DISK ON USE
DISTINCT OPEN USER
DISTRIBUTED OPENDATASOURCE VALUES
DOUBLE OPENQUERY VARYING
DROP OPENROWSET VIEW
DUMMY OPENXML WAITFOR
DUMP OPTION WHEN
ELSE OR WHERE
END ORDER WHILE
ERRLVL OUTER WITH
33. ESCAPE OVER WRITETEXT
Future T-SQL Keywords
ABSOLUTE FOUND PRESERVE
ACTION FREE PRIOR
ADMIN GENERAL PRIVILEGES
AFTER GET READS
AGGREGATE GLOBAL REAL
ALIAS GO RECURSIVE
ALLOCATE GROUPING REF
ARE HOST REFERENCING
ARRAY HOUR RELATIVE
ASSERTION IGNORE RESULT
AT IMMEDIATE RETURNS
BEFORE INDICATOR ROLE
BINARY INITIALIZE ROLLUP
BIT INITIALLY ROUTINE
BLOB INOUT ROW
BOOLEAN INPUT ROWS
BOTH INT SAVEPOINT
BREADTH INTEGER SCROLL
CALL INTERVAL SCOPE
CASCADED ISOLATION SEARCH
CAST ITERATE SECOND
CATALOG LANGUAGE SECTION
CHAR LARGE SEQUENCE
CHARACTER LAST SESSION
CLASS LATERAL SETS
CLOB LEADING SIZE
COLLATION LESS SMALLINT
COMPLETION LEVEL SPACE
CONNECT LIMIT SPECIFIC
CONNECTION LOCAL SPECIFICTYPE
CONSTRAINTS LOCALTIME SQL
34. CONSTRUCTOR LOCALTIMESTAMP SQLEXCEPTION
CORRESPONDING LOCATOR SQLSTATE
CUBE MAP SQLWARNING
CURRENT_PATH MATCH START
CURRENT_ROLE MINUTE STATE
CYCLE MODIFIES STATEMENT
DATA MODIFY STATIC
DATE MODULE STRUCTURE
DAY MONTH TEMPORARY
DEC NAMES TERMINATE
DECIMAL NATURAL THAN
DEFERRABLE NCHAR TIME
DEFERRED NCLOB TIMESTAMP
DEPTH NEW TIMEZONE_HOUR
DEREF NEXT TIMEZONE_MINUTE
DESCRIBE NO TRAILING
DESCRIPTOR NONE TRANSLATION
DESTROY NUMERIC TREAT
DESTRUCTOR OBJECT TRUE
DETERMINISTIC OLD UNDER
DICTIONARY ONLY UNKNOWN
DIAGNOSTICS OPERATION UNNEST
DISCONNECT ORDINALITY USAGE
DOMAIN OUT USING
DYNAMIC OUTPUT VALUE
EACH PAD VARCHAR
END-EXEC PARAMETER VARIABLE
EQUALS PARAMETERS WHENEVER
EVERY PARTIAL WITHOUT
EXCEPTION PATH WORK
EXTERNAL POSTFIX WRITE
FALSE PREFIX YEAR
FIRST PREORDER ZONE
FLOAT PREPARE