Presentation is loading. Please wait.

Presentation is loading. Please wait.

Slide 1 of 77 Database, SQL, MySQL, CENG 449 Lecture 7.

Similar presentations


Presentation on theme: "Slide 1 of 77 Database, SQL, MySQL, CENG 449 Lecture 7."— Presentation transcript:

1 Slide 1 of 77 Database, SQL, MySQL, CENG 449 Lecture 7

2 Slide 2 of 77 SQL stands for "Structured Query Language", and is just a definition of a computer language that can be used to access data stored in relational databases. SQL is not itself a standalone computer application, but is rather part of many relational DB programs such as MySQL, Oracle, Sybase, Microsoft SQL Server, etc. MySQL is an actual computer application you can download and install. It is the most popular open-source database management system. In addition to having an SQL interpreter, MySQL also has a database manager component, GUI database viewers, session monitoring tools, etc. The difference between SQL and MySQL would be similar to the difference between C++ and the Visual C++ IDE; the first is just a language and the second is an actual tool that can be used to work in that language. Or similarly, the difference between HTML and Dreamweaver; HTML is just a web page standard, while Dreamweaver is a computer program that lets you create and edit and view web pages and web sites. CENG 449 Lecture 7

3 Slide 3 of 77 SQL (Structured Query Language) is a standard. No actual software follows that standard to the last letter. Every software vendor has their own version (or dialect) of SQL, which may both skip some standard SQL features and offer features not present in standard SQL. Microsoft has Transact-SQL (or T-SQL), Oracle has PL/SQL, MySQL has MySQL, etc. CENG 449 Lecture 7

4 Slide 4 of 77 "relational databases" and "database management" and all that is, they are just terms for one computer-efficient way to organize and retrieve _lots and lots_ of data that can be represented in a table. For example, a small mom-and-pop business may be able to keep their customer lists (with customer names, addresses, cities, zips, phone numbers, etc.) on paper, in a Word document table, or in an Excel spreadsheet and have that be manageable. However, if Amazon tried to do that with its millions (tens of millions, hundreds of millions?) of customers, paper would be unworkable and even Word and Excel keep their data in a structure that would take too long to look up a particular customer info. However, Amazon keeps their customer lists in a relational database, and the lookup would be amazingly fast, which is why your customized web page appears within seconds after you log in. CENG 449 Lecture 7

5 Slide 5 of 77 FeatureMySQL Series Unions4.0 Subqueries4.1 R-trees4.1 (for the MyISAM storage engine) Stored procedures and functions5.0 Views5.0 Cursors5.0 XA transactions5.0 Triggers5.0 and 5.1 Event scheduler5.1 Introduced in 2008 Partitioning5.1 Pluggable storage engine API5.1 Plugin API5.1 InnoDB Plugin5.1 Row-based replication5.1 Server log tables5.1 CENG 449 Lecture 7

6 Slide 6 of 77 What is Database? A database is a separate application that stores a collection of data. Each database has one or more distinct APIs for creating, accessing, managing, searching and replicating the data it holds. Other kinds of data stores can be used, such as files on the file system or large hash tables in memory but data fetching and writing would not be so fast and easy with those types of systems. So nowadays, we use relational database management systems (RDBMS) to store and manage huge volume of data. This is called relational database because all the data is stored into different tables and relations are established using primary keys or other keys known as foreign keys. A Relational DataBase Management System (RDBMS) is a software that: Enables you to implement a database with tables, columns and indexes. Guarantees the Referential Integrity between rows of various tables. Updates the indexes automatically. Interprets an SQL query and combines information from various tables. CENG 449 Lecture 7

7 Slide 7 of 77 RDBMS Terminology: Before we proceed to explain MySQL database system, let's revise few definitions related to database. Database: A database is a collection of tables, with related data. Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet. Column: One column (data element) contains data of one and the same kind, for example the column postcode. Row: A row (= tuple, entry or record) is a group of related data, for example the data of one subscription. Redundancy: Storing data twice, redundantly to make the system faster. Primary Key: A primary key is unique. A key value can not occur twice in one table. With a key, you can find at most one row. Foreign Key: A foreign key is the linking pin between two tables. Compound Key: A compound key (composite key) is a key that consists of multiple columns, because one column is not sufficiently unique. Index: An index in a database resembles an index at the back of a book. Referential Integrity: Referential Integrity makes sure that a foreign key value always points to an existing row. CENG 449 Lecture 7

