Aga Non-Government Institute for Computer Science

Size: px
Start display at page:

Download "Aga Non-Government Institute for Computer Science"

Transcription

1 Aga Non-Government Institute for Computer Science Teacher SHERZAD ABDULLAH

2 History of Database Systems s and early 1960s: Data processing using magnetic tapes for storage Tapes provided only sequential access Punched cards for input - Late 1960s and 1970s: Hard disks allowed direct access to data Network and hierarchical data models in widespread use Ted Codd defines the relational data model s: Research relational prototypes evolve into commercial systems SQL becomes industrial standard Parallel and distributed database systems Object-oriented database systems s: Large decision support and data-mining applications Large multi-terabyte data warehouses Emergence of Web commerce Early 2000s: XML and XQuery standards Automated database administration Later 2000s: Giant data storage systems Google BigTable, Yahoo PNuts, Amazon,.. 2

3 Data Models Relational Databases Database Design Storage Manager Query Processing Transaction Manager The Need for Databases Database Management System (DBMS) - DBMS contains information about a particular enterprise Collection of interrelated data Set of programs to access the data An environment that is both convenient and efficient to use - Database Applications: Banking: transactions Airlines: reservations, schedules Universities: registration, grades 3

4 Sales: customers, products, purchases Online retailers: order tracking, customized recommendations Manufacturing: production, inventory, orders, supply chain Human resources: employee records, salaries, tax deductions - Databases can be very large. - Databases touch all aspects of our lives University Database Example - Application program examples Add new students, instructors, and courses Register students for courses, and generate class rosters Assign grades to students, compute grade point averages (GPA) and generate transcripts In the early days, database applications were built directly on top of file systems Disadvantage of using file systems to store data Data redundancy and inconsistency - Multiple file formats, duplication of information in different files Difficulty in accessing data - Need to write a new program to carry out each new task Data isolation 4

5 - Multiple files and formats Integrity problems - Integrity constraints (e.g., account balance > 0) become buried in program code rather than being stated explicitly - Hard to add new constraints or change existing ones Database systems offer solutions to all the above problems Levels of Abstraction Physical level: describes how a record (e.g., instructor) is stored. Logical level: describes data stored in database, and the relationships among the data. type instructor = record end; ID : string; name : string; dept_name : string; salary : integer; View level: application programs hide details of data types. Views can also hide information (such as an employee s salary) for security purposes. 5

6 View of Data An architecture for a database system Instances and Schemas Similar to types and variables in programming languages Logical Schema the overall logical structure of the database Example: The database consists of information about a set of customers and accounts in a bank and the relationship between them - Analogous to type information of a variable in a program Physical schema the overall physical structure of the database instance the actual content of the database at a particular point in time Analogous to the value of a variable Physical Data Independence the ability to modify the physical schema without changing the logical schema - Applications depend on the logical schema - In general, the interfaces between the various levels and components should be well defined so that changes in some parts do not seriously influence others. 6

7 Data Models A collection of tools for describing o Data o Data relationships o Data semantics o Data constraints 7

8 Relational model Entity-Relationship data model (mainly for database design) Object-based data models (Object-oriented and Object-relational) Semistructured data model (XML) Other older models: o Network model o Hierarchical model Data Definition Language (DDL) o Specification notation for defining the database schema o Example: create table shara ( ID char(5), name varchar(20), dept_name varchar(20), salary numeric(8,2)) o DDL compiler generates a set of table templates stored in a data dictionary o Data dictionary contains metadata (i.e., data about data) o Database schema o Integrity constraints o Primary key (ID uniquely identifies instructors) o Authorization o Who can access what Data Manipulation Language (DML) o Language for accessing and manipulating the data organized by the appropriate data model o DML also known as query language 8

9 o Two classes of languages o Pure used for proving properties about computational power and for optimization o Commercial used in commercial systems SQL is the most widely used commercial Database Design The process of designing the general structure of the database: o Logical Design Deciding on the database schema. Database design requires that we find a good collection of relation schemas. o Business decision What attributes should we record in the database? o Computer Science decision What relation schemas should we have and how should the attributes be distributed among the various relation schemas? o Physical Design Deciding on the physical layout of the database 9

10 Object Relational Data Models Extend the relational data model by including object orientation and constructs to deal with added data types. Allow attributes of tuples to have complex types, including non-atomic values such as nested relations. Preserve relational foundations, in particular the declarative access to data, while extending modeling power. Provide upward compatibility with existing relational languages. Database Engine 1. Storage manager 2. Query processing 3. Transaction manager Query Processing 1.Parsing and translation 2. Optimization 3. Evaluation 10

11 Database Architecture The architecture of database systems is greatly influenced by the underlying computer system on which the database is running: Centralized Client-server Parallel (multi-processor) Distributed Entity and Attribute Entity is an entity is a single person, place, or thing about which data can be stored. That is in other words for example when one wants to store information about STUDENT then it has details like student no, student name, address for communication, phone number, class of the student Attribute is the characteristic property of an existing entity. The attribute has two parts in it namely the attribute instance and attribute type. Attribute type is the column name or field name that is in the above student entity student name is the attribute type and the actual value stored in it is the attribute We begin to add attributes to the entities, the diagram will look like this; 11

12 SQL Server 2012 Developer This is identical to the Enterprise edition, except that it is only licensed for development and test systems. Express The Express version of SQL Server is a great entry-level product. It is perfect for learning and building small data-driven applications. Choosing Hardware for SQL Server Processor : Processor type: Intel Pentium IV or AMD Athlon Processor Speed: 2.0 GHz or faster Memory 4 GB or more Hard disk space Database Engine, data files, and replication: 811 MB SSIS: 591 MB Client components: 1823 MB Before Installation SQL Server Instances SQL Server 2012 supports multiple Database Engine instances on the same computer. Typically, the initial install of SQL Server is the default instance, which assumes the name of the computer on which SQL Server is being installed. Any additional installed instances are referred to as named instances. Microsoft SQL Server is one the most popular Relational Database Management System (RDBMS) used in Microsoft universe. It can be used for data storage as well as for data retrieval for applications which can be either on desktop or Web/Browse. 12

13 DBMS : DBMS A database management system is the software system that allows users to define, create and maintain a database and provides controlled access to the data. A Database Management System (DBMS) is basically a collection of programs that enables users to store, modify, and extract information from a database as per the requirements. DBMS is an intermediate layer between programs and the data. Advantages of Database Management System (DBMS) 1. Minimize Data Redundancy In File Processing System, duplicate data is created in many places because all the programs have their own files. 2. Sharing of Data In DBMS, Data can be shared in between authorized user of database. All the users have their own right to access the database up to a level. 3. Data Consistency DBMS controls data redundancy which in turn controls data consistency. Data consistency means if you want to update data in any files then all the files should not be updated again. As in DBMS, data is stored in a single database so data becomes more consistent in comparison to file processing system 13

14 4. Data Integrity Data integrity means unification of so many files into a single file. In DBMS data is stored in different tables. 5. Search Capability Users of database may require to fetch data from the database. There are numerous queries users may ask about the data. Search speed of the database must be fast to produce quick results. 6. Security Data security means protecting your precious data from unauthorized access. Data in database should be kept secure and safe to unauthorized modifications 7. Privacy Privacy means up to what extent a user can access the data 9. Backup and Recovery Data loss is a very big problem for all the organizations. In traditional file processing system, a user needs to backup the database 8. Simplicity DBMS is very simple for its users who use it. All the operations like insert, delete, create and update are very easy to implement. 14

15 Table Basics A relational database system (DBMS) contains one or more objects called tables. The data or information for the database are stored in these tables Tables are uniquely identified by their names and are comprised of columns and rows. Columns contain the column name, data type, and any other attributes for the column Rows contain the records or data for the columns. The table and column names must start with a letter and can be followed by letters, numbers, or underscores - not to exceed a total of 30 characters in length Do not use any SQL reserved keywords as names for tables or column names (such as "select", "create", "insert", etc) Data types specify what the type of data can be for that particular column. If a column called "Last_Name", is to be used to hold names, then that particular column should have a "varchar" (variable-length character) data type. Here are the most common Data types: char(size) varchar(size) number(size) date Fixed-length character string. Size is specified in parenthesis. Max 255 bytes. Variable-length character string. Max size is specified in parenthesis. Number value with a max number of column digits specified in parenthesis. Date value number(size,d) Number value with a maximum number of digits of "size" total, with a maximum number of "d" digits to the right of the decimal. 15

16 What are constraints? When tables are created, it is common for one or more columns to have constraints associated with them. A constraint is basically a rule associated with a column that the data entered into that column must follow. For example, a "unique" constraint specifies that no two records can have the same value in a particular column. They must all be unique. The other two most popular constraints are "not null" which specifies that a column can't be left blank, and "primary key". A "primary key" constraint defines a unique identification of each record (or row) in a table. Constraints can be entered in this SQL interpreter, 1- Open SQL Server and Login 2- Create new data base by Right click on Database 16

17 3- Creating Tables and Define Fields and Data type 4- Data Entry to Table by ( Right Click on Table and Click Edit top 200 Rows ) 17

