SQL is a language used to interact with database management systems (DBMS) and query relational databases. It allows users to create, modify, and access data in databases. The document provides an overview of SQL and relational database concepts like relational data structure, domains, primary keys, and referential integrity. It also demonstrates basic SQL queries using the SELECT statement to retrieve data from example CAR and DRIVER tables. Operators like WHERE, BETWEEN, LIKE, NULL, and comparisons are discussed to filter query results based on conditions.
This document provides a history of currencies and exchange rates. It discusses how barter systems led to the development of coins and currency to serve as a medium of exchange. Currencies were originally tied to gold through the gold standard from 1821 to 1914. However, most countries moved to a floating exchange rate system after World War II. The key factors that determine exchange rates between currencies today include differences in inflation rates, interest rates, current account balances, public debt levels, trade terms, and political/economic conditions.
Este documento presenta una guía de práctica clínica para el manejo de la fibrosis quística en Ecuador. La guía fue desarrollada por el Ministerio de Salud Pública del Ecuador y provee recomendaciones para el diagnóstico, tratamiento y seguimiento de los pacientes con esta enfermedad, con énfasis en los aspectos respiratorios, gastrointestinales y nutricionales. La guía también cubre temas como prevención, complicaciones, aspectos psicológicos y cuidados paliativos en fibrosis quística.
This document discusses the discovery of the exotic carpenter bee Lithurgus chrysurus in Slatington, PA. It describes how the bee was first found in 1970 in Phillipsburg, NJ where it damaged a home. In 2007, a single bee was discovered at Lehigh Gap Nature Center, about 20 miles west of the original location. Experts were called in and some nesting sites were found along railroad tracks in NJ and PA. In 2012, one of the nesting sites was found in a firewood pile in a homeowner's yard in Slatington.
This document provides information about commuting through Grand Central Terminal and Pennsylvania Station in New York City. It includes statistics on the demographics of Grand Central Terminal commuters as well as retail shops and dining options available at both Grand Central and Penn Station. Themes around the sensory experiences, scale, technology, social behaviors, and nature are discussed. An interview with a Long Island Rail Road commuter shares their perspectives on how their commute has changed over 15 years with increased crowding on trains and the use of technology to make trips feel quicker.
Croxton Kerrial Manor House
Excavations in Pinfold Field
Geophysical surveys and excavations revealed the remains of a substantial medieval manor house at Croxton Kerrial dating from the 11th-16th centuries. Wall foundations and cobbled floors from four main areas were uncovered along with domestic artifacts like pottery and a medieval pitcher. A large cellar or pit contained animal bones, shells, and more pottery. While no definitive evidence of a manor was found, the high-status domestic site adjacent to the church is likely the location of the historic Croxton Kerrial manor house.
El documento presenta resúmenes breves de las características de varios navegadores web populares como Mozilla Firefox, Opera, Avant, Internet Explorer, Netscape Navigator, Safari y Chrome. Cada resumen destaca algunas de las funciones clave de cada navegador como la navegación por pestañas, el rendimiento, la seguridad, la personalización y el soporte para estándares web.
Grand Central Terminal and Pennsylvania Station are two major transportation hubs in New York City. Grand Central sees about 750,000 passengers daily and over 1 million during the holidays, with many commuters being affluent professionals. Pennsylvania Station serves Amtrak, NJ Transit, and Long Island Railroad lines, handling around 600,000 passengers daily. Both stations feature numerous retail shops and dining options catering to the large commuter populations. Commuters rely on their senses like hearing to navigate the busy stations and are attuned to any changes in normal sounds that could indicate issues. The scale of the stations is immense, spanning multiple levels and tracks, and technology has modernized ticketing and provided commuter information.
This document provides a history of currencies and exchange rates. It discusses how barter systems led to the development of coins and currency to serve as a medium of exchange. Currencies were originally tied to gold through the gold standard from 1821 to 1914. However, most countries moved to a floating exchange rate system after World War II. The key factors that determine exchange rates between currencies today include differences in inflation rates, interest rates, current account balances, public debt levels, trade terms, and political/economic conditions.
Este documento presenta una guía de práctica clínica para el manejo de la fibrosis quística en Ecuador. La guía fue desarrollada por el Ministerio de Salud Pública del Ecuador y provee recomendaciones para el diagnóstico, tratamiento y seguimiento de los pacientes con esta enfermedad, con énfasis en los aspectos respiratorios, gastrointestinales y nutricionales. La guía también cubre temas como prevención, complicaciones, aspectos psicológicos y cuidados paliativos en fibrosis quística.
This document discusses the discovery of the exotic carpenter bee Lithurgus chrysurus in Slatington, PA. It describes how the bee was first found in 1970 in Phillipsburg, NJ where it damaged a home. In 2007, a single bee was discovered at Lehigh Gap Nature Center, about 20 miles west of the original location. Experts were called in and some nesting sites were found along railroad tracks in NJ and PA. In 2012, one of the nesting sites was found in a firewood pile in a homeowner's yard in Slatington.
This document provides information about commuting through Grand Central Terminal and Pennsylvania Station in New York City. It includes statistics on the demographics of Grand Central Terminal commuters as well as retail shops and dining options available at both Grand Central and Penn Station. Themes around the sensory experiences, scale, technology, social behaviors, and nature are discussed. An interview with a Long Island Rail Road commuter shares their perspectives on how their commute has changed over 15 years with increased crowding on trains and the use of technology to make trips feel quicker.
Croxton Kerrial Manor House
Excavations in Pinfold Field
Geophysical surveys and excavations revealed the remains of a substantial medieval manor house at Croxton Kerrial dating from the 11th-16th centuries. Wall foundations and cobbled floors from four main areas were uncovered along with domestic artifacts like pottery and a medieval pitcher. A large cellar or pit contained animal bones, shells, and more pottery. While no definitive evidence of a manor was found, the high-status domestic site adjacent to the church is likely the location of the historic Croxton Kerrial manor house.
El documento presenta resúmenes breves de las características de varios navegadores web populares como Mozilla Firefox, Opera, Avant, Internet Explorer, Netscape Navigator, Safari y Chrome. Cada resumen destaca algunas de las funciones clave de cada navegador como la navegación por pestañas, el rendimiento, la seguridad, la personalización y el soporte para estándares web.
Grand Central Terminal and Pennsylvania Station are two major transportation hubs in New York City. Grand Central sees about 750,000 passengers daily and over 1 million during the holidays, with many commuters being affluent professionals. Pennsylvania Station serves Amtrak, NJ Transit, and Long Island Railroad lines, handling around 600,000 passengers daily. Both stations feature numerous retail shops and dining options catering to the large commuter populations. Commuters rely on their senses like hearing to navigate the busy stations and are attuned to any changes in normal sounds that could indicate issues. The scale of the stations is immense, spanning multiple levels and tracks, and technology has modernized ticketing and provided commuter information.
The document summarizes key SQL concepts for filtering, ordering, and aggregating data in a database table. It covers:
1. Combining filtering rules with AND, OR, and NOT operators, and using parentheses to specify precedence.
2. Sorting query results with ORDER BY in ascending or descending order.
3. Calculating statistics on data with aggregate functions like COUNT, SUM, AVG, MIN, MAX.
4. Using GROUP BY to combine aggregate functions with other columns, and the HAVING clause to filter groups.
The document discusses the relational database model and its key concepts. It describes the relational model as consisting of tables with rows and columns of atomic values. It outlines the eight relational operators and discusses primary keys, foreign keys, and integrity rules such as entity integrity and referential integrity. Semantic data types that define user-friendly domains and composite types are also introduced.
This document provides a summary of MySQL indexes and how to use the EXPLAIN statement to analyze query performance. It defines what indexes are, the different types of indexes like B-tree, hash, and full-text indexes. It also explains concepts like compound indexes, covering indexes, and partial indexes. The document demonstrates how to use the EXPLAIN statement to view and understand a query execution plan, including analyzing the possible and actual indexes used, join types, number of rows examined, and index usage. It provides examples of interpreting EXPLAIN output and analyzing performance bottlenecks.
The document discusses various SQL commands for retrieving data from Oracle databases. It covers the SELECT statement and its clauses like WHERE, DISTINCT, LIKE, BETWEEN, IN and operators like AND, OR, NOT. It also discusses NULL values, concatenation, character strings, dates and basic SQL terminology. The SELECT statement is used to retrieve data from tables and supports filtering rows and selecting specific columns.
FOUNDATION OF DATA SCIENCE SQL QUESTIONSHITIKAJAIN4
This document provides an overview of relational databases and the SQL language. It defines key concepts like relational databases, tables, rows, columns and SQL. It explains how SQL can be used to query databases using commands like SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY. It provides examples of basic queries involving filtering, projections, aggregations, joins and use of SQL clauses. It also discusses SQL data types, NULL values, pattern matching and basic statistics that can be computed using SQL.
The document provides an introduction to SQL (Structured Query Language) and its basic concepts and commands for interacting with relational databases. It explains how to query data using SELECT statements, filter results using WHERE clauses, group data using GROUP BY, perform calculations using aggregate functions like COUNT, AVG, and SUM, sort results with ORDER BY, and join data from multiple tables. Examples are provided for each concept to illustrate how it can be used to extract and analyze data from database tables.
A database is a collection of information organized in a way that allows a computer program to select desired data quickly. A traditional database is organized into fields, records, and files. A field contains a single piece of information, a record contains one set of fields, and a file contains records.
A database management system (DBMS) is a collection of programs that allows users to enter, organize, and select data in a database. It performs functions like user management, data creation/modification/access, and database maintenance. Popular DBMS include Microsoft Access, Oracle, MySQL, SQL Server, and others.
Good database systems have ACID properties - Atomicity, Consistency, Isolation, and Durability.
This document provides an introduction to SQL and database systems. It begins with example tables to demonstrate SQL concepts. It then covers the objectives of SQL, including allowing users to create database structures, manipulate data, and perform queries. Various SQL concepts are introduced such as data types, comparison operators, logical operators, and arithmetic operators. The document also discusses SQL statements for schema and catalog definitions, data definition, data manipulation, and other operators. Example SQL queries are provided to illustrate concepts around selecting columns, rows, sorting, aggregation, grouping, and more.
This document provides an overview of SQL (Structured Query Language) concepts including:
1) SQL is used to define and manipulate data in a relational database. It includes commands for data definition, manipulation, and control.
2) The CREATE TABLE statement is used to define tables and their columns, including data types, constraints, and keys.
3) Queries use the SELECT statement to retrieve data from one or more tables, optionally filtering rows using a WHERE clause. Joins allow querying multiple related tables.
4) Aggregate functions like COUNT, AVG, MIN, MAX operate on columns and return a single value. GROUP BY is used to aggregate values within categories.
This document provides an overview of SQL and MySQL. It discusses topics such as creating and deleting databases and tables, importing data, using IDEs like Execute Query, configuring connections, performing queries with SELECT statements including filters, joins, and aggregates, updating and deleting data, indexing, and working with dates, strings, and numbers. Examples of SQL queries are provided throughout to demonstrate different SQL syntax and functions.
The document provides an overview of SQL and reasons for learning SQL. It discusses what SQL is, why learn SQL, and provides an overview of SQL functions including retrieving data using SELECT statements, arithmetic expressions, null values, column aliases, concatenation operators, literal character strings, and alternative quote operators. It also covers restricting and sorting data using WHERE clauses, comparison operators, logical operators, pattern matching, and null conditions.
Relational algebra is a procedural query language used to manipulate relations in a relational database. It consists of operators like select, project, join, union, and set difference. SQL is based on the concepts of relational algebra. Relational algebra expressions specify a sequence of operators to apply to relations in order to retrieve the desired data from the database. Some key operators include selection to filter tuples, projection to select attributes, and join to combine tuples from two relations based on a join condition.
This presentation was provided by Racquel Jemison, Ph.D., Christina MacLaughlin, Ph.D., and Paulomi Majumder. Ph.D., all of the American Chemical Society, for the second session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session Two: 'Expanding Pathways to Publishing Careers,' was held June 13, 2024.
Gender and Mental Health - Counselling and Family Therapy Applications and In...PsychoTech Services
A proprietary approach developed by bringing together the best of learning theories from Psychology, design principles from the world of visualization, and pedagogical methods from over a decade of training experience, that enables you to: Learn better, faster!
The document summarizes key SQL concepts for filtering, ordering, and aggregating data in a database table. It covers:
1. Combining filtering rules with AND, OR, and NOT operators, and using parentheses to specify precedence.
2. Sorting query results with ORDER BY in ascending or descending order.
3. Calculating statistics on data with aggregate functions like COUNT, SUM, AVG, MIN, MAX.
4. Using GROUP BY to combine aggregate functions with other columns, and the HAVING clause to filter groups.
The document discusses the relational database model and its key concepts. It describes the relational model as consisting of tables with rows and columns of atomic values. It outlines the eight relational operators and discusses primary keys, foreign keys, and integrity rules such as entity integrity and referential integrity. Semantic data types that define user-friendly domains and composite types are also introduced.
This document provides a summary of MySQL indexes and how to use the EXPLAIN statement to analyze query performance. It defines what indexes are, the different types of indexes like B-tree, hash, and full-text indexes. It also explains concepts like compound indexes, covering indexes, and partial indexes. The document demonstrates how to use the EXPLAIN statement to view and understand a query execution plan, including analyzing the possible and actual indexes used, join types, number of rows examined, and index usage. It provides examples of interpreting EXPLAIN output and analyzing performance bottlenecks.
The document discusses various SQL commands for retrieving data from Oracle databases. It covers the SELECT statement and its clauses like WHERE, DISTINCT, LIKE, BETWEEN, IN and operators like AND, OR, NOT. It also discusses NULL values, concatenation, character strings, dates and basic SQL terminology. The SELECT statement is used to retrieve data from tables and supports filtering rows and selecting specific columns.
FOUNDATION OF DATA SCIENCE SQL QUESTIONSHITIKAJAIN4
This document provides an overview of relational databases and the SQL language. It defines key concepts like relational databases, tables, rows, columns and SQL. It explains how SQL can be used to query databases using commands like SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY. It provides examples of basic queries involving filtering, projections, aggregations, joins and use of SQL clauses. It also discusses SQL data types, NULL values, pattern matching and basic statistics that can be computed using SQL.
The document provides an introduction to SQL (Structured Query Language) and its basic concepts and commands for interacting with relational databases. It explains how to query data using SELECT statements, filter results using WHERE clauses, group data using GROUP BY, perform calculations using aggregate functions like COUNT, AVG, and SUM, sort results with ORDER BY, and join data from multiple tables. Examples are provided for each concept to illustrate how it can be used to extract and analyze data from database tables.
A database is a collection of information organized in a way that allows a computer program to select desired data quickly. A traditional database is organized into fields, records, and files. A field contains a single piece of information, a record contains one set of fields, and a file contains records.
A database management system (DBMS) is a collection of programs that allows users to enter, organize, and select data in a database. It performs functions like user management, data creation/modification/access, and database maintenance. Popular DBMS include Microsoft Access, Oracle, MySQL, SQL Server, and others.
Good database systems have ACID properties - Atomicity, Consistency, Isolation, and Durability.
This document provides an introduction to SQL and database systems. It begins with example tables to demonstrate SQL concepts. It then covers the objectives of SQL, including allowing users to create database structures, manipulate data, and perform queries. Various SQL concepts are introduced such as data types, comparison operators, logical operators, and arithmetic operators. The document also discusses SQL statements for schema and catalog definitions, data definition, data manipulation, and other operators. Example SQL queries are provided to illustrate concepts around selecting columns, rows, sorting, aggregation, grouping, and more.
This document provides an overview of SQL (Structured Query Language) concepts including:
1) SQL is used to define and manipulate data in a relational database. It includes commands for data definition, manipulation, and control.
2) The CREATE TABLE statement is used to define tables and their columns, including data types, constraints, and keys.
3) Queries use the SELECT statement to retrieve data from one or more tables, optionally filtering rows using a WHERE clause. Joins allow querying multiple related tables.
4) Aggregate functions like COUNT, AVG, MIN, MAX operate on columns and return a single value. GROUP BY is used to aggregate values within categories.
This document provides an overview of SQL and MySQL. It discusses topics such as creating and deleting databases and tables, importing data, using IDEs like Execute Query, configuring connections, performing queries with SELECT statements including filters, joins, and aggregates, updating and deleting data, indexing, and working with dates, strings, and numbers. Examples of SQL queries are provided throughout to demonstrate different SQL syntax and functions.
The document provides an overview of SQL and reasons for learning SQL. It discusses what SQL is, why learn SQL, and provides an overview of SQL functions including retrieving data using SELECT statements, arithmetic expressions, null values, column aliases, concatenation operators, literal character strings, and alternative quote operators. It also covers restricting and sorting data using WHERE clauses, comparison operators, logical operators, pattern matching, and null conditions.
Relational algebra is a procedural query language used to manipulate relations in a relational database. It consists of operators like select, project, join, union, and set difference. SQL is based on the concepts of relational algebra. Relational algebra expressions specify a sequence of operators to apply to relations in order to retrieve the desired data from the database. Some key operators include selection to filter tuples, projection to select attributes, and join to combine tuples from two relations based on a join condition.
This presentation was provided by Racquel Jemison, Ph.D., Christina MacLaughlin, Ph.D., and Paulomi Majumder. Ph.D., all of the American Chemical Society, for the second session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session Two: 'Expanding Pathways to Publishing Careers,' was held June 13, 2024.
Gender and Mental Health - Counselling and Family Therapy Applications and In...PsychoTech Services
A proprietary approach developed by bringing together the best of learning theories from Psychology, design principles from the world of visualization, and pedagogical methods from over a decade of training experience, that enables you to: Learn better, faster!
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).
Elevate Your Nonprofit's Online Presence_ A Guide to Effective SEO Strategies...TechSoup
Whether you're new to SEO or looking to refine your existing strategies, this webinar will provide you with actionable insights and practical tips to elevate your nonprofit's online presence.
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumMJDuyan
(𝐓𝐋𝐄 𝟏𝟎𝟎) (𝐋𝐞𝐬𝐬𝐨𝐧 𝟏)-𝐏𝐫𝐞𝐥𝐢𝐦𝐬
𝐃𝐢𝐬𝐜𝐮𝐬𝐬 𝐭𝐡𝐞 𝐄𝐏𝐏 𝐂𝐮𝐫𝐫𝐢𝐜𝐮𝐥𝐮𝐦 𝐢𝐧 𝐭𝐡𝐞 𝐏𝐡𝐢𝐥𝐢𝐩𝐩𝐢𝐧𝐞𝐬:
- Understand the goals and objectives of the Edukasyong Pantahanan at Pangkabuhayan (EPP) curriculum, recognizing its importance in fostering practical life skills and values among students. Students will also be able to identify the key components and subjects covered, such as agriculture, home economics, industrial arts, and information and communication technology.
𝐄𝐱𝐩𝐥𝐚𝐢𝐧 𝐭𝐡𝐞 𝐍𝐚𝐭𝐮𝐫𝐞 𝐚𝐧𝐝 𝐒𝐜𝐨𝐩𝐞 𝐨𝐟 𝐚𝐧 𝐄𝐧𝐭𝐫𝐞𝐩𝐫𝐞𝐧𝐞𝐮𝐫:
-Define entrepreneurship, distinguishing it from general business activities by emphasizing its focus on innovation, risk-taking, and value creation. Students will describe the characteristics and traits of successful entrepreneurs, including their roles and responsibilities, and discuss the broader economic and social impacts of entrepreneurial activities on both local and global scales.
How Barcodes Can Be Leveraged Within Odoo 17Celine George
In this presentation, we will explore how barcodes can be leveraged within Odoo 17 to streamline our manufacturing processes. We will cover the configuration steps, how to utilize barcodes in different manufacturing scenarios, and the overall benefits of implementing this technology.
This presentation was provided by Rebecca Benner, Ph.D., of the American Society of Anesthesiologists, for the second session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session Two: 'Expanding Pathways to Publishing Careers,' was held June 13, 2024.
1. SQL – Simple Queries
Chapter 3.1
V3.0
Copyright @ Napier University
Dr Gordon Russell
2. Introduction
• SQL is the Structured Query Language
• It is used to interact with the DBMS
• SQL can
– Create Schemas in the DBMS
– Alter Schemas
– Add data
– Remove data
– Change data
– Access Data
3. DSL
• SQL is a Data Sub Language – DSL
• This is a combination of two languages
– DDL – Data Definition Language
– DML – Data Manipulation Language
• The main way of accessing data is using the DML command
SELECT.
• The abilities of the SELECT command forms the majority of
this material on SQL
4. Database Models
A data model comprises
• a data structure
• a set of integrity constraints
• operations associated with the data structure
Examples of data models include:
• hierarchic
• network
• relational
5. Relational Databases
The relational data model comprises:
• relational data structure
• relational integrity constraints
• relational algebra or equivalent (SQL)
– SQL is an ISO language based on relational
algebra
– relational algebra is a mathematical formulation
6. Relational Data Structure
A relational data structure is a collection of tables or
relations.
• A relation is a collection of rows or tuples
• A tuple is a collection of columns or attributes
• A domain is a pool of values from which the actual
attribute values are taken.
7. Relational Structure cont
M E N U R elatio n o r
T ab le A ttrib u tes
D escrip tio n P rice
T u p le
D o m ain
8. Domain and Integrity Constraints
• Domain Constraints
– limit the range of domain values of an attribute
– specify uniqueness and ‘nullness’ of an attribute
– specify a default value for an attribute when no value is
provided.
• Entity Integrity
– every tuple is uniquely identified by a unique non-null
attribute, the primary key.
• Referential Integrity
– rows in different tables are correctly related by valid key
values (‘foreign’ keys refer to primary keys).
9. Example Database
• In order to better understand SQL, all the example queries
make use of a simple database.
• The database is formed from 2 tables, CAR and DRIVER.
• Each car may be owned by a DRIVER.
• A DRIVER may own multiple CARs.
DRIVER CAR
10. DRIVER
NAME DOB
Jim Smith 11 Jan 1980
Bob Smith 23 Mar 1981
Bob Jones 3 Dec 1986
11. CAR
REGNO MAKE COLOUR PRICE OWNER
F611 AAA FORD RED 12000 Jim Smith
J111 BBB SKODA BLUE 11000 Jim Smith
A155 BDE MERCED BLUE 22000 Bob Smith
ES
K555 GHT FIAT GREEN 6000 Bob Jones
SC04 BFE SMART BLUE 13000
12. • Each column holds data of a particular type
– Integer, string, decimal, blobs
– The range of values can be further constrained
• If a column in a row contains no data, it is NULL.
• It can indicate no possible value or unavailable data.
• All rows must differ from each other in some way
• Sometimes a row is called a tuple
• Cardinality is the number of rows of a table
• Arity is the number of columns of a table
13. Primary Keys
• In the design section the idea of a Primary Key is defined.
• A Primary Key is a group of 1 or more columns which, when
taken together, is unique in the table
• No part of a primary key can be NULL.
• In our example,
– DRIVER: the primary key is NAME
– CAR: the primary key is REGNO
• In our example this means that no two drivers can have the
same name. In the real world this would be a problem, but
this is just an example.
14. Referential Integrity
• Note that there is a link between CAR and DRIVER via
OWNER.
• If there is a value in OWNER, then this value must also
appear somewhere in DRIVER.
• If you change a driver’s name in DRIVER, you must make
sure the same change is made in OWNER of CAR.
• The DBMS enforces the rules.
• If you try to break the rules the DBMS reports the problem as
a REFERENTIAL INTEGRITY error.
15. SQL Basics
• Basic SQL statements include
– CREATE – a data structure
– SELECT – read one or more rows from a table
– INSERT – one of more rows into a table
– DELETE – one or more rows from a table
– UPDATE – change the column values in a row
– DROP – a data structure
• In this lecture the focus is on SELECT.
16. Simple SELECT
• SELECT column FROM tablename
• SELECT column1,column2,column3 FROM tablename
• SELECT * from tablename
• SELECT * from CAR;
REGNO MAKE COLOUR PRICE OWNER
F611 AAA FORD RED 12000 Jim Smith
J111 BBB SKODA BLUE 11000 Jim Smith
A155 BDE MERCEDES BLUE 22000 Bob Smith
K555 GHT FIAT GREEN 6000 Bob Jones
SC04 BFE SMART BLUE 13000
17. SELECT regno from CAR;
REGNO
F611 AAA
J111 BBB
A155 BDE
K555 GHT
SC04 BFE
18. SELECT colour,owner from CAR;
COLOUR OWNER
RED Jim Smith
BLUE Jim Smith
BLUE Bob Smith
GREEN Bob Jones
BLUE
19. Formatting
• SPACES do not matter
• NEWLINES do not matter
• Good practice to put ; at the end of the query.
• CASE (except between single quotes) does not matter.
• These are all valid:
SELECT REGNO FROM CAR;
SElecT regno
From Car
;
20. Comments
• To give you the ability to make notes in queries you are
allowed to have comments.
• Comments are not executed
• A comment starts with -- and ends with a newline
• They are only permitted within a query.
SELECT regno -- The registration number
FROM car -- The car storage table
;
21. SELECT filters
• You can have rules in your queries
• These rules are tested for each row your query produces
• If the rule is true, the row is displayed
• If the rule is false, the row is not displayed
• The rule starts with WHERE
SELECT columns
FROM table
WHERE rule
22. Simple Rule
• A simple rule might be to look for a car with a colour of RED.
• The rule would be colour = 'RED'
SELECT regno FROM CAR SELECT regno from CAR
WHERE colour = 'RED'
REGNO
F611 AAA
REGNO
J111 BBB
F611 AAA
A155 BDE
K555 GHT
SC04 BFE
23. Note
• Things between quotes is CASE SENSITIVE.
• ‘RED’ is not the same as ‘Red’ or ‘red’
• Rules which mention fields – they can be used if
they appear on the SELECT line or not.
REGNO COLOUR
SELECT regno from CAR
F611 AAA RED
WHERE colour = 'RED'
24. Comparisons
• Valid comparisons include =,!=,<>,<,<=,>,>=
– Colour = ‘RED’ The colour must be red
– Colour != ‘RED’ The colour is not red
– Colour <> ‘Red’ Same as !=
– Price > 10000 More than 10000
– Price >= 10000 More than or equal to 10000
– Price < 10000 Cheaper than 10000
– Price <=10000 Cheaper or the same as 10000
• Numbers – You can say ‘10000’ or 10000. Strings always
have quotes…
25. DATE
• Date comparisons can be tricky
• You can use all the normal comparators with dates.
SELECT name,dob SELECT name,dob from driver
from driver where DOB = ‘3 Jan 1986’
NAME DOB
NAME DOB
Jim Smith 11 Jan 1980
Bob Jones 3 Dec 1986
Bob Smith 23 Mar 1981
Bob Jones 3 Dec 1986
26. • The tricky part with dates is remembering that dates get
bigger as you move into the future.
• DATE1>DATE2 indicates DATE1 is in the future after
DATE2.
SELECT name,dob from driver
WHERE DOB >= ‘1 Jan 1981’
NAME DOB
Bob Smith 23 Mar 1981
Bob Jones 3 Dec 1986
27. DATE Syntax
• It must be in quotes
• Each DBMS handles dates in a slightly different way
• Dates like ‘1 Jan 2003’ work quite well.
• Oracle permits dates like ‘1-Jan-2003’
• Oracle also permits dates like ‘1-Jan-03’
– Be caseful … if you type this it will assume 2003.
– If you mean 1984 type 1984 not –04.
• You must always specify a day and a month. If you do not
the DBMS will report an error.
28. BETWEEN
• When dealing with dates sometimes you want to test to see
if a field value falls between two dates.
• The easiest way to do this is with BETWEEN
• Find all drivers born between 1995 and 1999
SELECT name,dob from driver
WHERE DOB between ‘1 Jan 1985’ and ’31 Dec 1999’
• Between works for other things, not just dates…
SELECT regno from CAR
where price between 5000 and 10000;
29. NULL
• NULL indicates that something has no value
• It is not a value, and you cannot use normal comparison
operators.
• For instance, looking for cars without owners…
Wrong: SELECT regno from car where owner = NULL
Wrong: SELECT regno from car where owner = ‘NULL’
• Instead there are two special operators, IS NULL, and
IS NOT NULL
30. SELECT regno from car REGNO
WHERE OWNER is null SC04 BFE
REGNO
SELECT regno from car F611 AAA
WHERE OWNER is not null J111 BBB
A155 BDE
K555 GHT
SC04 BFE
31. LIKE
• Sometimes you want to have a rule involving
partial strings, substrings, or wildcards
• LIKE does this, and is a slot-in replacement for ‘=‘
• If the string contains ‘%’ or ‘_’, LIKE uses them to
support wildcards.
– % - Matches 0 or more characters in the string
– _ - Matches exactly 1 character in the string
32. Examples
• Name LIKE ‘Jim Smith’ e.g. Jim Smith
• Name LIKE ‘_im Smith’ e.g. Tim Smith
• Name LIKE ‘___ Smith’ e.g. Bob Smith
• Name LIKE ‘% Smith’ e.g. Frank Smith
• Name LIKE ‘% S%’ e.g. Brian Smart
• Name LIKE ‘Bob %’ e.g. Bob Martin
• Name LIKE ‘%’ i.e. match anyone
• LIKE is more expensive than =
• If you are not using wildcards, always use = rather than
LIKE.