8 Slide 8 of 77 MySQL Database: MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is developed, marketed, and supported by MySQL AB, which is a Swedish company. MySQL is becoming so popular because of many good reasons: MySQL is released under an open-source license. So you have nothing to pay to use it. MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages. MySQL uses a standard form of the well-known SQL data language. MySQL works on many operating systems and with many languages including PHP, PERL, C, C++, JAVA, etc. MySQL works very quickly and works well even with large data sets. MySQL is very friendly to PHP, the most appreciated language for web development. MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of 8 million terabytes (TB). MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL software to fit their own specific environments. CENG 449 Lecture 7

9 Slide 9 of 77 MySQL is a database management system. A database is a structured collection of data. It may be anything from a simple shopping list to a picture gallery or the vast amounts of information in a corporate network. To add, access, and process data stored in a computer database, you need a database management system such as MySQL Server. Since computers are very good at handling large amounts of data, database management systems play a central role in computing, as standalone utilities, or as parts of other applications. CENG 449 Lecture 7

10 Slide 10 of 77 MySQL databases are relational. A relational database stores data in separate tables rather than putting all the data in one big storeroom. The database structures are organized into physical files optimized for speed. The logical model, with objects such as databases, tables, views, rows, and columns, offers a flexible programming environment. You set up rules governing the relationships between different data fields, such as one-to-one, one-to-many, unique, required or optional, and “pointers” between different tables. The database enforces these rules, so that with a well-designed database, your application never sees inconsistent, duplicate, orphan, out-of- date, or missing data. CENG 449 Lecture 7

11 Slide 11 of 77 MySQL software is Open Source. Open Source means that it is possible for anyone to use and modify the software. Anybody can download the MySQL software from the Internet and use it without paying anything. If you wish, you may study the source code and change it to suit your needs. CENG 449 Lecture 7

12 Slide 12 of 77 The MySQL Database Server is very fast, reliable, scalable, and easy to use. If that is what you are looking for, you should give it a try. MySQL Server can run comfortably on a desktop or laptop, alongside your other applications, web servers, and so on, requiring little or no attention. If you dedicate an entire machine to MySQL, you can adjust the settings to take advantage of all the memory, CPU power, and I/O capacity available. MySQL can also scale up to clusters of machines, networked together. CENG 449 Lecture 7

13 Slide 13 of 77 The Main Features of MySQL Written in C and C++. Tested with a broad range of different compilers. Works on many different platforms. CENG 449 Lecture 7

14 Slide 14 of 77 History of MySQL MySQL is named after co-founder Monty Widenius's daughter, My. The name of the MySQL Dolphin (our logo) is “Sakila,” which was chosen from a huge list of names suggested by users in our “Name the Dolphin” contest. The winning name was submitted by Ambrose Twebaze, an Open Source software developer from Swaziland, Africa. According to Ambrose, the feminine name Sakila has its roots in SiSwati, the local language of Swaziland. Sakila is also the name of a town in Arusha, Tanzania, near Ambrose's country of origin, Uganda. CENG 449 Lecture 7

15 Slide 15 of 77 CENG 449 Lecture 7

16 Slide 16 of 77 Connecting to and Disconnecting from the Server To connect to the server, you will usually need to provide a MySQL user name when you invoke mysql and, most likely, a password. If the server runs on a machine other than the one where you log in, you will also need to specify a host name. Contact your administrator to find out what connection parameters you should use to connect (that is, what host, user name, and password to use). Once you know the proper parameters, you should be able to connect like as in the next slide CENG 449 Lecture 7

17 Slide 17 of 77 shell> mysql -h host -u user –p Enter password: ******** host and user represent the host name where your MySQL server is running and the user name of your MySQL account. Substitute appropriate values for your setup. The ******** represents your password; enter it when mysql displays the Enter password: prompt. mysql If that works, you should see some introductory information followed by a mysql> prompt: CENG 449 Lecture 7