18 5- Adding data and creating new view -- By clicking Add command, the Execute SQL command in the tool bar will be active. 18

19 History of SQL n IBM Sequel language developed as part of System R project at the IBM San Jose Research Laboratory n Renamed Structured Query Language (SQL) n ANSI and ISO standard SQL: l SQL-86 l SQL-89 l SQL-92 What is SQL? l SQL:1999 (language name became Y2K compliant!) l SQL:2003 SQL Stands for Structured Query Language. SQL lets you access and manipulate databases SQL is used to communicate with a database. According to ANSI (American National Standards Institute),it is the standard language for relational database management systems. SQL statements are used to perform tasks such as update data on a database, or retrieve data from a database. All SQL statements should end with a ";". Table (Student) Student_ID Name Gender year SHYAR Male ALAND Male AHMED Male ZHYAR Female ZHALA Female BANAZ Female SHANAZ Female

20 Table (Course) ID Student_ID Stage Department CourseName Network SQL Server Network CCNA Network Web Network Server Programming C# Programming PHP Programming Visual Basic Programming Oracle Create Table Construct Example: Example: create table instructor ( ID char(5), name varchar(20), dept_name varchar(20), salary numeric(8,2)) create table instructor ( ID char(5), name varchar(20) not null, dept_name varchar(20), salary numeric(8,2), primary key (ID), foreign key (dept_name) references department); create table student ( ID varchar(5), name varchar(20) not null, dept_name varchar(20), tot_cred numeric(3,0), primary key (ID), foreign key (dept_name) references department); 20

21 create table takes ( ID varchar(5), course_id varchar(8), sec_id varchar(8), semester varchar(6), year numeric(4,0), grade varchar(2), primary key (ID, course_id, sec_id, semester, year), foreign key (ID) references student, foreign key (course_id, sec_id, semester, year) references section); Note: sec_id can be dropped from primary key above, to ensure a student cannot be registered for two sections of the same course in the same semester create table course ( course_id varchar(8), title varchar(50), dept_name varchar(20), credits numeric(2,0), primary key (course_id), foreign key (dept_name) references department); Updates to tables Insert insert into instructor values ( 10211, Smith, Biology, 66000); Delete Remove all tuples from the student relation delete from student Drop Table drop table r Alter 21

22 alter table r add A D alter table r drop A where A is the name of the attribute to be added to relation r and D is the domain of A. All exiting tuples in the relation are assigned null as the value for the new attribute. where A is the name of an attribute of relation r Dropping of attributes not supported by many databases. Basic Query Structure A typical SQL query has the form: select A 1, A 2,..., A n from r 1, r 2,..., r m where P A i represents an attribute R i represents a relation P is a predicate. The result of an SQL query is a relation. Inserting into a Table The insert statement is used to insert or add a row of data into the table. insert into "tablename" (first_column,...last_column) values (first_value,...last_value); Example: insert into employee (first, last, age, address, city, state) values ('Luke', 'Duke', 45, '2130 Boars Nest', 'Hazard Co', 'Georgia'); 22

23 Note: All strings should be enclosed between singlequotes: 'string Table (Employee) Employe_ID Firstname Lastname Gender Job tile Salary Age 10 SHARA SHERZAD Female Programmer ZHAKAW AZAD Male IT Officer AHMED MOHAMMED Male Teacher ZHYAR AHMED Female Teacher ZHALA KAZM Female Manager MEDIA NAWZAD Female Teacher SHANAZ OMED Female Programmer After they're inserted into the table, enter select statements to: 1. Select all columns for everyone in your employee table. 2. Select all columns for everyone with a salary over Select first and last names for everyone that's under 30 years old. 4. Select first name, last name, and salary for anyone with "Programmer" in their title. 5. Select all columns for everyone whose last name contains "ME". 6. Select the first name for everyone whose first name equals "ZH". 7. Select all columns for everyone over 35 years old. 8. Select all columns for everyone whose last name ends in "ZAD". Selecting Data The select statement is used to query the database and retrieve selected data that match the criteria that you specify. Here is the format of a simple select statement: select "column1" [,"column2",etc] from "tablename" [where "condition"]; [] = optional Conditional selections used in the where clause: = Equal > Greater than < Less than >= Greater than or equal 23

24 <= Less than or equal <> Not equal to LIKE *See note below The LIKE pattern matching operator can also be used in the conditional selection of the where clause example: select first, last, city from empinfo where first LIKE 'Er%'; This SQL statement will match any first names that start with 'Er'. Strings must be in single quotes. Or you can specify, select first, last from empinfo where last LIKE '%s'; This statement will match any last names that end in a 's'. select * from empinfo where first = 'Eric'; This will only select rows where the first name equals 'Eric' exactly. select first, last, city from empinfo; select last, city, age from empinfo where age > 30; select first, last, city, state from empinfo where first LIKE 'J%'; select * from empinfo; select first, last, from empinfo where last LIKE '%s'; select first, last, age from empinfo where last LIKE '%illia%'; select * from empinfo where first = 'Eric'; Selecting Data Answers 1. Display everyone's first name and their age for everyone that's in table. 24

25 select first, age from empinfo; 2. Display the first name, last name, and city for everyone that's not from Payson. select first, last, city from empinfo where city <> 'Payson'; 3. Display all columns for everyone that is over 40 years old. select * from empinfo where age > 40; 4. Display the first and last names for everyone whose last name ends in an "ay". select first, last from empinfo where last LIKE '%ay'; 5. Display all columns for everyone whose first name equals "Mary". select * from empinfo where first = 'Mary'; 6. Display all columns for everyone whose first name contains "Mary". select * from empinfo where first LIKE '%Mary%'; Creating Tables The create table statement is used to create a new table. Here is the format of a simple create tablestatement: create table "tablename" ("column1" "data type", "column2" "data type", "column3" "data type"); Format of create table if you were to use optional constraints: create table "tablename" ("column1" "data type" [constraint], "column2" "data type" [constraint], "column3" "data type" [constraint]); [ ] = optional 25

26 Example: create table employee (first varchar(15), last varchar(20), age number(3), address varchar(30), city varchar(20), state varchar(20)); Updating Records The update statement is used to update or change records that match a specified criteria. This is accomplished by carefully constructing a where clause. update "tablename" set "columnname" = "newvalue" [,"nextcolumn" = "newvalue2"...] where "columnname" OPERATOR "value" [and or "column" OPERATOR "value"]; [] = optional [The above example was line wrapped for better viewing on this Web page.] Examples: update phone_book set area_code = 623 where prefix = 979; update phone_book set last_name = 'Smith', prefix=555, suffix=9292 where last_name = 'Jones'; update employee set age = age+1 where first_name='mary' and last_name='williams'; 26

27 Update statement exercises After each update, issue a select statement to verify your changes. 1. Jonie Weber just got married to Bob Williams. She has requested that her last name be updated to Weber-Williams. 2. Dirk Smith's birthday is today, add 1 to his age. 3. All secretaries are now called "Administrative Assistant". Update all titles accordingly. 4. Everyone that's making under are to receive a 3500 a year raise. 5. Everyone that's making over are to receive a 4500 a year raise. 6. All "Programmer II" titles are now promoted to "Programmer III". 7. All "Programmer" titles are now promoted to "Programmer II". Deleting Records The delete statement is used to delete records or rows from the table. delete from "tablename" where "columnname" OPERATOR "value" [and or "column" OPERATOR "value"]; [ ] = optional [The above example was line wrapped for better viewing on this Web page.] Examples: delete from employee where lastname = 'May'; delete from employee where firstname = 'Mike' or firstname = 'Eric'; Drop a Table The drop table command is used to delete a table and all rows in the table. To delete an entire table including all of its rows, issue the drop table command followed by the tablename. drop table is different from deleting all of the records in the table. Deleting all of the records in the table leaves the table including column and constraint information. Dropping the table removes the table definition as well as all of its rows. 27

28 drop table "tablename" Example: drop table myemployees_ts0211; Look at the "Customers" table: Example SELECT * FROM Customers; Every table is broken up into smaller entities called fields. The fields in the Customers table consist of CustomerID, CustomerName, ContactName, Address, City, PostalCode and Country. A field is a column in a table that is designed to maintain specific information about every record in the table. SELECT CustomerName, City FROM Customers; SELECT * FROM Customers; CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquería Around the Horn City Berlin México D.F. México D.F. London SQL SELECT DISTINCT Statement SELECT DISTINCT Country FROM Customers; Country Germany Mexico UK Sweden SELECT * FROM Customers WHERE Country='Mexico'; 28

29 Custome rid CustomerName ContactName Address City PostalCode Countr y 2 Ana Trujillo Ana Trujillo Avda. de la México Mexico Emparedados y helados Constitución 2222 D.F. 3 Antonio Moreno Antonio Mataderos 2312 México Mexico Taquería Moreno D.F. 13 Centro comercial Francisco Sierras de Granada México Mexico Moctezuma Chang 9993 D.F. 58 Pericles Comidas Guillermo Calle Dr. Jorge Cash México Mexico clásicas Fernández 321 D.F. 80 Tortuga Restaurante Miguel Angel Paolino Avda. Azteca 123 México D.F Mexico Table Custome rid CustomerName ContactNa me Address City PostalCo de Count ry 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin Germa ny 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitució n 2222 Méxic o D.F Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 Méxic o D.F Mexico 4 Around the Horn Thomas Hardy 120 Hanover Sq. Londo n WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsväg en 8 Luleå S Swede n SQL AND, OR and NOT Operators SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; 29

30 Result: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin Germany SELECT * FROM Customers WHERE City='Berlin' OR City='München'; Result: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Berlin Germany Str Frankenversand Peter Franken Berliner Platz 43 München Germany SELECT * FROM Customers ORDER BY Country; Result: CustomerI CustomerName ContactName Address City PostalCode Country D 12 Cactus Comidas Patricio Cerrito 333 Buenos Aires 1010 Argentina para llevar Simpson 20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria 76 Suprêmes Pascale Cartrain Boulevard Charleroi B-6000 Belgium délices Tirou, Mère Paillarde Jean Fresnière 43 rue St. Montréal H1J 1C3 Canada Laurent 73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark INSERT INTO Example INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country) VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway'); How to Test for NULL Values? Demo Database Assume we have the following "Persons" table: 30

31 ID LastName FirstName Address City 1 Doe John 542 W. 27th Street New York 2 Bloggs Joe London 3 Roe Jane New York 4 Smith John 110 Bishopsgate London SELECT LastName, FirstName, Address FROM Persons WHERE Address IS NULL; IS NOT NULL Operator SELECT LastName, FirstName, Address FROM Persons WHERE Address IS NOT NULL; UPDATE Table UPDATE Customers SET ContactName = 'Alfred Schmidt', City= 'Frankfurt' WHERE CustomerID = UPDATE Multiple Records UPDATE Customers SET ContactName='Juan' WHERE Country='Mexico'; SQL DELETE Example DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste'; The SQL SELECT TOP Clause SELECT TOP 3 * FROM Customers; SELECT * FROM Customers LIMIT 3; 31

32 SELECT * FROM Customers WHERE ROWNUM <= 3; SQL TOP PERCENT Example SELECT TOP 50 PERCENT * FROM Customers; ADD a WHERE CLAUSE SELECT TOP 3 * FROM Customers WHERE Country='Germany'; SELECT * FROM Customers WHERE Country='Germany' LIMIT 3; SELECT * FROM Customers WHERE Country='Germany' AND ROWNUM <= 3; Demo Database Below is a selection from the "Products" table in the Northwind sample database: ProductID ProductName SupplierID CategoryID Unit Price 1 Chais boxes x 20 bags 18 2 Chang oz bottles 19 3 Aniseed Syrup ml bottles 10 4 Chef Anton's Cajun Seasoning oz jars 22 5 Chef Anton's Gumbo Mix boxes SQL MIN() and MAX() Functions SELECT MIN(Price) AS SmallestPrice FROM Products; SmallestPrice 2.5 SELECT MAX(Price) AS LargestPrice FROM Products; LargestPrice 32

33 263.5 SQL COUNT(), AVG() and SUM() Functions COUNT() Example SELECT COUNT(ProductID) FROM Products; 5 AVG() Example SELECT AVG(Price) FROM Products; Demo Database Below is a selection from the "OrderDetails" table in the Northwind sample database: OrderDetailID OrderID ProductID Quantity SUM() Example SELECT SUM(Quantity) FROM OrderDetails; SQL LIKE Operator Here are some examples showing different LIKE operators with '%' and '_' wildcards: LIKE Operator Description WHERE CustomerName LIKE 'a%' Finds any values that starts with "a" 33

34 WHERE CustomerName LIKE '%a' Finds any values that ends with "a" WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position WHERE CustomerName LIKE 'a_%_%' Finds any values that starts with "a" and are at least 3 characters in length WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o" Demo Database Below is a selection from the "Customers" table in the Northwind sample database: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F Mexico 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 34

35 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S Sweden SQL LIKE Examples SELECT * FROM Customers WHERE CustomerName LIKE 'a%'; Result: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Maria Anders Obere Str. 57 Berlin Germany Futterkiste 2 Ana Trujillo Ana Trujillo Avda. de la México Mexico Emparedados y helados Constitución 2222 D.F. 3 Antonio Moreno Antonio Mataderos 2312 México Mexico Taquería Moreno 4 Around the Horn Thomas Hardy D.F. 120 Hanover Sq. London WA1 1DP UK SELECT * FROM Customers WHERE CustomerName LIKE '%a'; Result: CustomerID CustomerName ContactName Address City PostalCode Country 3 Antonio Moreno Antonio Mataderos México Mexico Taquería Moreno 2312 D.F. 13 Centro Francisco Sierras de México Mexico comercial Moctezuma Chang Granada 9993 D.F. 30 Godos Cocina José Pedro C/ Romero, Sevilla Spain Típica Freyre 61 Que Delícia Bernardo Batista 62 Queen Cozinha Lúcia Carvalho 88 Wellington Paula Parente Importadora 90 Wilman Kala Matti Karttunen 33 Rua da Panificadora, 12 Alameda dos Canàrios, 891 Rua do Mercado, 12 Keskuskatu 45 Rio de Janeiro Brazil São Brazil Paulo Resende Brazil Helsinki Finland 35

36 SELECT * FROM Customers WHERE CustomerName LIKE '%or%'; Result: CustomerID CustomerName ContactName Address City PostalCode Country 3 Antonio Moreno Antonio Mataderos 2312 México Mexico Taquería Moreno D.F. 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 36 Hungry Coyote Yoshi Latimer City Center Plaza Elgin USA Import Store 516 Main St. 40 La corne Daniel Tonini 67, avenue de Versailles France d'abondance l'europe 43 Lazy K Kountry John Steel 12 Orchestra Walla USA Store Terrace Walla 52 Morgenstern Alexander Heerstr. 22 Leipzig Germany Gesundkost Feuer 53 North/South Simon Crowther South House 300 Queensbridge London SW7 1RZ UK SELECT * FROM Customers WHERE CustomerName LIKE '_r%'; Result: CustomerID CustomerName ContactName Address City PostalCode Country 4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK Sq. 17 Drachenblut Sven Ottlieb Walserweg 21 Aachen Germany Delikatessend 20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria 25 Frankenversand Peter Franken Berliner Platz München Germany France restauration Carine Schmitt 54, rue Royale Nantes France 27 Franchi S.p.A. Paolo Accorti Via Monte Torino Italy Bianco Great Lakes Food Howard Snyder 2732 Baker Eugene USA Market Blvd. 33 GROSELLA- Manuel Pereira 5ª Ave. Los Caracas 1081 Venezuela Restaurante Palos Grandes 60 Princesa Isabel Isabel de Estrada da Lisboa 1756 Portugal Vinhoss Castro saúde n Tradição Anabela Av. Inês de São Brazil Hipermercados Domingues Castro, 414 Paulo 82 Trail's Head Gourmet Provisioners Helvetius Nagy 722 DaVinci Blvd. Kirkland USA SELECT * FROM Customers WHERE CustomerName LIKE 'a_%_%'; 36

37 Result: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin Germany 2 Ana Trujillo Ana Trujillo Avda. de la México Mexico Emparedados y helados Constitución 2222 D.F. 3 Antonio Moreno Antonio Mataderos 2312 México Mexico Taquería Moreno D.F. 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK SELECT * FROM Customers WHERE ContactName LIKE 'a%o'; Result: CustomerID CustomerName ContactName Address City PostalCode Country 2 Ana Trujillo Ana Trujillo Avda. de la México Mexico Emparedados y helados Constitución 2222 D.F. 3 Antonio Moreno Antonio Mataderos 2312 México Mexico Taquería Moreno 69 Romero y tomillo Alejandra Camino D.F. Gran Vía, 1 Madrid Spain SELECT * FROM Customers WHERE CustomerName NOT LIKE 'a%'; Result: CustomerID CustomerName ContactName Address City PostalCode Country 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S Sweden 6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim Germany 7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg France SQL Wildcard Characters Here are some examples showing different LIKE operators with '%' and '_' wildcards: 37

38 LIKE Operator Description WHERE CustomerName LIKE 'a%' Finds any values that starts with "a" WHERE CustomerName LIKE '%a' Finds any values that ends with "a" WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position WHERE CustomerName LIKE 'a_%_%' Finds any values that starts with "a" and are at least 3 characters in length WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o" Demo Database Below is a selection from the "Customers" table in the Northwind sample database: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F Mexico 38