18 Slide 18 of 77 shell> mysql -h host -u user –p Enter password: ******** Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 25338 to server version: 5.0.96-standard Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> The mysql> prompt tells you that mysql is ready for you to enter commands.mysql CENG 449 Lecture 7

19 Slide 19 of 77 After you have connected successfully, you can disconnect any time by typing QUIT (or \q) at the mysql> prompt: mysql> QUIT Bye On Unix, you can also disconnect by pressing Control+D. CENG 449 Lecture 7

20 Slide 20 of 77 Entering Queries Make sure that you are connected to the server, as discussed in the previous section. Doing so does not in itself select any database to work with, but that is okay. At this point, it is more important to find out a little about how to issue queries than to jump right in creating tables, loading data into them, and retrieving data from them. CENG 449 Lecture 7

21 Slide 21 of 77 Here is a simple command that asks the server to tell you its version number and the current date. Type it in as shown here following the mysql> prompt and press Enter: mysql> SELECT VERSION(), CURRENT_DATE; +----------------+------------------+ | VERSION() | CURRENT_DATE | +----------------+-----------------+ | 5.0.7-beta-Max | 2005-07-11 | +----------------+----------------+ 1 row in set (0.01 sec) mysql> CENG 449 Lecture 7

22 Slide 22 of 77 A command normally consists of an SQL statement followed by a semicolon. (There are some exceptions where a semicolon may be omitted. QUIT, mentioned earlier, is one of them. We'll get to others later.) When you issue a command, mysql sends it to the server for execution and displays the results, then prints another mysql> prompt to indicate that it is ready for another command. mysql displays query output in tabular form (rows and columns). CENG 449 Lecture 7

23 Slide 23 of 77 Keywords may be entered in any lettercase. The following queries are equivalent: mysql> SELECT VERSION(), CURRENT_DATE; mysql> select version(), current_date; mysql> SeLeCt vErSiOn(), current_DATE; CENG 449 Lecture 7

24 Slide 24 of 77 Here is another query. It demonstrates that you can use mysql as a simple calculator: mysql> SELECT SIN(PI()/4), (4+1)*5; +------------------+------------------+ | SIN(PI()/4) | (4+1)*5 | +------------------+-------------------+ | 0.70710678118655 | 25 | +------------------+-------------------+ 1 row in set (0.02 sec) CENG 449 Lecture 7

25 Slide 25 of 77 Creating and Using a Database Use the SHOW statement to find out what databases currently exist on the server: mysql> SHOW DATABASES; +--------------+ | Database | +--------------+ | mysql | | test | | tmp | +--------------+ If the test database exists, try to access it: mysql> USE test Database changed CENG 449 Lecture 7

26 Slide 26 of 77 Otherwise, you need to create it yourself: mysql> CREATE DATABASE menagerie; Creating a database does not select it for use; you must do that explicitly. To make menagerie the current database, use this command: mysql> USE menagerie Database changed CENG 449 Lecture 7

27 Slide 27 of 77 Creating the database is the easy part, but at this point it is empty, as SHOW TABLES tells you: mysql> SHOW TABLES; Empty set (0.00 sec) CENG 449 Lecture 7

28 Slide 28 of 77 CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry 1Alfreds Futterkiste Maria AndersObere Str. 57Berlin12209Germany 2Ana Trujillo Emparedados y helados Ana TrujilloAvda. de la Constitución 2222 México D.F.05021Mexico 3Antonio Moreno Taquería Antonio MorenoMataderos 2312 México D.F.05023Mexico 4Around the Horn Thomas Hardy120 Hanover Sq. LondonWA1 1DPUK 5Berglunds snabbköp Christina Berglund Berguvsvägen 8 LuleåS-958 22Sweden CENG 449 Lecture 7 Database Tables A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is a selection from the "Customers" table: The table above contains five records (one for each customer) and seven columns CustomerID, CustomerName, ContactName, Address, City, PostalCode, and Country).