39 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S Sweden SELECT * FROM Customers WHERE City LIKE 'ber%'; Result: Number of Records: 3 CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. Berlin Germany Chop-suey Yang Wang Hauptstr. Bern 3012 Switzerland Chinese Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22 Bergamo Italy SELECT * FROM Customers WHERE City LIKE '%es%'; Result: Number of Records: 9 CustomerID CustomerName ContactName Address City PostalCode Country 12 Cactus Comidas Patricio Cerrito 333 Buenos 1010 Argentina para llevar Simpson Aires 18 Du monde entier Janine 67, rue des Nantes France Labrune Cinquante Otages 26 France Carine Schmitt 54, rue Royale Nantes France restauration 38 Island Trading Helen Bennett Garden House Cowes PO31 7PJ UK Crowther Way 40 La corne Daniel Tonini 67, avenue de Versailles France d'abondance l'europe 50 Maison Dewey Catherine Rue Joseph- Bruxelles B-1180 Belgium 54 Océano Atlántico Ltda. Dewey Yvonne Moncada Bens 532 Ing. Gustavo Moncada 8585 Buenos Aires 1010 Argentina 39

40 64 Rancho grande Sergio Gutiérrez 88 Wellington Paula Parente Importadora Piso 20-A Av. del Libertador 900 Rua do Mercado, 12 Buenos 1010 Argentina Aires Resende Brazil SELECT * FROM Customers WHERE City LIKE '_erlin'; Result: Number of Records: 1 CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin Germany SELECT * FROM Customers WHERE City LIKE 'L_n_on'; Result: Number of Records: 6 CustomerID CustomerName ContactName Address City PostalCode Country 4 Around the Horn Thomas Hardy 120 London WA1 1DP UK Hanover Sq. 11 B's Beverages Victoria Fauntleroy London EC2 5NT UK Ashworth Circus 16 Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery London WX1 6LT UK SELECT * FROM Customers WHERE City LIKE '[bsp]%'; Customer CustomerNa ID me 1 Alfreds Futterkiste 7 Blondel père et fils 12 Cactus Comidas para llevar ContactNa me Maria Anders Frédérique Citeaux Patricio Simpson Addre ss Obere Str , place Kléber Cerrito 333 City PostalCo de Countr y Berlin German y Strasbour France g Buenos Aires 1010 Argenti na 40

41 SELECT * FROM Customers WHERE City LIKE '[a-c]%'; CustomerI CustomerNa D me 1 Alfreds Futterkiste 12 Cactus Comidas para llevar 14 Chop-suey Chinese ContactNa me Maria Anders Patricio Simpson Yang Wang Addres s Obere Str. 57 Cerrito 333 Hauptst r. 29 City PostalCo Country de Berlin Germany Bueno s Aires 1010 Argentina Bern 3012 Switzerlan d SQL IN Operator Below is a selection from the "Customers" table in the Northwind sample database: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F Mexico SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK'); Result: Number of Records: 29 CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. Berlin Germany 57 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim Germany 41

42 SELECT * FROM Customers WHERE Country NOT IN ('Germany', 'France', 'UK'); CustomerID CustomerName ContactName Address City PostalCode Country 2 Ana Trujillo Ana Trujillo Avda. de la México Mexico Emparedados y helados Constitución 2222 D.F. 3 Antonio Moreno Antonio Mataderos 2312 México Mexico Taquería Moreno 5 Berglunds snabbköp Christina Berglund D.F. Berguvsvägen 8 Luleå S Sweden SELECT * FROM Customers WHERE Country IN (SELECT Country FROM Suppliers); SQL BETWEEN Operator Demo Database Below is a selection from the "Products" table in the Northwind sample database: ProductID ProductName SupplierID CategoryID Unit Price 1 Chais boxes x 20 bags 18 2 Chang oz bottles 19 BETWEEN Example SELECT * FROM Products WHERE Price BETWEEN 10 AND 20; Result: ProductID ProductName SupplierID CategoryID Unit Price 1 Chais boxes x 20 bags 18 2 Chang oz bottles 19 3 Aniseed Syrup ml bottles 10 42

43 SELECT * FROM Products WHERE Price BETWEEN 10 AND 20; Result: ProductID ProductName SupplierID CategoryID Unit Price 1 Chais boxes x 20 bags 18 2 Chang oz bottles 19 3 Aniseed Syrup ml bottles 10 SQL Aliases SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used to make column names more readable. An alias only exists for the duration of the query. Alias Column Syntax SELECT column_name AS alias_name FROM table_name; Alias for Columns Examples SELECT CustomerID as ID, CustomerName AS Customer FROM Customers; SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address FROM Customers; CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquería Around the Horn Address Obere Str. 57, Berlin, Germany Avda. de la Constitución 2222, México D.F., Mexico Mataderos 2312, México D.F., Mexico 120 Hanover Sq., WA1 1DP London, UK 43

44 SQL JOIN A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Let's look at a selection from the "Orders" table: OrderID CustomerID OrderDate Then, look at a selection from the "Customers" table: CustomerID CustomerName ContactName Country 1 Alfreds Futterkiste Maria Anders Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico 3 Antonio Moreno Taquería Antonio Moreno Mexico Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table. The relationship between the two tables above is the "CustomerID" column. Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records that have matching values in both tables: Example SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders 44

45 INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerI D; Result: OrderID CustomerName OrderDate Wilman Kala Tradição Hipermercados Hanari Carnes Victuailles en stock Suprêmes délices Hanari Carnes Chop-suey Chinese Richter Supermarkt Wellington Importadora Different Types of SQL JOINs Here are the different types of the JOINs in SQL: (INNER) JOIN: Returns records that have matching values in both tables LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table FULL (OUTER) JOIN: Return all records when there is a match in either left or right table SQL UNION Operator The UNION operator is used to combine the result-set of two or more SELECT statements. Each SELECT statement within UNION must have the same number of columns The columns must also have similar data types The columns in each SELECT statement must also be in the same order 45

46 emo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F Mexico And a selection from the "Suppliers" table: SupplierID SupplierName ContactName Address City PostalCode Country 1 Exotic Liquid Charlotte Cooper 49 Gilbert St. London EC1 4SD UK 2 New Orleans Cajun Delights Shelley Burke P.O. Box New Orleans USA 3 Grandma Kelly's Homestead Regina Murphy 707 Oxford Rd. Ann Arbor USA SQL UNION Example SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City; 46

47 Result: Number of Records: 94 City Aachen Albuquerque Anchorage SELECT City, Country FROM Customers WHERE Country='Germany' UNION SELECT City, Country FROM Suppliers WHERE Country='Germany' ORDER BY City; Result: City Aachen Berlin Brandenburg SQL GROUP BY Statement Country Germany Germany Germany Demo Database Below is a selection from the "Customers" table in the Northwind sample database: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin Germany 2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México D.F Mexico 47

48 helados 2222 SQL GROUP BY Examples SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country; Result: COUNT(CustomerID) Country 3 Argentina 2 Austria 2 Belgium SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country ORDER BY COUNT(CustomerID) DESC; Result: COUNT(CustomerID) Country 13 USA 11 France SQL HAVING Clause Demo Database Below is a selection from the "Customers" table in the Northwind sample database: CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F Mexico 48

49 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F Mexico 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S Sweden SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5; Result: COUNT(CustomerID) Country 9 Brazil 11 France 11 Germany 7 UK 13 USA SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5 ORDER BY COUNT(CustomerID) DESC; Result: COUNT(CustomerID) Country 13 USA 11 France 11 Germany 9 Brazil 7 UK 49

50 SQL INSERT INTO SELECT Examples INSERT INTO Customers (CustomerName, City, Country) SELECT SupplierName, City, Country FROM Suppliers; INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country) SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers; SQL CREATE DATABASE Statement CREATE DATABASE databasename; SQL DROP DATABASE Statement DROP DATABASE databasename; DROP DATABASE testdb; SQL CREATE TABLE Statement CREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) ); SQL DROP TABLE Statement DROP TABLE table_name; DROP TABLE Shippers; 50

51 SQL ALTER TABLE Statement ALTER TABLE table_name MODIFY COLUMN column_name datatype; SQL Create Constraints Constraints can be specified when the table is created with the CREATE TABLE statement, or after the table is created with the ALTER TABLE statement. CREATE TABLE table_name ( column1 datatype constraint, column2 datatype constraint, column3 datatype constraint,... ); SQL NOT NULL Constraint By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field. The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept NULL values CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255) NOT NULL, Age int ); 51

52 SQL UNIQUE Constraint The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table. SQL UNIQUE Constraint on CREATE TABLE The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is created: SQL Server / Oracle / MS Access: CREATE TABLE Persons ( ID int NOT NULL UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int ); SQL PRIMARY KEY on CREATE TABLE SQL Server / Oracle / MS Access: CREATE TABLE Persons ( ID int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int ); SQL FOREIGN KEY Constraint A FOREIGN KEY is a key used to link two tables together. A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table. 52

53 The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table. Look at the following two tables: "Persons" table: PersonID LastName FirstName Age 1 Hansen Ola 30 2 Svendson Tove 23 3 Pettersen Kari 20 "Orders" table: OrderID OrderNumber PersonID Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the "Persons" table. The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table. The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. 53

54 The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the table it points to. SQL Server / Oracle / MS Access: CREATE TABLE Orders ( OrderID int NOT NULL PRIMARY KEY, OrderNumber int NOT NULL, PersonID int FOREIGN KEY REFERENCES Persons(PersonID) ); SQL CHECK on CREATE TABLE SQL Server / Oracle / MS Access: CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int CHECK (Age>=18) ); SQL DEFAULT on CREATE TABLE The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is created: My SQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, City varchar(255) DEFAULT 'Sandnes' ); SQL AUTO INCREMENT Field 54

55 CREATE TABLE Persons ( ID int NOT NULL AUTO_INCREMENT, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, PRIMARY KEY (ID) ); SQL Working With Dates SQL Date Data Types MySQL comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD DATETIME - format: YYYY-MM-DD HH:MI:SS TIMESTAMP - format: YYYY-MM-DD HH:MI:SS YEAR - format YYYY or YY SQL Server comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD DATETIME - format: YYYY-MM-DD HH:MI:SS SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS TIMESTAMP - format: a unique number Assume we have the following "Orders" table: OrderId ProductName OrderDate 1 Geitost Camembert Pierrot Mozzarella di Giovanni

56 4 Mascarpone Fabioli Now we want to select the records with an OrderDate of " " from the table above. We use the following SELECT statement: SELECT * FROM Orders WHERE OrderDate=' ' The result-set will look like this: OrderId ProductName OrderDate 1 Geitost Mozzarella di Giovanni Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate" column): OrderId ProductName OrderDate 1 Geitost :23:44 2 Camembert Pierrot :45:21 3 Mozzarella di Giovanni :12:01 4 Mascarpone Fabioli :56:59 If we use the same SELECT statement as above: SELECT * FROM Orders WHERE OrderDate=' ' we will get no result! This is because the query is looking only for dates with no time portion. 56

57 Tip: To keep your queries simple and easy to maintain, do not allow time components in your dates! SQL Arithmetic Operators Operator Description + Add - Subtract * Multiply / Divide % Modulo Text data types: Data type Description CHAR(size) Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note:If you put a greater value than 255 it will be converted to a TEXT type TINYTEXT Holds a string with a maximum length of 255 characters TEXT Holds a string with a maximum length of 65,535 characters BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters 57

58 MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. Note: The values are sorted in the order you enter them. SET You enter the possible values in this format: ENUM('X','Y','Z') Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice Number data types: Data type Description TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis SMALLINT(size) to normal. 0 to UNSIGNED*. The maximum number of digits may be specified in parenthesis MEDIUMINT(size) to normal. 0 to UNSIGNED*. The maximum number of digits may be specified in parenthesis INT(size) to normal. 0 to UNSIGNED*. The maximum number of digits may be specified in parenthesis BIGINT(size) to normal. 0 to UNSIGNED*. The maximum number of digits may be specified in parenthesis FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of 58

59 digits to the right of the decimal point is specified in the d parameter DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter DECIMAL(size,d) A DOUBLE stored as a string, allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter *The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a negative number. Date data types: Data type Description DATE() DATETIME() TIMESTAMP() TIME() YEAR() A date. Format: YYYY-MM-DD Note: The supported range is from ' ' to ' ' *A date and time combination. Format: YYYY-MM-DD HH:MI:SS Note: The supported range is from ' :00:00' to ' :59:59' *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch (' :00:00' UTC). Format: YYYY-MM-DD HH:MI:SS Note: The supported range is from ' :00:01' UTC to ' :14:07' UTC A time. Format: HH:MI:SS Note: The supported range is from '-838:59:59' to '838:59:59' A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069 *Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time. TIMESTAMP also accepts various formats, like 59

60 YYYYMMDDHHMISS, YYMMDDHHMISS, YYYYMMDD, or YYMMDD. SQL Server Data Types String data types: Data type Description Max size Storage char(n) Fixed width character string 8,000 characters Defined width varchar(n) Variable width character string 8,000 characters 2 bytes + number of chars varchar(max) Variable width character string 1,073,741,824 characters 2 bytes + number of chars text Variable width character string 2GB of text data 4 bytes + number of chars nchar Fixed width Unicode string 4,000 characters Defined width x 2 nvarchar Variable width Unicode string 4,000 characters nvarchar(max) Variable width Unicode string 536,870,912 characters 60

61 ntext Variable width Unicode string 2GB of text data binary(n) Fixed width binary string 8,000 bytes varbinary Variable width binary string 8,000 bytes varbinary(max) Variable width binary string 2GB image Variable width binary string 2GB Number data types: Data type Description Storage bit Integer that can be 0, 1, or NULL tinyint Allows whole numbers from 0 to byte smallint Allows whole numbers between -32,768 and 32,767 2 bytes int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes bigint Allows whole numbers between - 9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 8 bytes 61

62 decimal(p,s) numeric(p,s) Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18. The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0 Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is bytes 5-17 bytes The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0 smallmoney Monetary data from -214, to 214, money Monetary data from -922,337,203,685, to 922,337,203,685, float(n) Floating precision number data from -1.79E to 1.79E The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53. real Floating precision number data from -3.40E + 38 to 3.40E + 38 Date data types: 4 bytes 8 bytes 4 or 8 bytes 4 bytes Data type Description Storage 62

63 datetime From January 1, 1753 to December 31, 9999 with 8 bytes datetime2 From January 1, 0001 to December 31, 9999 with 6-8 bytes smalldatetime From January 1, 1900 to June 6, 2079 with an 4 bytes date Store a date only. From January 1, 0001 to 3 bytes time Store a time only to an accuracy of bytes datetimeoffset The same as datetime2 with the addition of a 8-10 bytes timestamp Stores a unique number that gets updated every Other data types: Data type sql_variant uniqueidentifier xml cursor table Description Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp Stores a globally unique identifier (GUID) Stores XML formatted data. Maximum 2GB Stores a reference to a cursor used for database operations Stores a result-set for later processing Teacher SHERZAD ABDULLAH

64 SQL LIKE Operator with '%' and '_' In SQL Server 2012 LIKE Operator Description 1- WHERE CustomerName LIKE 'a%' Finds any values that starts with "a" 2- WHERE CustomerName LIKE '%a' Finds any values that ends with "a" 3- WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position 4- WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position 5- WHERE CustomerName LIKE 'a_%_%' Finds any values that starts with "a" and are at least 3 characters in length 6- WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o" 1- SELECT * FROM Customer WHERE CustomerName LIKE 'a%'; 2- SELECT * FROM Customer WHERE CustomerName LIKE '%a'; 3- SELECT * FROM Customer WHERE CustomerName LIKE '%or%'; 4- SELECT * FROM Customer WHERE CustomerName LIKE '_r%'; 5- SELECT * FROM Customer WHERE CustomerName LIKE 'a_%_%'; 6- SELECT * FROM Customer WHERE ContactName LIKE 'a%o'; 7- SELECT * FROM Customer WHERE CustomerName NOT LIKE 'a%'; 64