29 Slide 29 of 77 Use a CREATE TABLE statement to specify the layout of your table: mysql> CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE); Once you have created a table, SHOW TABLES should produce some output: mysql> SHOW TABLES; +-----------------------------+ | Tables in menagerie | +-----------------------------+ | pet | +-----------------------------+ The created table is shown in the following slide CENG 449 Lecture 7

30 Slide 30 of 77 CENG 449 Lecture 7 nameownerspeciessexbirthdeath Table name is “pet”

31 Slide 31 of 77 To verify that your table was created the way you expected, use a DESCRIBE statement: mysql> DESCRIBE pet; +------------+----------------+-------+------+---------+-------+ | Field | Type | Null | Key | Default| Extra| +------------+----------------+-------+------+---------+-------+ | name | varchar(20) | YES | | NULL | | | owner | varchar(20) | YES | | NULL | | | species | varchar(20) | YES | | NULL | | | sex | char(1) | YES | | NULL | | | birth | date | YES | | NULL | | | death | date | YES | | NULL | | +------------+----------------+------+-------+----------+------+ CENG 449 Lecture 7

32 Slide 32 of 77 SQL PRIMARY KEY Constraint The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain unique values. A primary key column cannot contain NULL values. Most tables should have a primary key, and each table can have only ONE primary key. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (P_Id) ) CENG 449 Lecture 7

33 Slide 33 of 77 P_IdLastNameFirstNameAddressCity 1HansenOlaTimoteivn 10Sandnes 2SvendsonToveBorgvn 23Sandnes 3PettersenKariStorgt 20Stavanger O_IdOrderNoP_Id 1778953 2446783 3224562 4245621 CENG 449 Lecture 7 SQL FOREIGN KEY Constraint A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Let's illustrate the foreign key with an example. Look at the following two tables: The "Persons" table: The "Orders" table: Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "P_Id" 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. 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.

34 Slide 34 of 77 The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created: MySQL: CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) ) CENG 449 Lecture 7

35 Slide 35 of 77 You could add a new record using an INSERT statement like this: mysql> INSERT INTO pet VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL); String and date values are specified as quoted strings here. Also, with INSERT, you can insert NULL directly to represent a missing value. After the above command the table is seen as in the next slide CENG 449 Lecture 7

36 Slide 36 of 77 nameownerspeciessexbirthdeath FluffyHaroldcatf1993-02-04 CENG 449 Lecture 7 Assume that we repeat similar command and fill the table as follows

37 Slide 37 of 77 nameownerspeciessexbirthdeath FluffyHaroldcatf1993-02-04 ClawsGwencatm1994-03-17 BuffyHarolddogf1989-05-13 FangBennydogm1990-08-27 BowserDianedogm1979-08-311995-07-29 ChirpyGwenbirdf1998-09-11 WhistlerGwenbird 1997-12-09 SlimBennysnakem1996-04-29 CENG 449 Lecture 7

38 Slide 38 of 77 Retrieving Information from a Table The SELECT statement is used to pull information from a table. The general form of the statement is: SELECT what_to_select FROM which_table WHERE conditions_to_satisfy; what_to_select indicates what you want to see. This can be a list of columns, or * to indicate “all columns.” which_table indicates the table from which you want to retrieve data. The WHERE clause is optional. If it is present, conditions_to_satisfy specifies one or more conditions that rows must satisfy to qualify for retrieval. CENG 449 Lecture 7

39 Slide 39 of 77 CENG 449 Lecture 7 Selecting All Data The simplest form of SELECT retrieves everything from a table:

40 Slide 40 of 77 Selecting Particular Rows CENG 449 Lecture 7

41 Slide 41 of 77 You can specify conditions on any column, not just name. For example, if you want to know which animals were born during or after 1998, test the birth column: CENG 449 Lecture 7

42 Slide 42 of 77 You can combine conditions, for example, to locate female dogs: CENG 449 Lecture 7

43 Slide 43 of 77 The preceding query uses the AND logical operator. There is also an OR operator: CENG 449 Lecture 7

44 Slide 44 of 77 AND and OR may be intermixed, although AND has higher precedence than OR. If you use both operators, it is a good idea to use parentheses to indicate explicitly how conditions should be grouped: CENG 449 Lecture 7