65 3 CustomerName LIKE '%or%'; 4 CustomerName LIKE '_r%'; 5 CustomerName LIKE 'a_%_%'; 6 ContactName LIKE 'a%o'; 7- CustomerName NOT LIKE 'a%'; پهيمانگهى )ئاگا( ى ناحكومى بۆ زانستهكانى كۆمپيوتهر 65

66 Sum, AVG, Count, Min, Max SELECT Sum(Price) FROM ProductID; SELECT sum(price)/2 FROM ProductID; SELECT AVG(Price) FROM ProductID; SELECT Count(Price) FROM ProductID; SELECT Max(Price) FROM ProductID; SELECT Min(Price) FROM ProductID; 66

MySQL. Prof.Sushila Aghav

MySQL. Prof.Sushila Aghav MySQL Prof.Sushila Aghav Introduction SQL is a standard language for storing, manipulating and retrieving data in databases. SQL is a part of many relational database management systems like: MySQL, SQL

More information

SQL is a standard language for accessing and manipulating databases.

SQL is a standard language for accessing and manipulating databases. Introduction to SQL SQL is a standard language for accessing and manipulating databases. What is SQL? SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI

More information

L e a r n S q l select where

L e a r n S q l select where L e a r n S q l The select statement is used to query the database and retrieve selected data that match the criteria that you specify. Here is the format of a simple select statement: select "column1"

More information

Chapter 1: Introduction

Chapter 1: Introduction Chapter 1: Introduction Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Outline The Need for Databases Data Models Relational Databases Database Design Storage Manager Query

More information

11. Introduction to SQL

11. Introduction to SQL 11. Introduction to SQL 11.1 What is SQL? SQL stands for Structured Query Language SQL allows you to access a database SQL is an ANSI standard language SQL can execute queries against a database SQL can

More information

Database Technology Introduction. Heiko Paulheim

Database Technology Introduction. Heiko Paulheim Database Technology Introduction Outline The Need for Databases Data Models Relational Databases Database Design Storage Manager Query Processing Transaction Manager Introduction to the Relational Model

More information

Jarek Szlichta

Jarek Szlichta Jarek Szlichta http://data.science.uoit.ca/ SQL is a standard language for accessing and manipulating databases What is SQL? SQL stands for Structured Query Language SQL lets you gain access and control

More information

CS425 Fall 2016 Boris Glavic Chapter 1: Introduction

CS425 Fall 2016 Boris Glavic Chapter 1: Introduction CS425 Fall 2016 Boris Glavic Chapter 1: Introduction Modified from: Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Textbook: Chapter 1 1.2 Database Management System (DBMS)

More information

Chapter 1: Introduction

Chapter 1: Introduction This image cannot currently be displayed. Chapter 1: Introduction Database System Concepts, 5th Ed. See www.db-book.com for conditions on re-use Chapter 1: Introduction Purpose of Database Systems View

More information

Chapter 1: Introduction. Chapter 1: Introduction

Chapter 1: Introduction. Chapter 1: Introduction Chapter 1: Introduction Database System Concepts, 5th Ed. See www.db-book.com for conditions on re-use Chapter 1: Introduction Purpose of Database Systems View of Data Database Languages Relational Databases

More information

UNIT I. Introduction

UNIT I. Introduction UNIT I Introduction Objective To know the need for database system. To study about various data models. To understand the architecture of database system. To introduce Relational database system. Introduction

More information

Chapter 1: Introduction

Chapter 1: Introduction Chapter 1: Introduction Chapter 1: Introduction Purpose of Database Systems Database Languages Relational Databases Database Design Data Models Database Internals Database Users and Administrators Overall

More information

Chapter 1: Introduction

Chapter 1: Introduction Chapter 1: Introduction Slides are slightly modified by F. Dragan Database System Concepts, 5th Ed. See www.db-book.com for conditions on re-use Chapter 1: Introduction Purpose of Database Systems View

More information

Database Management Systems (CPTR 312)

Database Management Systems (CPTR 312) Database Management Systems (CPTR 312) Preliminaries Me: Raheel Ahmad Ph.D., Southern Illinois University M.S., University of Southern Mississippi B.S., Zakir Hussain College, India Contact: Science 116,

More information

Database Principle. Zhuo Wang Spring

Database Principle. Zhuo Wang Spring Database Principle Zhuo Wang zhuowang@sjtu.edu.cn 2017 Spring Overview Data Database Database Management System Database System References Database System Concepts Abraham Silberschatz, Henry F. Korth,

More information

Database Management System. Fundamental Database Concepts

Database Management System. Fundamental Database Concepts Database Management System Fundamental Database Concepts CONTENTS Basics of DBMS Purpose of DBMS Applications of DBMS Views of Data Instances and Schema Data Models Database Languages Responsibility of

More information

Advance SQL: SQL Performance Tuning. SQL Views

Advance SQL: SQL Performance Tuning. SQL Views Advance SQL: SQL Performance Tuning SQL Views A view is nothing more than a SQL statement that is stored in the database with an associated name. A view is actually a composition of a table in the form

More information

Unit I. By Prof.Sushila Aghav MIT

Unit I. By Prof.Sushila Aghav MIT Unit I By Prof.Sushila Aghav MIT Introduction The Need for Databases Data Models Relational Databases Database Design Storage Manager Query Processing Transaction Manager DBMS Applications DBMS contains

More information

Chapter 1: Introduction

Chapter 1: Introduction Chapter 1: Introduction Chapter 2: Intro. To the Relational Model Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Database Management System (DBMS) DBMS is Collection of

More information

Chapter 1 Introduction

Chapter 1 Introduction Chapter 1 Introduction Contents The History of Database System Overview of a Database Management System (DBMS) Three aspects of database-system studies the state of the art Introduction to Database Systems

More information

CS34800 Information Systems. Course Overview Prof. Walid Aref January 8, 2018

CS34800 Information Systems. Course Overview Prof. Walid Aref January 8, 2018 CS34800 Information Systems Course Overview Prof. Walid Aref January 8, 2018 1 Why this Course? Managing Data is one of the primary uses of computers This course covers the foundations of organized data

More information

QQ Group

QQ Group QQ Group: 617230453 1 Extended Relational-Algebra-Operations Generalized Projection Aggregate Functions Outer Join 2 Generalized Projection Extends the projection operation by allowing arithmetic functions

More information

Database System Concepts

Database System Concepts s Design Chapter 1: Introduction Departamento de Engenharia Informática Instituto Superior Técnico 1 st Semester 2009/2010 Slides (fortemente) baseados nos slides oficiais do livro c Silberschatz, Korth

More information

B.H.GARDI COLLEGE OF MASTER OF COMPUTER APPLICATION. Ch. 1 :- Introduction Database Management System - 1

B.H.GARDI COLLEGE OF MASTER OF COMPUTER APPLICATION. Ch. 1 :- Introduction Database Management System - 1 Basic Concepts :- 1. What is Data? Data is a collection of facts from which conclusion may be drawn. In computer science, data is anything in a form suitable for use with a computer. Data is often distinguished

More information

SQL. Structured Query Language (SQL ISO/CEI 9075:2011) focused mainly on Oracle 11g r2 for Data Science. Vincent ISOZ V6.0 r ouuid 1839

SQL. Structured Query Language (SQL ISO/CEI 9075:2011) focused mainly on Oracle 11g r2 for Data Science. Vincent ISOZ V6.0 r ouuid 1839 SQL Structured Query Language (SQL ISO/CEI 9075:2011) focused mainly on Oracle 11g r2 for Data Science Vincent ISOZ V6.0 r13 2018-12-09 ouuid 1839 Table Of Contents 1 Useful Links... 8 2 Introduction...

More information

Introduction Database Concepts

Introduction Database Concepts Introduction Database Concepts CO attained : CO1 Hours Required: 05 Self Study: 08 Prepared and presented by : Ms. Swati Abhang Contents Introduction Characteristics of databases, File system V/s Database

More information

D.Hemavathi & R.Venkatalakshmi, Assistant Professor, SRM University, Kattankulathur

D.Hemavathi & R.Venkatalakshmi, Assistant Professor, SRM University, Kattankulathur DATABASE SYSTEMS IT 0303 5 TH Semester D.Hemavathi & R.Venkatalakshmi, Assistant Professor, SRM University, Kattankulathur School of Computing, Department of IT Unit 1: introduction 1 Disclaimer The contents

More information

Upon completion of this Unit, the students will be introduced to the following

Upon completion of this Unit, the students will be introduced to the following Instructional Objectives Upon completion of this Unit, the students will be introduced to the following The meaning of the term database. Meaning of the term Database Management System (DBMS). The typical

More information

CHAPTER: 4 ADVANCE SQL: SQL PERFORMANCE TUNING (12 Marks)

CHAPTER: 4 ADVANCE SQL: SQL PERFORMANCE TUNING (12 Marks) (12 Marks) 4.1 VIEW View: Views are virtual relations mainly used for security purpose, and can be provided on request by a particular user. A view can contain all rows of a table or select rows from a

More information

Chapter 3: Introduction to SQL

Chapter 3: Introduction to SQL Chapter 3: Introduction to SQL Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Chapter 3: Introduction to SQL Overview of the SQL Query Language Data Definition Basic Query

More information

Institute of Aga. Microsoft SQL Server LECTURER NIYAZ M. SALIH

Institute of Aga. Microsoft SQL Server LECTURER NIYAZ M. SALIH Institute of Aga 2018 Microsoft SQL Server LECTURER NIYAZ M. SALIH Database: A Database is a collection of related data organized in a way that data can be easily accessed, managed and updated. Any piece

More information

SQL Server and SQL Structured Query Language

SQL Server and SQL Structured Query Language SQL Server and SQL Structured Query Language Step by step Exercises Hans-Petter Halvorsen Database Systems Hans-Petter Halvorsen, M.Sc. Database Systems A Database is a structured way to store lots of

More information

Course Logistics & Chapter 1 Introduction

Course Logistics & Chapter 1 Introduction CMSC 461, Database Management Systems Spring 2018 Course Logistics & Chapter 1 Introduction These slides are based on Database System Concepts book th edition, and the 2009 CMSC 461 slides by Dr. Kalpakis

More information

Department of Computer Science & IT

Department of Computer Science & IT Department of Computer Science & IT Laboratory Manual (A Guide to MySQL) Prepared by: Muhammad Nouman Farooq Senior Lecturer Page 1 of 111 Course: Database Systems (CS-208 & CS-503) Table of Contents Lab

More information

Unit1: Introduction. Database System Concepts, 6 th Ed. Silberschatz, Korth and Sudarshan See for conditions on re-use

Unit1: Introduction. Database System Concepts, 6 th Ed. Silberschatz, Korth and Sudarshan See   for conditions on re-use Unit1: Introduction Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Outline Introduction to Database Management Systems, Purpose of Database Systems, Database-System Applications,

More information

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data.

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data. Managing Data Data storage tool must provide the following features: Data definition (data structuring) Data entry (to add new data) Data editing (to change existing data) Querying (a means of extracting

More information

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL Chapter 3: Introduction to SQL Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Chapter 3: Introduction to SQL Overview of The SQL Query Language Data Definition Basic Query

More information

Principles of Data Management

Principles of Data Management Principles of Data Management Alvin Lin August 2018 - December 2018 Structured Query Language Structured Query Language (SQL) was created at IBM in the 80s: SQL-86 (first standard) SQL-89 SQL-92 (what

More information

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH Private Institute of Aga 2018 NETWORK DATABASE LECTURER NIYAZ M. SALIH Data Definition Language (DDL): String data Types: Data Types CHAR(size) NCHAR(size) VARCHAR2(size) Description A fixed-length character

More information

The SQL data-definition language (DDL) allows defining :

The SQL data-definition language (DDL) allows defining : Introduction to SQL Introduction to SQL Overview of the SQL Query Language Data Definition Basic Query Structure Additional Basic Operations Set Operations Null Values Aggregate Functions Nested Subqueries

More information

QUETZALANDIA.COM. 5. Data Manipulation Language

QUETZALANDIA.COM. 5. Data Manipulation Language 5. Data Manipulation Language 5.1 OBJECTIVES This chapter involves SQL Data Manipulation Language Commands. At the end of this chapter, students should: Be familiar with the syntax of SQL DML commands

More information

Chapter 3: Introduction to SQL

Chapter 3: Introduction to SQL Chapter 3: Introduction to SQL Database System Concepts, 6 th Ed. See www.db-book.com for conditions on re-use Chapter 3: Introduction to SQL Overview of the SQL Query Language Data Definition Basic Query

More information

SQL Commands & Mongo DB New Syllabus

SQL Commands & Mongo DB New Syllabus Chapter 15 : Computer Science Class XI ( As per CBSE Board) SQL Commands & Mongo DB New Syllabus 2018-19 SQL SQL is an acronym of Structured Query Language.It is a standard language developed and used

More information

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates Chapter 13 : Informatics Practices Class XI ( As per CBSE Board) SQL Commands New Syllabus 2018-19 SQL SQL is an acronym of Structured Query Language.It is a standard language developed and used for accessing

More information

SQL Interview Questions

SQL Interview Questions SQL Interview Questions SQL stands for Structured Query Language. It is used as a programming language for querying Relational Database Management Systems. In this tutorial, we shall go through the basic

More information

DATABASE MANAGEMENT SYSTEMS. UNIT I Introduction to Database Systems

DATABASE MANAGEMENT SYSTEMS. UNIT I Introduction to Database Systems DATABASE MANAGEMENT SYSTEMS UNIT I Introduction to Database Systems Terminology Data = known facts that can be recorded Database (DB) = logically coherent collection of related data with some inherent

More information

Natural-Join Operation

Natural-Join Operation Natural-Join Operation Natural join ( ) is a binary operation that is written as (r s) where r and s are relations. The result of the natural join is the set of all combinations of tuples in r and s that

More information

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1 SQL Fundamentals Chapter 3 Class 03: SQL Fundamentals 1 Class 03: SQL Fundamentals 2 SQL SQL (Structured Query Language): A language that is used in relational databases to build and query tables. Earlier

More information

8. Orders shipping to France or Belgium

8. Orders shipping to France or Belgium 8. Orders shipping to France or Belgium Looking at the Orders table, there s a field called ShipCountry. Write a query that shows the OrderID, CustomerID, and ShipCountry for the orders where the ShipCountry

More information

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 304 Introduction to Database Systems SQL DDL Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca SQL Overview Structured Query Language or SQL is the standard query language

More information

COMP Instructor: Dimitris Papadias WWW page:

COMP Instructor: Dimitris Papadias WWW page: COMP 5311 Instructor: Dimitris Papadias WWW page: http://www.cse.ust.hk/~dimitris/5311/5311.html Textbook Database System Concepts, A. Silberschatz, H. Korth, and S. Sudarshan. Reference Database Management

More information

Entity Relationship Diagrams and Relational DBs

Entity Relationship Diagrams and Relational DBs Entity Relationship Diagrams and Relational DBs BSAD 4 Dave Novak Topics Covered ERD (entity relationship diagram) Data Modeling Entity vs- Entity set Attribute vs- Relationship Types of attributes and

More information

CISC 3140 (CIS 20.2) Design & Implementation of Software Application II

CISC 3140 (CIS 20.2) Design & Implementation of Software Application II CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Email Address: meyer@sci.brooklyn.cuny.edu Course Page: http://www.sci.brooklyn.cuny.edu/~meyer/ CISC3140-Meyer-lec4

More information

Full file at

Full file at David Kroenke's Database Processing: Fundamentals, Design and Implementation (10 th Edition) CHAPTER TWO INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) True-False Questions 1. SQL stands for Standard

More information

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS Questions & Answers- DBMS https://career.guru99.com/top-50-database-interview-questions/ 1) Define Database. A prearranged collection of figures known as data is called database. 2) What is DBMS? Database

More information

MIS2502: Review for Exam 2. JaeHwuen Jung

MIS2502: Review for Exam 2. JaeHwuen Jung MIS2502: Review for Exam 2 JaeHwuen Jung jaejung@temple.edu http://community.mis.temple.edu/jaejung Overview Date/Time: Wednesday, Mar 28, in class (50 minutes) Place: Regular classroom Please arrive 5

More information

STRUCTURED QUERY LANGUAGE (SQL)

STRUCTURED QUERY LANGUAGE (SQL) STRUCTURED QUERY LANGUAGE (SQL) SQL is a standard computer language for accessing and manipulating databases. In this tutorial you will learn how to use SQL to access and manipulate data in Oracle, Sybase,

More information

Mahathma Gandhi University

Mahathma Gandhi University Mahathma Gandhi University BSc Computer science III Semester BCS 303 OBJECTIVE TYPE QUESTIONS Choose the correct or best alternative in the following: Q.1 In the relational modes, cardinality is termed

More information

COUNT Function. The COUNT function returns the number of rows in a query.

COUNT Function. The COUNT function returns the number of rows in a query. Created by Ahsan Arif COUNT Function The COUNT function returns the number of rows in a query. The syntax for the COUNT function is: SELECT COUNT(expression) FROM tables WHERE predicates; Note: The COUNT

More information

Structured Query Language (SQL)

Structured Query Language (SQL) Structured Query Language (SQL) SQL Chapters 6 & 7 (7 th edition) Chapters 4 & 5 (6 th edition) PostgreSQL on acsmysql1.acs.uwinnipeg.ca Each student has a userid and initial password acs!

More information

ACS-3902 Fall Ron McFadyen 3D21 Slides are based on chapter 5 (7 th edition) (chapter 3 in 6 th edition)

ACS-3902 Fall Ron McFadyen 3D21 Slides are based on chapter 5 (7 th edition) (chapter 3 in 6 th edition) ACS-3902 Fall 2016 Ron McFadyen 3D21 ron.mcfadyen@acs.uwinnipeg.ca Slides are based on chapter 5 (7 th edition) (chapter 3 in 6 th edition) 1 The Relational Data Model and Relational Database Constraints

More information

CS143: Relational Model

CS143: Relational Model CS143: Relational Model Book Chapters (4th) Chapters 1.3-5, 3.1, 4.11 (5th) Chapters 1.3-7, 2.1, 3.1-2, 4.1 (6th) Chapters 1.3-6, 2.105, 3.1-2, 4.5 Things to Learn Data model Relational model Database

More information

The Structured Query Language Get Started

The Structured Query Language Get Started The Structured Query Language Get Started Himadri Barman 0. Prerequisites: A database is an organized collection of related data that can easily be retrieved and used. By data, we mean known facts that

More information

Views in SQL Server 2000

Views in SQL Server 2000 Views in SQL Server 2000 By: Kristofer Gafvert Copyright 2003 Kristofer Gafvert 1 Copyright Information Copyright 2003 Kristofer Gafvert (kgafvert@ilopia.com). No part of this publication may be transmitted,

More information

':~W zi Ascending 'i; Selection -., =. New E Totals Jfi { Replace Calibri ;E ^~

':~W zi Ascending 'i; Selection -., =. New E Totals Jfi { Replace Calibri ;E ^~ HANDS-ON E ISES i* HOE2 Training 2 Filters, Sorts, and Access ersus Excel The sales managers at Northwind Traders need quick answers to their questions about customer orders. You use the Access database

More information

CMPT 354: Database System I. Lecture 2. Relational Model

CMPT 354: Database System I. Lecture 2. Relational Model CMPT 354: Database System I Lecture 2. Relational Model 1 Outline An overview of data models Basics of the Relational Model Define a relational schema in SQL 2 Outline An overview of data models Basics

More information

Chapter-14 SQL COMMANDS

Chapter-14 SQL COMMANDS Chapter-14 SQL COMMANDS What is SQL? Structured Query Language and it helps to make practice on SQL commands which provides immediate results. SQL is Structured Query Language, which is a computer language

More information

Exam code: Exam name: Database Fundamentals. Version 16.0

Exam code: Exam name: Database Fundamentals. Version 16.0 98-364 Number: 98-364 Passing Score: 800 Time Limit: 120 min File Version: 16.0 Exam code: 98-364 Exam name: Database Fundamentals Version 16.0 98-364 QUESTION 1 You have a table that contains the following

More information

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH 2017 Institute of Aga Network Database LECTURER NIYAZ M. SALIH Database: A Database is a collection of related data organized in a way that data can be easily accessed, managed and updated. Any piece of

More information

MIS2502: Review for Exam 2. Jing Gong

MIS2502: Review for Exam 2. Jing Gong MIS2502: Review for Exam 2 Jing Gong gong@temple.edu http://community.mis.temple.edu/gong Overview Date/Time: Thursday, March 24, in class (1 hour 20 minutes) Place: Regular classroom Please arrive 5 minutes

More information

Development of Online Banking System with High Level of Security using ASP.NET Technology and Microsoft SQL

Development of Online Banking System with High Level of Security using ASP.NET Technology and Microsoft SQL Available Online at www.ijcsmc.com International Journal of Computer Science and Mobile Computing A Monthly Journal of Computer Science and Information Technology ISSN 2320 088X IMPACT FACTOR: 5.258 IJCSMC,

More information

Assignment 6: SQL III Solution

Assignment 6: SQL III Solution Data Modelling and Databases Exercise dates: April 12/April 13, 2018 Ce Zhang, Gustavo Alonso Last update: April 16, 2018 Spring Semester 2018 Head TA: Ingo Müller Assignment 6: SQL III Solution This assignment

More information

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1 COSC344 Database Theory and Applications Lecture 5 SQL - Data Definition Language COSC344 Lecture 5 1 Overview Last Lecture Relational algebra This Lecture Relational algebra (continued) SQL - DDL CREATE

More information

SQL STRUCTURED QUERY LANGUAGE

SQL STRUCTURED QUERY LANGUAGE STRUCTURED QUERY LANGUAGE SQL Structured Query Language 4.1 Introduction Originally, SQL was called SEQUEL (for Structured English QUery Language) and implemented at IBM Research as the interface for an

More information

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210 SQL: Concepts Todd Bacastow IST 210: Organization of Data 2/17/2004 1 Design questions How many entities are there? What are the major entities? What are the attributes of each entity? Is there a unique

More information

1) Introduction to SQL

1) Introduction to SQL 1) Introduction to SQL a) Database language enables users to: i) Create the database and relation structure; ii) Perform insertion, modification and deletion of data from the relationship; and iii) Perform