45 Slide 45 of 77 Selecting Particular Columns If you do not want to see entire rows from your table, just name the columns in which you are interested, separated by commas. For example, if you want to know when your animals were born, select the name and birth columns: CENG 449 Lecture 7

46 Slide 46 of 77 To find out who owns pets, use this query: CENG 449 Lecture 7

47 Slide 47 of 77 Notice that the query simply retrieves the owner column from each record, and some of them appear more than once. To minimize the output, retrieve each unique output record just once by adding the keyword DISTINCT: CENG 449 Lecture 7

48 Slide 48 of 77 You can use a WHERE clause to combine row selection with column selection. For example, to get birth dates for dogs and cats only, use this query: CENG 449 Lecture 7

49 Slide 49 of 77 Sorting Rows You may have noticed in the preceding examples that the result rows are displayed in no particular order. It is often easier to examine query output when the rows are sorted in some meaningful way. To sort a result, use an ORDER BY clause. Here are animal birthdays, sorted by date: CENG 449 Lecture 7

50 Slide 50 of 77 The default sort order is ascending, with smallest values first. To sort in reverse (descending) order, add the DESC keyword to the name of the column you are sorting by: CENG 449 Lecture 7

51 Slide 51 of 77 You can sort on multiple columns, and you can sort different columns in different directions. For example, to sort by type of animal in ascending order, then by birth date within animal type in descending order (youngest animals first), use the following query: CENG 449 Lecture 7

52 Slide 52 of 77 Pattern Matching To find names beginning with “b”: CENG 449 Lecture 7

53 Slide 53 of 77 To find names ending with “fy”: CENG 449 Lecture 7

54 Slide 54 of 77 To find names containing a “w”: CENG 449 Lecture 7

55 Slide 55 of 77 To find names containing exactly five characters, use five instances of the “_” pattern character: CENG 449 Lecture 7

56 Slide 56 of 77 To find names beginning with “b”, use “^” to match the beginning of the name: CENG 449 Lecture 7

57 Slide 57 of 77 To find names ending with “fy”, use “$” to match the end of the name: CENG 449 Lecture 7

58 Slide 58 of 77 To find names containing a “w”, use this query: CENG 449 Lecture 7

59 Slide 59 of 77 Counting Rows Databases are often used to answer the question, “How often does a certain type of data occur in a table?” For example, you might want to know how many pets you have, or how many pets each owner has, or you might want to perform various kinds of census operations on your animals. Counting the total number of animals you have is the same question as “How many rows are in the pet table?” because there is one record per pet. COUNT(*) counts the number of rows, so the query to count your animals looks like this: CENG 449 Lecture 7

60 Slide 60 of 77 Earlier, you retrieved the names of the people who owned pets. You can use COUNT() if you want to find out how many pets each owner has: CENG 449 Lecture 7

61 Slide 61 of 77 Number of animals per species: CENG 449 Lecture 7

62 Slide 62 of 77 Number of animals per sex: CENG 449 Lecture 7

63 Slide 63 of 77 Number of animals per combination of species and sex: CENG 449 Lecture 7

64 Slide 64 of 77 You need not retrieve an entire table when you use COUNT(). For example, the previous query, when performed just on dogs and cats, looks like this: CENG 449 Lecture 7

65 Slide 65 of 77 Some more SQL commands will be studies for the following table CENG 449 Lecture 7 CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry 1Alfreds Futterkiste Maria AndersObere Str. 57Berlin12209Germany 2Ana Trujillo Emparedados y helados Ana TrujilloAvda. de la Constitución 2222 México D.F.05021Mexico 3Antonio Moreno Taquería Antonio MorenoMataderos 2312 México D.F.05023Mexico 4Around the Horn Thomas Hardy120 Hanover Sq. LondonWA1 1DPUK 5Berglunds snabbköp Christina Berglund Berguvsvägen 8 LuleåS-958 22Sweden