More information

Lecture 6 - More SQL

Lecture 6 - More SQL CMSC 461, Database Management Systems Spring 2018 Lecture 6 - More SQL These slides are based on Database System Concepts book and slides, 6, and the 2009/2012 CMSC 461 slides by Dr. Kalpakis Dr. Jennifer

More information

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints SQL KEREM GURBEY WHAT IS SQL Database query language, which can also: Define structure of data Modify data Specify security constraints DATA DEFINITION Data-definition language (DDL) provides commands

More information

Test Bank for Database Processing Fundamentals Design and Implementation 13th Edition by Kroenke

Test Bank for Database Processing Fundamentals Design and Implementation 13th Edition by Kroenke Test Bank for Database Processing Fundamentals Design and Implementation 13th Edition by Kroenke Link full download: https://testbankservice.com/download/test-bank-fordatabase-processing-fundamentals-design-and-implementation-13th-edition-bykroenke

More information

Exact Numeric Data Types

Exact Numeric Data Types SQL Server Notes for FYP SQL data type is an attribute that specifies type of data of any object. Each column, variable and expression has related data type in SQL. You would use these data types while

More information

DATABASE DEVELOPMENT (H4)

DATABASE DEVELOPMENT (H4) IMIS HIGHER DIPLOMA QUALIFICATIONS DATABASE DEVELOPMENT (H4) Friday 3 rd June 2016 10:00hrs 13:00hrs DURATION: 3 HOURS Candidates should answer ALL the questions in Part A and THREE of the five questions

More information

UFCEKG 20 2 : Data, Schemas and Applications

UFCEKG 20 2 : Data, Schemas and Applications Lecture 11 UFCEKG 20 2 : Data, Schemas and Applications Lecture 11 Database Theory & Practice (5) : Introduction to the Structured Query Language (SQL) Origins & history Early 1970 s IBM develops Sequel

More information

EE221 Databases Practicals Manual

EE221 Databases Practicals Manual EE221 Databases Practicals Manual Lab 1 An Introduction to SQL Lab 2 Database Creation and Querying using SQL Assignment Data Analysis, Database Design, Implementation and Relation Normalisation School

More information

Chapter 1 Chapter-1

Chapter 1 Chapter-1 Chapter 1 Chapter-1 Data: Data are the raw facts that can be obtained after some experiments or observations. Raw data is of no use until and unless we process it to find some useful information form it.

More information

Lecture 3 SQL. Shuigeng Zhou. September 23, 2008 School of Computer Science Fudan University

Lecture 3 SQL. Shuigeng Zhou. September 23, 2008 School of Computer Science Fudan University Lecture 3 SQL Shuigeng Zhou September 23, 2008 School of Computer Science Fudan University Outline Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries Derived Relations Views

More information

Quick Facts about the course. CS 2550 / Spring 2006 Principles of Database Systems. Administrative. What is a Database Management System?

Quick Facts about the course. CS 2550 / Spring 2006 Principles of Database Systems. Administrative. What is a Database Management System? Quick Facts about the course CS 2550 / Spring 2006 Principles of Database Systems 01 Introduction Alexandros Labrinidis University of Pittsburgh When: Tue & Thu 2:30pm 3:45pm Where: 5313 SENSQ Instructor:

More information

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement Chapter 4 Basic SQL Basic SQL SQL language Considered one of the major reasons for the commercial success of relational databases SQL Structured Query Language Statements for data definitions, queries,

More information

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011 Introduction to SQL IT 5101 Introduction to Database Systems J.G. Zheng Fall 2011 Overview Using Structured Query Language (SQL) to get the data you want from relational databases Learning basic syntax

More information

Data about data is database Select correct option: True False Partially True None of the Above

Data about data is database Select correct option: True False Partially True None of the Above Within a table, each primary key value. is a minimal super key is always the first field in each table must be numeric must be unique Foreign Key is A field in a table that matches a key field in another

More information

What is MySQL? [Document provides the fundamental operations of PHP-MySQL connectivity]

What is MySQL? [Document provides the fundamental operations of PHP-MySQL connectivity] What is MySQL? [Document provides the fundamental operations of PHP-MySQL connectivity] MySQL is a database. A database defines a structure for storing information. In a database, there are tables. Just

More information

How to use SQL to create a database

How to use SQL to create a database Chapter 17 How to use SQL to create a database How to create a database CREATE DATABASE my_guitar_shop2; How to create a database only if it does not exist CREATE DATABASE IF NOT EXISTS my_guitar_shop2;

More information

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept] Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept] 1. What is DBMS? A Database Management System (DBMS) is a program that controls creation, maintenance and use

More information

DATABASE DEVELOPMENT (H4)

DATABASE DEVELOPMENT (H4) IMIS HIGHER DIPLOMA QUALIFICATIONS DATABASE DEVELOPMENT (H4) December 2017 10:00hrs 13:00hrs DURATION: 3 HOURS Candidates should answer ALL the questions in Part A and THREE of the five questions in Part

More information

DATABASE TECHNOLOGY - 1MB025

DATABASE TECHNOLOGY - 1MB025 1 DATABASE TECHNOLOGY - 1MB025 Fall 2005 An introductury course on database systems http://user.it.uu.se/~udbl/dbt-ht2005/ alt. http://www.it.uu.se/edu/course/homepage/dbastekn/ht05/ Kjell Orsborn Uppsala

More information

CMPT 354: Database System I. Lecture 3. SQL Basics

CMPT 354: Database System I. Lecture 3. SQL Basics CMPT 354: Database System I Lecture 3. SQL Basics 1 Announcements! About Piazza 97 enrolled (as of today) Posts are anonymous to classmates You should have started doing A1 Please come to office hours

More information

The Relational Model

The Relational Model The Relational Model What is the Relational Model Relations Domain Constraints SQL Integrity Constraints Translating an ER diagram to the Relational Model and SQL Views A relational database consists

More information

DATABASE MANAGEMENT SYSTEM COURSE CONTENT

DATABASE MANAGEMENT SYSTEM COURSE CONTENT 1 DATABASE MANAGEMENT SYSTEM COURSE CONTENT UNIT II DATABASE SYSTEM ARCHITECTURE 2 2.1 Schemas, Sub-schemas, and Instances 2.2 Three-level ANSI SPARC Database Architecture: Internal level, Conceptual Level,

More information

Basant Group of Institution

Basant Group of Institution Basant Group of Institution Visual Basic 6.0 Objective Question Q.1 In the relational modes, cardinality is termed as: (A) Number of tuples. (B) Number of attributes. (C) Number of tables. (D) Number of

More information

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved. Database Foundations 6-3 Roadmap You are here Introduction to Oracle Application Express Structured Query Language (SQL) Data Definition Language (DDL) Data Manipulation Language (DML) Transaction Control

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe CHAPTER 6 Basic SQL Slide 6-2 Chapter 6 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL INSERT, DELETE, and UPDATE Statements in SQL Additional Features

More information