66 Slide 66 of 77 The SQL UPDATE Statement: The UPDATE statement is used to update existing records in a table. SQL UPDATE Syntax: UPDATE table_name SET column1=value1,column2=value2, WHERE some_column=some_value; Example: UPDATE Customers SET ContactName='Alfred Schmidt', City='Hamburg‘ WHERE CustomerName='Alfreds Futterkiste'; CENG 449 Lecture 7

67 Slide 67 of 77 SQL DELETE Statement The DELETE statement is used to delete records in a table. SQL DELETE Syntax DELETE FROM table_name WHERE some_column=some_value; Example: DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria Anders'; CENG 449 Lecture 7

68 Slide 68 of 77 SQL DROP INDEX, DROP TABLE, and DROP DATABASE Indexes, tables, and databases can easily be deleted/removed with the DROP statement. DROP TABLE table_name CENG 449 Lecture 7

69 Slide 69 of 77 SQL DROP INDEX, DROP TABLE, and DROP DATABASE Indexes, tables, and databases can easily be deleted/removed with the DROP statement. DROP TABLE table_name DROP DATABASE database_name What if we only want to delete the data inside the table, and not the table itself? Then, use the TRUNCATE TABLE statement: TRUNCATE TABLE table_name CENG 449 Lecture 7

70 Slide 70 of 77 The ALTER TABLE Statement The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. To add a column in a table, use the following syntax: ALTER TABLE table_name ADD column_name datatype To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column): ALTER TABLE table_name DROP COLUMN column_name CENG 449 Lecture 7

71 Slide 71 of 77 EXAMPLES: Now we want to add a column named "DateOfBirth" in the "Persons" table. We use the following SQL statement: ALTER TABLE Persons ADD DateOfBirth date Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table. We use the following SQL statement: ALTER TABLE Persons ALTER COLUMN DateOfBirth year Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- digit or four-digit format. Next, we want to delete the column named "DateOfBirth" in the "Persons" table. We use the following SQL statement: ALTER TABLE Persons DROP COLUMN DateOfBirth CENG 449 Lecture 7

72 Slide 72 of 77 AUTO INCREMENT a Field Very often we would like the value of the primary key field to be created automatically every time a new record is inserted. We would like to create an auto-increment field in a table. CREATE TABLE Persons ( ID int NOT NULL AUTO_INCREMENT, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (ID) ) CENG 449 Lecture 7

73 Slide 73 of 77 MySQL Data Types In MySQL there are three main types : text, number, and Date/Time types. Text types: CENG 449 Lecture 7

74 Slide 74 of 77 Data typeDescription 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 TINYTEXTHolds a string with a maximum length of 255 characters TEXTHolds a string with a maximum length of 65,535 characters BLOBFor BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data MEDIUMTEXTHolds a string with a maximum length of 16,777,215 characters MEDIUMBLOBFor BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data LONGTEXTHolds a string with a maximum length of 4,294,967,295 characters LONGBLOBFor 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 65535 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. You enter the possible values in this format: ENUM('X','Y','Z') SETSimilar to ENUM except that SET may contain up to 64 list items and can store more than one choice CENG 449 Lecture 7

75 Slide 75 of 77 Data typeDescription TINYINT(size)-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis SMALLINT(size)-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesis MEDIUMINT(size)-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis INT(size)-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis BIGINT(size)-9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 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 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 CENG 449 Lecture 7 Number types:

76 Slide 76 of 77 SQL Functions SQL Aggregate Functions SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions: AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum SQL Scalar functions SQL scalar functions return a single value, based on the input value. Useful scalar functions: UCASE() - Converts a field to upper case LCASE() - Converts a field to lower case MID() - Extract characters from a text field LEN() - Returns the length of a text field ROUND() - Rounds a numeric field to the number of decimals specified NOW() - Returns the current system date and time FORMAT() - Formats how a field is to be displayed CENG 449 Lecture 7

77 Slide 77 of 77 The AVG() Function The AVG() function returns the average value of a numeric column. SQL AVG() Syntax SELECT AVG(column_name) FROM table_name SELECT AVG(daily_typing_pages) FROM employee_tbl; CENG 449 Lecture 7


Download ppt "Slide 1 of 77 Database, SQL, MySQL, CENG 449 Lecture 7."

Similar presentations


Ads by Google