This action might not be possible to undo. Are you sure you want to continue?
SQL stands for Structured Query Language and is a very powerful and diverse language used to create and query databases. Its loose syntax makes it easy to learn but mastering its intricate architecture may take a lifetime. Advertise on Tizag.com SQL is the language used to interact with data and databases. Armed with a firm understanding of its structure and mechanics will allow you to build simple, dynamic applications for the web or create robust applications for your preferred operating system. The loose structure and flexibility of this language make it an ideal candidate for the web, especially since there are more than a handful of database applications available for free such as MySQL and SQL Server Express.
SQL - Fundamentals
SQL alone can input, modify, and drop data from databases. In this tutorial we use command line examples to show you just a sample of what SQL is capable of. With the use of web languages such as HTML and PHP, SQL becomes an even greater tool for building dynamic web pages.
SQL - World Wide Web
SQL has become a popular among web designers due to its flexibility and simplicity. With some basic knowledge of HTML, PHP, and a database program such as MySQL, a web designer is capable of creating some of the most complex of web sites and applications and most of your online web services are run using a SQL backend to store user data. This tutorial will provide you with just a small taste of this type of programming and architecture. Building a web site on SQL architecture is quickly becoming the standard among web 2.0 sites. With a SQL backend it is fairly simple to store user data or email lists. SQL is an absolute must for any e-commerce web site where orders are processed and money is exchanged.
SQL - Tutorial Scope
Reading further you will encounter a number of hands on examples intended to introduce you to SQL. The majority of these examples are intended to span across the different available variations of SQL but the primary focus of this tutorial is aimed at Microsoft's SQL Server 2000 and later.
SQL - Getting Started
To get started you will need to install database program SQL Server, MySQL, Oracle, or IBM's DB2. For installation help, we suggest you go straight to the developer homepages: Oracle SQL Server MySQL It is preferred that you select SQL Server Express 200X, at least for the duration of this tutorial. The express addition is available for private use for free and you can find the download page by searching for "SQL Server Express" with Google. Follow the on-line installation guide that Microsoft provides and once you have that application installed you are ready to for the rest of our tutorial.
SQL - What's a Database?
A database is nothing more than an empty shell, like a vacant warehouse. It offers no real functionality what so ever, other than holding a name. Tables are the next tier of our tree offering a wide scope of functionality. If you follow our warehouse example, a SQL table would be the physical shelving inside our vacant warehouse. Each SQL table is capable of housing 1024 columns(shelves). Depending on the situation, your goods may require reorganization, reshelving, or removal. SQL tables can be manipulated in this same way or in any fashion the situation calls for. Advertise on Tizag.com
SQL - Four Principles of Database Design
When designing and implementing a database, keep in mind these four guidelines. Atomicity Your coded statements flow without the constant need to update or "fix" your data. Consistency Your statements are either executed 100% or fail 100%, do not implement code that partially works. Isolation Keep data files and logs away from public eyes, and limit the number of users with administration access to your database. Durability Maintain reliable servers with plenty of storage space and back-up systems that save
transactions immediately. A well thought out database will continue to serve and meet your needs for ages. It is important to plan ahead and really put some thought into what you intend to record in your databases. Keep in mind that tables and databases should maintain some relationship. In many instances it is far more desirable to have several small related tables and databases than one giant one. "Never place your eggs all in one basket."
The Database Model
Dr. Edgar F. Codd was the founding father of what is known as the relational model of databases. In 1970, he published a groundbreaking article "A Relational Model of Data for Large Shared Data Banks." Included within the article were 12 rules of relational databases. These rules are as follows (paraphrased). Information Rule All data in the database should be represented as values in tables. Guaranteed Access Every piece of data should be accesible by using the table name, primary key, and a column name. Treatment of NULL Values Null values must be treated as incomplete data pieces. Nulls are not to be confused with zeros. Active-Online Relational Catalog A database is represented at a logical level of tables. Sublanguage Having one supported language with a well-defined syntax. Updating Views All views should be updated through the system. Set-level Insertion, Update, and Deletion System must support set-time insert, update, and deletion operations. Data Independence (Physical) Alterations to the way data is stored must not alter the application itself. Data Independence (Logical) Altering tables, columns, and/or rows must not alter the application itself. Integrity Independence The language of the database must define integrity rules. Distribution Independence Distributing the database to numerous locations should be anonymous and
existing applications should be unaffected. Nonsubversion If the system uses a low level interface to record data, then there must be a higher level interface used when administrating. The largest of corporations follow these rules of cataloging information to this very day.
Database Driven Web Sites
Today we experience the power of databases throughout the web. Many sites are completely dynamic, meaning the content that is being display is held inside of a table with columns, and columns of information to display. This is quickly becoming the ideal way to host websites. It allows for dynamic content on the fly, user interaction, and webmasters can store information about returning users making way for the site to recognize returning users. Any chance at building rapport with your audience is a great opportunity indeed.
SQL - Platforms
A SQL platform acts as the stage for building and developing your databases. Several different platforms exist including: Advertise on Tizag.com • • • • • IBM's DB2 MySQL PostgreSQL Oracle Microsoft's SQL Server
SQL - MySQL and PostgreSQL
MySQL and PostgreSQL are open source database programs rich in functionality and flexibility. They are often the choice of web developers and small businesses simply because they get the job done for a very reasonable price. Also they will go anywhere and can operate on nearly every operating system available.
UPDATE.com SQL Code: SELECT getdate(). SQL Results: 2008-08-09 11:56:05. These systems run on personal computers as well as large corporate mainframes. Even though you may not know exactly what is happening here or when this may be useful. SQL . Each query statement begins with a clause such as SELECT. this statement begins with the SELECT clause and the built in function getdate() does all the work for you.SQL Server Microsoft's SQL Server is steadily on the rise in the commercial world gaining popularity slowly.DB2 and Oracle By far the selection of choice for large corporations is either Oracle or DB2. or selecting data rows that meet specific criteria. It is a query that uses a built in SQL function called getdate() that will return the current server date.SQL .407 As you can see. This platform has a GUI "Windows" type interface and is also rich with functionality. By executing this query you are essentially telling your database to "go and fetch" the current date. updating data inside a table. CREATE. SQL .Queries SQL uses commands called queries to execute tasks such as creating a databases (which we've seen already). or DELETE and the simplest query is only two words long. A free trial version can be downloaded at the Microsoft web site. Execute the following statement to have SQL go and fetch the current SQL server date and time: Advertise on Tizag. Companies that have large ties to IBM stick to their DB2 software whereas others have made the switch to Oracle. however it is only available to Windows users. This particular query is probably as simple and straight forward as it gets in the SQL world. you have taken the first step toward understanding the fundamental mechanics of SQL query statements and the very foundation on which SQL architecture resides. .
For now just take note that we are creating a new table to store data and this table has only 5 essential table columns . orders (CREATE TABLE orders).Query Structure Queries are loosely typed into your SQL prompt. We now know that a query begins with a clause. SQL Create Table Query: USE mydatabase. quantity) VALUES('Tizag'. The blank line after is not required but it makes our query much more legible and the line following the page break starting with the CREATE clause is where we are actually going to tell SQL to create our new table and give this table a name. This is a list and each new table column is separated by a comma (.product. this line defines the scope of the query and directs SQL to run the following command against the mydatabase database as appose to some other database that exists inside our SQL application. product VARCHAR(50).'Sharpie'. INSERT INTO orders (customer. The next query is going to add data to our table by inserting values into each table column. what comes next depends on the clause. Spacing and line breaks are not very important as excess line breaks and spacing are ignored by the SQL application. The first line of our example "use mydatabase. SQL Insert Query: use mydatabase.'8/1/08'. quantity int ).4). customer VARCHAR(50). CREATE TABLE orders ( id INT IDENTITY(1." is pretty straight forward.day_of_order. we must specify which database we intend on executing a query against . day_of_order DATETIME. It isn't important to understand many of the other details they will be explained later on in different lessons.SQL . Again. In order to expand our understanding of queries we will need to create a table and populate this table with some data which we can then manipulate as we introduce more Query commands and SQL functions.1) PRIMARY KEY. The next couple of examples should be overwhelming to newer SQL programmers but we will still take a moment to explain what's going on and focus on the structure of each query. The lines contained in parenthesis() are telling SQL how to set up the columns. Listed above is a typical INSERT query used to insert data into the table we previously created.).
SQL Code: SELECT * FROM table_name. SQL . a good habit is to capitalize your clauses. The advantage of this isn't apparent with this example. there are not many quotations or other symbols to throw into your statements. More on this in a moment. meaning first we decide what we want to do. All queries start with a clause. Advertise on Tizag. Clauses are commands in the SQL world and the backbone of any script. all three queries we have run in this lesson are very similar. we have to list the columns we intend to insert data into and the final line lists the actual values that will be inserted into each of the table columns.(use mydatabase . Generally we follow a Do what To what syntax.insert data). and finally we end the whole thing with a semicolon (.Syntax SQL follows a general syntax. Each are fairly easy to read. The common formatting technique is to begin each line with a clause or to break up and list columns or tables as needed. We will look at each of these clauses a little more in depth on the next few pages but it may be obvious to you already what each of those clauses does.Query Structure Review Structurally. The first clause of a statement gives a general idea of what type of action a script is taking.Line 1). INSERT. Formating your statements in a similar fashion will also aid your debugging efforts. or CREATE. A few basic clauses are SELECT. Above we have a SELECT clause asking for all columns and values (*) from our database table.). SQL . then we decide what we want to do it to. A basic statement might look like this: SQL Code: SELECT * FROM table_name. telling SQL how to handle the query and then the remaining lines describe in detail how we want SQL to go about performing our task. Finally. Later on when we have larger statements and subqueries it will make life much easier to go back and debug your code. As shown above. SQL statements end with a semicolon as most with most programming languages. And then we tell SQL what we want to do (INSERT INTO orders. .com A statement begins with a clause.
id'). column_two FROM table_name WHERE ( column_one.id = 'table_two. column_two.com • • • • Character Strings . When the table is created you may either allow a table to have a null value or may disallow null values for each table column. Both statements are neither right nor wrong. column_three.(True / False) Nulls . Quotations are not found until the predicate of the statement. ) = (SELECT column_one.Data Types SQL recognizes 4 general types of data. Advertise on Tizag.However the example below shows an example where this format shines. A one line statement will not fit across your screen. -17) Booleans . each are easier to follow.423. SQL . As you can see.(empty fields) SQL .(3. . 3.('Words or numbers') Numbers . Parentheses generally depict order of operations but it is not an exact science.NULL Values A null value may be the most foreign to new programmers. SQL Code: SELECT column_one. Stating that a value has a null value indicates that nothing exists in that table field. when subqueries are thrown into the mix things become a little more complicated. column_two FROM table_two WHERE table_one. Before we look at each type of table column we will elaborate on specific data types and how they are handled in SQL. As the database designer you will be selecting which type of data that can be placed in each table column.
integers.66 28. The advantage of working with numbers is that SQL has built in functions such as the AVG() or SUM() functions that will return the average or the sum of a numeric column. SQL . Character Strings: employee_id TS_0036 . Either something is or something is not.Numeric Data Dates. and money are all numeric data types. Boolean Values: admin 1 1 0 SQL .Boolean Data Boolean values are either yes/no (true/false) types of data. Math functions can not be performed with character strings.Character Strings Character strings are sentences. total_hours INT NULL. symbols. or a combination of both.SQL Code: CREATE TABLE weekly_payroll (employee_id VARCHAR(10) PRIMARY KEY. hourly_rate MONEY NOT NULL.40 SQL . Others use a 1/0 (1 for yes 0 for no) approach. Numbers: rate_of_pay 27 26.). time stamps.
What is a Function There are a number of functions built into SQL that can add column values for you.TS_0078 CL_1099 SQL . SELECT.What is a Clause Clauses were mentioned briefly in the SQL Queries lesson. SQL . We will be covering this function as well as many others as this tutorial continues. Each type of command plays an essential role while working with your database. The query above will return a numeric value representing the number of rows that have been inserted into your database. Equality. they are the commands issued during a query. To briefly recap. INSERT. DROP. and Logical. SQL Code: Count() function SELECT COUNT(*) FROM table_one.Commands SQL commands can be categorized into three distinct groups. They come in four flavors including: Arithmatic. average column values. you may want the language to start performing some basic . Certain duties require specific tools and the more tools you have in your shed. These functions are used directly inside of your queries and are excellent tools for you to use. Range. SQL . Advertise on Tizag.com SQL . One analogy might be to think of each SQL Command as a possible tool in your tool shed.What is an Operator Operators are a means by which SQL can manipulate numbers and strings or test for equality. or even change lowercase to uppercase strings. the greater the chances that you will have the exact tool you need for the appropriate job. CREATE. As your skills with SQL grow. etc are all clauses that begin each SQL Query and execute some sort of action upon your database. ADD.
There are two logical operators. Advertise on Tizag.com Operators come in three flavors. This becomes possible with operators. multiply. inequality. or a combination of both. this term describes the result when one number is divided by another number resulting in a remainder. logical. or range operations. AND / OR. Take note of the following tables for future reference. mathematical. Mathematical operators add. divide. For example 4 % 3 would result with a value of 1 since 1 is left over after 4 is divided by 3. SQL Code: SELECT * FROM table_one WHERE column_one > 5. Range operators include the infamous < and > symbols used to compare equality.arithmatic for you or perhaps you wish to select a range of rows with a numeric column value larger than 5. SQL Range Operators: Operator < Example 7<4 Defined 7 less than 4? Result False . they show equality. subtract.Operators Operators are used in expressions or conditional statements. SQL . SQL operators follow the same rules you may have learned in a math class or know from previous programming experience. Mathematical operators are found in every computer language and may be familiar to you. SQL Arithmetic Operators: Operator + * / % Example 7+7 7-7 7*7 7/7 7%7 Result = 14 =0 = 49 =1 =0 Definition Addition Subtraction Multiplication Division Modulus Modulus may be the only unfamiliar term on the chart. and compare equality of numbers and strings.
Expressions after the where clause might appear more familiar to programmers. . if (($x OR $y) == 5).. The simplest form of an expression appears as column_one of our table.Expression Types Expressions in SQL generally fall into one of four categories including: Boolean. Advertise on Tizag..> <= >= 7>4 7 <= 11 7 >= 11 greater than 4? Is 7 less than or equal to 11? Is 7 greater than or equal to 11? True True False SQL Equality Operators: Operator = <> Example 5=5 7 <> 2 Defined Is 5 equal to 5? Is 7 not equal to 2? Result True True SQL Logical Operators: Operator AND OR Defined Associates two values using AND Associates two values using OR Example if (($x AND $y) == 5).. SQL Code: SELECT column_one FROM table_name. Character.Expressions In the programming world an expression is a special statement that returns a value. and/or Date Expressions.com SQL . SQL .. Numeric. and column_one acts as the defined expression returning each row of that particular column. Select is our clause telling our database what we want to do. SQL is no exception to this standard rule.
Returns a count of the number of rows of a given column. SQL Code: SELECT * FROM table_name WHERE column_one = 'some value'.Returns the sum of a given column.Character Expressions Character expressions are used to test for values of a string. There are some built in functions that we will be examining in greater detail later on. SQL Code: SELECT COUNT(*) FROM table_name. SUM() -. and SUM() only return results for integer table columns.Returns the average of a stated column. More information on the where clause is available at SQL Where. Using one of the following functions is perhaps the easiest way to demonstrate the return of a number: • • • AVG() -. SQL . Returning to the previous example containing the where clause. Please be aware that the AVG().SQL Code: SELECT * FROM table_name WHERE column_one = 'some value'. Each time a match is found (testing true).Numeric Expression A numeric expression simply returns a numeric value. SQL . that row is selected and returned for our viewing pleasure. COUNT(). The latter example returns rows of the specified column containing 'some value'. COUNT() -. Often these expressions will appear in a where clause as follows. Using one of these functions with a varchar column will result in an error message. SQL .Boolean Expressions A boolean expression in any programming language returns a true/false result. Using expressions like the one above gives you precise control over what results will be returned. SQL Code: SELECT * FROM table_name WHERE . The logic behind this query is that each row is being tested for 'some value' to appear in our column_one. Our expression above returns a numeric value representing the number of rows that have been inserted into your table thus far.
simply type in any of those listed below and SQL will return exactly what you have requested. We will be looking more indepth at the insert clause. Keep in mind that SQL is case sensitive. we should have something like the following. SQL . .Current_Timestamp). These expressions are very straight forward.Returns the current date.column_one LIKE '%string'. Here we have used the percent(%) symbol to signify the start of our string.Date Expressions Date expressions come in three flavors. SQL Code: INSERT INTO table_name(column_one. SQL tests our expression against column_one and returns all the rows and columns where column_one contains our string. Current_Timestamp -. These expressions can also be placed into your tables as column values for any given row with an insert statement. In this table we have set up a column a last_name column. Say we have created a table with employee information.Returns the current timestamp. Now if we plug in our hypothetical situation into our code.column_two. Current_Time -.Returns the current time. This might come across easier if we use a live example.) Values(Current_Date. The query above will come in handy if we were wanting to pull all the employees with a last_name that begins with a "T". however here is a glimpse of what is to come. • • • Current_Date -. using a lowercase t would not yield results for a last_name that has been capitalized. SQL Code: SELECT * FROM employees WHERE last_name LIKE '%T'. This statement inserts a new row into our imaginary table with the current date value for column one and the current timestamp value for columne_two.
you must use the underscore (_). reshelving. SQL programs are case sensitive. next we create our tables to store and organize our data. character. We will be using this database for the remainder of the tutorial. or brief strings. or removal. The create clause is straight forward. Depending on the situation.Create Database We first need to build our warehouse. Column types specify what type of data can be placed inside a table column ranging from numbers. For example. Here we have a one line script using the create clause to create a database we named business. We use the same create clause and follow the same syntax above. It offers no real functionality what so ever. Naming your table columns can be as simple or complicated as desired. The exact number of databases a SQL program can handles is entirely up to the manufacturer. keep this in mind as you will be calling on our table columns by name a great deal as you enhance your SQL knowledge. setting a column type to an int value means your database will ONLY accept an integer value for this column type. SQL tables can be manipulated in this same way or in any fashion the situation calls for. visit your sites manufacturer if you would like to have specifics. SQL . Tables. Tables are the next tier of our tree offering a wide scope of functionality. Column Types: Column Type int varchar Description Accepts integer values only Accepts any symbol. If you follow our warehouse example. like a vacant warehouse. are fairly complex. In our script we must also include parameters for each table column as well as name each one. int varchar(char limit value) . your goods may require reorganization. Advertise on Tizag. Also. other than holding a name.Create Table Our empty shell of a database will do nothing standing alone. paragraphs. however. or create our database.com SQL . most programs do not support spaces in column names. or number Syntax tinyint. SQL Code: CREATE DATABASE business.Create A database is nothing more than an empty shell.SQL . a SQL table would be the physical shelving inside our vacant warehouse.
which is perfect for short names of people. digits. We recommend reading up on each column type available to you from your database manufacturer. medium. Firstname VARCHAR(25). or symbols. and large. Using the correct size field will dramatically increase performance including query speeds. ADD PRIMARY KEY ('id'). SQL . Later on as you expand the database it will become extremely important not to overdue the size of your column fields. The last column has a specified default value of "crew" so that if we add a new crew member we can simply place a default value. For each record in the table the primary key acts like a driver's license number. SQL Code: ALTER TABLE 'employees' DROP PRIMARY KEY. varchar. Any table can only be given one auto increment field and as such it is forced to be the primary key of the table. SQL Code: CREATE TABLE employees ( id INT IDENTITY PRIMARY KEY NOT NULL. and text are the 3 most common types of columns. The same principle applys here. Therefore in our following examples we use the 'id' field as our primary key. blob Int. only one number exists for each person. most table columns will allow null values to be recorded but certain table columns will not allow a null value to be inserted. More about the alter clause later. By default.Primary Key A primary key is a property given to a table column that distinguishes that record apart from each. but for this tutorial we will be using medium sized column fields for each exercise. then add your desired primary as shown below. Our second line is a varchar meaning it will hold numbers. . Now create the table. generally this is a great way to automatically assign a unique id to a record. Title VARCHAR(10) DEFAULT 'crew' NULL ). Text and int columns have 3 flavors tiny. Every SQL program has its unique sizes. We do not always have to specify a default value or state weather each column may have a NULL value.text/blob lots of text including line breaks text. Above is our table. the first column is an int column set to automatically count each row. The alter clause is used to add or drop primary keys and indexes. To change a primary key you must drop the first one. Lastname VARCHAR(50).
SQL .SQL . The downside to indexing is that it enlarges the disk space consumed by a table on your web server. or ALTER TABLE `employees` DROP INDEX `Lastname`. it will pinpoint your index columns and search those first. Do we plan on inserting numbers? Strings? Files? Returning to the orders table we created in an earlier lesson. By adding an index to columns. The "Quantity" column for example. You may recall a few of the table columns that were created: • • • • • id customer day_of_order product quantity Looking at the column names alone you gain a sense of what type of data is expected by each column. is expecting a number of some sort .Insert SQL tables store data in rows. SQL Code: ALTER TABLE 'employees' ADD INDEX ('id').Indexes SQL automatically creates some indexes based on column types and attributes. Use indexes when you notice a drop in your query speeds. An index can also be given to a table column to optimize speeds. The INSERT command is the command used to insert new data (a new row) into a table by specifying a list of values to be inserted.com To use the INSERT command we must have an understanding of where we would like to insert data and what types of data we want to insert. SQL will start at the top of the table and search each and every record until it finds matches. Advertise on Tizag. one row after another. SQL will no longer search the entire table. Values are specified in the query statement and must be arranged inside the code according to the order of the table columns. This becomes a performance issue when a table holds a vast amount of records. When a query is executed searching for a specific column value.
day_of_order.000 2008-08-01 00:00:00. SQL Results: id customer 1 2 Tizag Tizag day_of_order 2008-08-01 00:00:00. SQL Insert Query: use mydatabase. The reason behind this is that when we created the table. you may omit the table columns entirely and only supply the values in the INSERT statement: SQL Insert Query: use mydatabase.Inserting Values As a shortcut.1).'Stapler'. Now when we run the SELECT (*) query. SQL should return two rows with our statement instead of only a single row. we created this column field to carry a special attribute called identity. the first value "Tizag" corresponds with the customer table column and this ensures SQL will insert the correct data into the correct. Again. With our new found understanding of what is to be expected in each table column it doesn't take much to effort to create an INSERT statement to add new row values to our table.product. corresponding table column.12).000 product Sharpie Stapler quantity 4 1 SQL .'Hanging Files'.'8/16/08'. SELECT * FROM orders. we can skip the id column because it is an IDENTITY column and SQL handles . Verification Query: use mydatabase. INSERT INTO orders VALUES('A+Maintenance'.'8/1/08'. quantity) VALUES('Tizag'. Therefore. SQL handles identity columns automatically for us (we'll talk more on this later). INSERT INTO orders (customer.(integer) and the "day_of_order" column is looking for a date value. You may notice that the id column has been left out of the query statement.
000 2008-08-01 00:00:00.'19" LCD Screen'.'HP Printer'.'7/25/08'.000 2008-08-01 00:00:00. let's add some more rows by running the following insert queries. If you are using SQL Express.'19" LCD Screen'.000 2008-07-25 00:00:00.2).3) INSERT INTO orders VALUES('Tizag'. you should be able to copy the entire code section below and execute all the queries at once and track the results.000 2008-08-16 00:00:00.000 2008-07-25 00:00:00.000 product Sharpie Stapler Hanging Files quantity 4 1 12 Before moving on.000 2008-08-16 00:00:00. SQL Insert Queries: use myDatabase.000 product Sharpie Stapler Hanging Files 19" LCD Screen 19" LCD Screen HP Printer quantity 4 1 12 3 3 2 . INSERT INTO orders VALUES('Gerald Garner'. SELECT * FROM orders Final Results: id customer 1 Tizag 2 Tizag 3 A+Maintenance 4 Gerald Garner 5 Tizag 6 Tizag day_of_order 2008-08-01 00:00:00.000 2008-08-15 00:00:00. SQL Results: id customer 1 Tizag 2 Tizag 3 A+Maintenance day_of_order 2008-08-01 00:00:00. INSERT INTO orders VALUES('Tizag'.'8/15/08'.3).'7/25/08'.inserts into these column types automatically.
SQL . SQL Select Query: SELECT table_column1. the first part is the "WHAT" which determines what we want SQL to go and fetch. SELECT query statements are easily identifiable because each one begins with the "SELECT" clause. Execute the following query against the orders table and retrieve the data we previously inserted. Earlier we saw a select statement that went and fetched the current date for us and because we used a SQL built in function to determine "WHAT" we wanted to select. Take a look at the results this query yields: SQL Select Query: . Advertise on Tizag. we just need to tell SQL what we want to select and from where to select the data. SQL Select Query: use mydatabase. How do we translate this request into SQL code so that the database application does all the work for us? Simple. quantity FROM orders. Line one tells SQL what it is we're looking for by listing each column we would like to retrieve. Let's apply this template to our orders table. SQL automatically filled in the second part of our SELECT query.com Select queries require two essential parts.Select SQL SELECT may be the most commonly used command by any SQL programmer as it is used to pull data from a database and present the data in a user-friendly table. the "FROM WHERE. customer. table_column2. Line 2 on the other hand tells SQL where to go and look for those columns. day_of_order. SELECT id." Now we would like SQL to go and fetch table column data for us from the orders table that we created earlier. SQL Orders Table Results: id customer 1 Tizag day_of_order 2008-08-01 00:00:00.000 product Sharpie quantity 4 We may also manipulate the result output by rearranging the table column list inside of the SELECT statement. table_column3 FROM my_table. product.
product. Use the (*) instead of listing each table column by name and SQL will return all columns that exist inside the specified table. SQL . The results should speak for themselves. SQL Orders Table Results: id customer 1 Tizag day_of_order 2008-08-01 00:00:00. Also. customer.use mydatabase. quantity FROM orders. going this route doesn't allow for you to alter the presentation of the results. SELECT day_of_order. Unfortunately. We're not going to discuss too much detail here just go ahead and execute the following query. by not including the id column in the list SQL did not fetch any column results for us simply because we didn't ask for them. SELECT COUNT(*) FROM orders. SQL Select COUNT() Query: use mydatabase. . This is a built in SQL function that we can use with our SELECT statement(s) to return the number of rows returned by our query rather than returning each table column and value.Select All (*) A shortcut exists to select all of a table's columns.000 customer Tizag product Sharpie quantity 4 By rearranging the table column list inside the SELECT statement we altered the appearance of the results. SQL Orders Table Results: day_of_order 2008-08-01 00:00:00. SQL Select All Query: use mydatabase. SELECT * FROM orders.000 product Sharpie quantity 4 We've mentioned functions a few times and now is a great opportunity to introduce the COUNT() function.
The best habits are to be as precise as possible and in the case of select statements this often means selecting ONLY the data than you need. It allows for ascending or descending lists of your table column values permitting SQL to reorder your table rows for the purpose of viewing.SQL Count Results: (no column name) 1 Because we enclosed our table column value (*) inside of the COUNT function SQL interprets that differently than it would the generic query statements we used previously. SQL . At this point you should feel comfortable with SELECT and how to look into your database to see data as it exists in the table. More on this later. and accessing data as requested by each application. . Corrupted data may be lost and never recovered and it can even lead to more corruption inside a database. Taking every precaution to avoid data corruption is in your best interest as a new SQL programmer. Using this against our little tutorial database will surely do no harm but using this query against an enterprise level database may not be the best practice. Instead of returning column data. The reason being that large databases may have web services or applications attached to them frequently updating. If this fraction happens to occur just as some piece of data is being updated.com SQL Code: SELECT * FROM employees ORDER BY Lastname.Order By The order by statement allows for table column assortment. you may experience data corruption. we see only a single number representing how many rows were returned by our SELECT command.Selecting Data The (*) query statement should be used with caution. Advertise on Tizag. SQL . Each query that is executed against a database can temporarily lock a table for a fraction of a second. This knowledge will prove invaluable as your SQL skills develop beyond the basics and as you begin to tackle larger SQL projects.
Here is another example ordering by two different columns First we alphabatize our job titles and again we order by lastname. select. or delete statement is properly executed by your SQL program . SQL Code: SELECT * FROM employees ORDER BY Title. This number will also be displayed anytime an insert. update. Also notice at the bottom of each query display will be the number of rows affected by your query.SQL Table: ID Lastname 11 Davis 10 Harris 9 2 1 Hicks Hively Johnson Firstname Julie Joel Freddy Jessica David Title manager crew crew crew crew The above example resorts our rows of data alphabetically by lastname. SQL Table: ID Lastname 10 Harris 9 2 1 Hicks Hively Johnson Firstname Joel Freddy Jessica David Julie Title crew crew crew crew manager 11 Davis Hint: It is possible to order by a column you do not wish to display such as an ID field.Lastname.
Any duplicate combinations of job titles and salaries will be ignored. both rows would be returned. Advertise on Tizag.salaries.com A conditional statement has 2 parts. SQL . SQL will return the rows with distinct or unique combinations of those columns. only one row would be returned but if we had two CEOs with different salaries. Advertise on Tizag. SQL Code: SELECT DISTINCT job_titles.com SQL Code: SELECT DISTINCT job_titles FROM employees. SQL . For example say we have a table of employees and in this table of employees we have several job titles from janitors to CEOs. Your server will query the database searching for rows that meet your specific where condition.SQL . . the left side is your table column and the right side is the condition to be met. Example:WHERE table_column(s) = condition. SQL has returned all the rows with unique combinations of job titles and salaries. Assume this same employee table has another column including the salary of each employee.Distinct Usage Distinct is used to retrieve rows of your database that have unique values for a given column. With the use of the distinct function we can pull a list of unique job titles . We would like to know just how many distinct job titles we have. salary FROM employees.Distinct Multiple Columns Using the distinct function with more than one column yields some substantial results.Where The where clause sets a conditional statement for your queries. For example if we had two CEOs in the table making the same salary each year. Our statement will return the number of rows with a distinct value for our column (job_titles). A typical query will have the following syntax.
With the in operator . Recall that in a where expression only one value is allowed to be sent through the query.Firstname. perhaps meaning they are full time employees. SQL .Hours FROM employees. payroll.Title.Where multiple conditionals SQL also supports multiple conditional statements within one script by using the AND or OR operators.Lastname = payroll.Lastname. Continuing the example from above we can select only those employees that worked 36 or more hours for the week.Hours => '36' ORDER BY employees.SQL Code: SELECT * FROM employees WHERE Title = 'crew' ORDER BY Lastname. for a complete list backtrack to SQL Operators SQL . SQL Code: SELECT employees. the where clause is a very powerful tool used to quickly pull rows from one table or many. employees.In In is a special kind of operator for use in your where clauses.payroll WHERE employees. As you can see. employees.Lastname AND payroll.Lastname. SQL Table: ID Lastname 10 Harris 9 2 1 Hicks Hively Johnson Firstname Joel Freddy Jessica David Title crew crew crew crew All the known typical operators can be used in the conditional statements.
last FROM employees WHERE user_id IN (Select user_id FROM logbook).com SQL Code: SELECT * FROM table_name WHERE some_column IN('value1'. Say we have a database with the following tables. The second table might be a log type table that keeps track of who accessed the database and at what time. The result is a complete listing of the names of .In Subqueries To better understand the power of this function. A standard operating procedure if many people will be accessing the database. Employees: user_id 0045 0067 0098 Logbook: user_id 0045 0045 0098 timestamp 000000002345 000000045666 000000076444 Davis Smith Hodgensen last first Julie John Bruce Now above we have an employees table giving us a user_id along with a first and last name of employees we have working in the office. SQL . What we want to know is the last name and first name of those that accessed the database.'value2'. SQL Code: SELECT first. The rows returned will have one of the values listed (value1. let's use an example involving a subquery.one can send multiple values in the where clause. This a security check. or value3) in brackets as the value for the specified column (column_one). To do this we may use a subquery like in the example below.'value3'). Advertise on Tizag. value2. The subquery highlighted in red selects all the values of user_id in the logbook and returns those to the previous in statement.
6. It allows for the selection of a range of values between one value and another. Be aware that the values you specify will also return results.Between Between is a special operator appearing in a where statement. SQL . employees user_id 0045 0048 0067 0098 logbook user_id timestamp last Davis Thomas Smith Hodgensen first Julie David John Bruce . or 10. SQL In. Below are two tables. This definatly adds some depth to your SQL knowledge thus far.8. For example if we were looking for values between 5 and 10. The employee table only stores personal information about employees while the logbook records when and who accessed our database.the employees that have accessed the database and have been recorded inside the logbook table. SQL .7. all rows would be retrieved where our column value is 5.In Between (Subqueries) This next example requires that you are familiar with the previous lesson. You may recall that the In operator allows the where clause to return more than one single value for a column. Advertise on Tizag. The good news is that this feat was accomplished without having to know the user_ids of every employee in the office.com SQL Code: SELECT * FROM table_name WHERE column_one BETWEEN value1 AND value2.9.
SQL will now retrieve exactly what we need. or modifying an existing table column. SQL Code: SELECT * FROM employees WHERE user_id IN (SELECT user_id FROM logbook WHERE user_id BETWEEN 0040 AND 0049). where X represents any number 0-9 (So data security employees are numbered 0040-0049).Alter Table The alter clause changes a table by adding.com The following example adds a new column to our table. SQL Table: id Lastname 1 Johnson Firstname David Title crew dob Now we will remove the same column from the table. Since we konw this information it will prove useful if we want to track down database users by department. For example our data security department employees will be numbered 004X. .0045 0045 0048 0098 000000002345 000000045666 000000055767 000000076444 Say we were thinking ahead when issuing user_ids and coordinated each user_id number with a department. removing. SQL Code: ALTER TABLE employees ADD dob varchar(10). A listing of all the data security employees (user_id 004X) that have accessed the database thus far. SQL . Advertise on Tizag.
our manager. SQL Code: ALTER TABLE 'employees' CHANGE 'ID' 'id' TINYINT ( 3 ) NOT NULL AUTO_INCREMENT. For instance if we wanted to change a table column name or change a column from a varchar to an interger type. After we have selected a new name.Update The update clause updates column values of a table. SQL Table: id Lastname 1 Johnson Firstname David Title crew SQL . . Update requires a conditional statement to select the row to be updated. to a new manager. SQL .Alter Columns Alter is used again when changing attributes of the table cloumns.com SQL Code: UPDATE employees SET Lastname = 'Fletcher'. Firstname = 'Ron' WHERE id = '11'.SQL Code: ALTER TABLE employees DROP dob. Advertise on Tizag. we list the new attributes to be given to the altered column. Above we changed 'ID' to 'id' because SQL is case sensative and this will remove a potential bug issue. SQL Table: ID Lastname 11 Fletcher Firstname Ron Title manager Here we changed record 11.
We may use all of our known SQL operators as .Delete Entire rows can be deleted from a table using the delete clause.Deleting Multiple Rows Delete is not limited to one row at a time. update allows for the manipulation of several rows at once. SQL Code: UPDATE employees SET Title = UPPER(Title). SQL Table: ID Lastname 1 2 9 Johnson Hively Hicks Firstname David Jessica Freddy Joel Julie Title CREW CREW CREW CREW MANAGER 10 Harris 11 Davis Using the UPPER expression we changed our Title field to all capital letters.com SQL Code: DELETE FROM employees WHERE id='4'.Updating Multiple Rows With the use of expressions and operators. We could use the above code to delete an employee using their unique employee number that has been assigned by the auto_increment field. Advertise on Tizag.SQL . SQL . SQL . Update also supports the use of subqueries.
SQL Code: DELETE FROM employees WHERE id <= '999'. expressions.Predicates Predicates follow the where clause.com SQL .well as subqueries to delete any or all rows that apply to our conditional. a percent sign (%) is used to define the start and ending or your string. SQL Code: TRUNCATE TABLE employees. but it is a handy statement to know and use when the time is right. After a where clause.Truncate We can clear an entire table using a truncate statement. SQL Code: SELECT * FROM employees WHERE Lastname LIKE '%H%'. and operators can be used to delete any rows you would like to remove from your table. Predicates. SQL . subqueries. The above example would delete every row from our table since we had previously limited our "id" field when we set up the table. we don't recommend that you run this script because you will essentially undo all of your inserts and have only empty table field to show for it. Not Like Like is a means of quering data in your database by keyword or keyletter means. Advertise on Tizag. Truncate quickly clears all rows of a table without deleting the table itself. use LIKE to match a character or a string. . SQL . Rows will be returned if they match the predicate condition. If you are following along.Like. Escape characters can be used for special situations. SQL retrieves all rows containing all or part of the string placed within the parameters. Generally. Predicates allow the searching through database records to recover specific strings and ranges or characters.
MySQL also supports the escape predicate allowing you to change your escape character exactly as it is done in the other programs.Predicates Escaping Characters Say you want to find a percent character(%) in your database. With Oracle and SQL Server. SQL Code: Oracle/SQL Server SELECT * FROM employees WHERE Lastname LIKE '%\%%' ESCAPE '\'. or all rows associated with one. On a contrary note. .SQL Table: ID Lastname 10 Harris 9 2 Hicks Hively Firstname Joel Freddy Jessica Title crew crew crew Our example will retrieve any and all rows with a capital letter H in the lastname field. SQL Table: ID Lastname 1 Johnson Firstname David Julie Title crew manager 11 Davis SQL . Here's code example. SQL Server and Oracle. use the Not Like predicate to find all rows that do not match the string. Case sensitivity is important in this situation. MySQL SELECT * FROM employees WHERE Lastname LIKE '%\%%' MySQL has a built in default escape character the backslash (\). you must specify the character used to escape. SQL Code: SELECT * FROM employees WHERE Lastname NOT LIKE '%H%'. require an additional statement over MySQL.
Always start your ranges with the lowest number first. Advertise on Tizag. and right. SQL Code: SELECT * FROM employees WHERE id BETWEEN 1 AND 4. SQL Table: ID Lastname 1 2 Johnson Hively Firstname David Jessica Title crew crew Between is essentially replacing your range operators.SQL . A join query does not alter either table.Between Between is a predicate to call a range of numeric values such as 1-20 or the like. SQL Code: SELECT * FROM employees LIMIT 2. Join matches up a column with one table to a column in another table. Its syntax follows the same as above. There are three types of join statements. but temporarily combines data from each table to be viewed as a single table.Inner Join The join clause combines columns of one table to that of another to create a single table.com . inner. left.Limit The limit predicate allows you to limit the number of rows selected. SQL . SQL Table: ID Lastname 1 2 Johnson Hively Firstname David Jessica Title crew crew SQL .
invoices.Left Join A Left join returns all rows of the left of the conditional even if there is no right column to match. SQL Code: SELECT employees.Firstname.Price FROM employees INNER JOIN invoices ON employees.99 . Sale. invoices. invoices. EmployeeID.Lastname.Lastname.99 We haven't changed or updated any information in either of our tables but we were able to fashion together a new table using a conditional that matches one table column to another. Inner Join: An inner join returns all rows that result in a match such as the example above. and Price.Price FROM employees LEFT JOIN invoices ON employees. Our invoices table is set up with 3 fields.Firstname.id = invoices. SQL Code: SELECT employees. employees. If we were a business owner we now have a means to track what was sold. employees. and by whom and we can bring this information together using an inner join clause.EmployeeID SQL Table: Lastname Johnson Hively Davis Davis Firstname David Jessica Julie Julie Sale HOT DOG LG SFT DRK CD SLD CD SLD Price 1.99 3.id = invoices. and a new table to track sales of each employee called invoices.EmployeeID SQL Table: Lastname Johnson Firstname David Sale HOT DOG Price 1. SQL .We will be using our employees table from previous examples.49 3.Sale. invoices.99 1.Sale.
EmployeeID SQL Table: Lastname Davis Davis Johnson Firstname Julie Julie David Sale CD SLD CD SLD HOT DOG HOT DOG Hively Jessica LG SFT DRK LG SFT DRK Price 3.99 1.99 1.Right Join A right join will display rows on the right side of the conditional that may or may not have a match.Lastname.49 1.49 CD SLD CD SLD 3.99 3.Price FROM employees RIGHT JOIN invoices ON employees.Firstname. SQL Code: SELECT employees.id = invoices.Sale.99 This would be a great way to track sales per person per day if the invoice table had a date field as well. invoices. .49 This would happen generally if perhaps nobody recieved credit for the sale or the sale was credited to the store by default.Hively Hicks Harris Davis Davis Jessica Freddy Joel Julie Julie LG SFT DRK 1.99 1.99 3. employees. SQL . invoices.
SQL Code: SELECT * FROM employees UNION SELECT * FROM employees2.Sale. and join them with our invoices table to generate a complete list of sales from both stores on a given day. invoices.SQL . With 2 queries. A union works best when using two tables with similar columns because each cloumn must have the same data type.com Say we had another table called employees2 with the names and information of employees from our second store. SQL Table: ID 1 2 9 10 11 Lastname Johnson Hively Hicks Harris Davis Firstname David Jessica Freddy Joel Julie Jim Craig Kevin Brad Title crew crew crew crew manager crew crew crew crew 101 Yazzow 102 Anderson 103 Carlson 104 Maines The result is a complete listing every employee from store 1 and 2.Firstname. Advertise on Tizag. invoices. employees.Union The union clause places two serarate queries together forming one table.Lastname. The next example shows a more practical means of using a union clause. Here we will select all of our employees from both tables. SQL Code: SELECT employees.Price FROM employees INNER JOIN invoices . we can combine the tables into a list of all employees.
99 1. invoices. SQL .49 Here we combined a join query with the union clause to create one table. SQL Table: Lastname Johnson Hively Davis Yazzow Carlson Firstname David Jessica Julie Jim Kevin Sale HOT DOG LG SFT DRK CK SLD HOT DOG LG SFT DRK Price 1.99 1. employees2.Price FROM employees2 INNER JOIN invoices ON employees2.99 1.Sale. SQL Code: SELECT * FROM employees UNION ALL SELECT * FROM employees2.Firstname.Union All Union all selects all rows from each table and combines them into a single table.ON employees.Lastname.id = invoices. instead it just pulls all rows from all tables fitting your query specifics and combines them into a table. invoices. SQL Table: ID 1 2 9 10 11 Lastname Johnson Hively Hicks Harris Davis Firstname David Jessica Freddy Joel Julie Jim Title crew crew crew crew manager crew 101 Yazzow .49 3.EmployeeID.id = invoices. The difference between Union and Union all is that Union all will not eliminate duplicate rows.EmployeeID UNION SELECT employees2.
Lastname. SQL Table: Lastname Johnson Hively Davis 11 Yazzow Carlson 11 11 Firstname David Jessica Julie Davis Jim Kevin Davis Davis Sale HOT DOG LG SFT DRK CK SLD Julie HOT DOG LG SFT DRK Julie Julie Price 1.id = invoices.id = invoices. invoices.Firstname.EmployeeID UNION ALL SELECT employees2. however Oracle and DB2 fully support them.Lastname.Sale.Subqueries MySQL offers a very limited support for subqueries.EmployeeID.99 1.99 1.99 manager 1. invoices. invoices. employees2. .102 Anderson 103 Carlson 11 Davis Craig Kevin Julie Brad crew crew manager crew 104 Maines SQL Code: SELECT employees.Price FROM employees2 INNER JOIN invoices ON employees2. invoices. employees.Firstname.Sale.Price FROM employees INNER JOIN invoices ON employees.49 3.49 manager manager SQL . Subqueries are Select queries placed within an existing SQL statement.
SQL Code: SELECT * FROM employees WHERE id = (SELECT EmployeeID FROM invoices WHERE EmployeeID='1'). SQL Table: id Lastname 11 Davis Firstname Julie Title MANAGER Here we have pulled our employee information from the employees table by only knowing the employee number from the invoices table.Lastname. Just given this information we can use a subquery to pull the employee lastname and first name from our database.Firstname.Firstname.Subquery Inserts Subqueries can be used to pull old data from your database and insert it into new tables. SQL . SQL Code: INSERT INTO employees3 (id.Title FROM employees WHERE Title='manager'). therefore several rows may or may not be inserted depending upon how your table is set up.com • • • • • • Select Insert Update Delete Set Do Subqueries are great for answering very specific questions regarding your data inside your database. Advertise on Tizag.They may exist in any of the following types of SQL statements.Lastname. as the employer you may notice employee number 101 had a great day yesterday with sales. For instance.Title) (SELECT id. . Also note that this form of insert will insert all cases where the subquery is true. For instance if we opened up a third store and we wanted to place the same manager over 3 stores we could do this by pulling the manager's information using a subquery and then inserting the records.
Retrieving a timestamp is very simple and the result can be converted or manipulated in nearly every way imaginable. SQL Code: SELECT CURRENT_TIMESTAMP. and MySQL.840 Keep in mind that each platform of SQL (DB2. the few listed work in DB2.) may return dates and times which are formatted differently. Return a Month: 6 SQL Code: SELECT DAY(CURRENT_TIMESTAMP). SQL Server. Oracle.. it is possible to breakdown timestamps into their individual pieces using any of the following date functions. Microsoft SQL Server users should skip to our SQL Datepart lesson.. SQL Code: SELECT MONTH(CURRENT_TIMESTAMP). every SQL platform has its own version of date functions.With complete mastery of a subqueries you can now see the power of the SQL language. Oracle. etc. Return a Timestamp: 2004-06-22 10:33:11.Dates Unfortunately. Advertise on Tizag. . SQL . The language is capable of nearly all things imaginable.com SQL .Timestamp A timestamp servers as the catch all for dates and times. SQL .Date Functions As we just mentioned.
SQL will return a numeric result from 1 . .returns a numeric value (1-7) SELECT DAYOFMONTH(CURRENT_TIMESTAMP).840) SELECT DAYOFWEEK(CURRENT_TIMESTAMP). including functions to extract milliseconds. SQL Code: SELECT MONTHNAME('2004-11-27'). Here's a few c\The following is a list of other date functions available to most platforms of SQL with the exception of MS's SQL Server.365 representing the day of the year that Joe's record was created/inserted. or timestamp to the function which then returns our result. .returns the time (10:33:11.returns the month name (January .December SELECT DAYNAME(CURRENT_TIMESTAMP). time.Return a Day: 22 There are many more functions available. names of the months.returns number of the week (1-53) Timestamps are often the easiest to work with.returns a day of month (1-31) SELECT DAYOFYEAR(CURRENT_TIMESTAMP). . SQL Function Code: SELECT DATE(CURRENT_TIMESTAMP). . We can send any date.returns the day of the year (1-365) SELECT MONTHNAME(CURRENT_TIMESTAMP). . Each SQL platform varies in the actual naming of date functions. . . SQL Code: SELECT DAYOFYEAR(column_name) FROM table_name WHERE name = 'Joe'.returns the name of the day (Sunday . Return a Month Name: MONTHNAME('2004-11-27') November Date functions can also be performed on table columns similarly to numeric and mathematical functions such as SUM() or AVG(). . names of each week day. .returns a date (2004-06-22) SELECT TIME(CURRENT_TIMESTAMP).Saturday) SELECT WEEK(CURRENT_TIMESTAMP). but we certainly are not limited to using only the current_timestamp as our parameter. etc.
James Bond. By setting the default value to the current date or timestamp. Built into most platforms are several date column types such as DATE or TIMESTAMP.Inserting Date Data Date data exists as numbers. A date or timestamp table column will only allow date data types to be inserted as values so be sure to convert any strings or numbers to dates and timestamps before trying to insert them SQL . a timestamp of that order is also recorded. In this table column are timestamps of when each record was entered and we would like to know what was the numeric day of the year that a record was entered. Here's the code to add a timestamp column to an existing table. strings.com The difference is that SQL Server uses one main function as oppose to several different functions ie the DATEPART() function. Above you can see how it is possible to combine several date functions as well as a subquery to return very specific information about Mr. SQL Code: ALTER TABLE `orders` ADD `order_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL.Datepart() Microsoft's SQL Server takes a little different approach to working with dates. a part . Datepart() requires two parameters.Date. It is still possible to extract individual parts of a timestamp and several other functions also work as outlined in SQL .We can expand this concept one step further with the use of a subquery. Now each time an order is placed in our make believe business. Advertise on Tizag. Say we have a table with a column named timestamp. the table column will automatically be filled with a current date/timestamp as each record is inserted. and timestamps. SQL . SQL Code: SELECT DAYOFYEAR( (SELECT DATE(timestamp) FROM employees WHERE name = 'James Bond') ).
SQL's CURRENT_DATE function could be also be substituted or a string value representing the year ('Dec 31. SQL Code: SELECT DATEPART(week.d wk. '2005-12-31'). time. The following table lists the datepart() arguments that can be extracted from any given date. It provides when-then-else functionality (WHEN this_happens THEN do_this) also known as conditional .y dd. Return the Week Number: 53 Here we have successfully pulled the "week number" from existing date. or timestamp. By part we mean year.Case In SQL case works with either the select or update clauses.q mm.ww dw hh mi.m dy. day of the week.yyyy qq. 2005').s ms SQL .argument and a date argument. Let's look at an example.n ss. day of the year. part year quarter month dayofyear day week weekday hour minute second millisecond Description returns a 4 digit year returns a value 1-4 representing the year's quarter returns the numeric equivalent month (1-12) returns the day of the year (1-365) returns the day of the month (1-31) returns the number of the week (1-53) returns the number of the day of the week (1-7) returns the number of hours for a given time returns the number of minutes from a given time returns the number of seconds in a given time returns the number of milliseconds in a given time Abbreviation(s) yy. etc.
Case (update) Case functions additionally allow for the updating of records within your table. SQL Code: SELECT employee_name CASE admin WHEN 1 THEN 'yes' ELSE 'no' END 'admin' FROM employees. we have a list of a few employees and then an admin column with boolean (true/false) values for their administration rights (admin).statements.com SQL . SQL Case: employee_name Ted Terry Trish admin no no yes In short all we really did is replace 1's and 0's with the words 'yes' and 'no'. we can present this information in a better form. For example. we could update the prices of items in our online store. A zero means they are not an admin a 1 mean they are. employee_name Ted Terry Trish admin 0 0 1 As you can see. Let's use the following table for this next example. .CASE (select) For this concept. visualize the following table. but more importantly we could update very specific records because of the conditional logic allowed by case. Advertise on Tizag. Using case logic. SQL .
Then we'll take 10% off the items that we have 10-20 of (between 10 and 20) and everything else we will discount only 5%.75 Each price has automatically been reduced by the appropriate percentages .95 END.00 0.item goldfish guppy blow fish quantity 12 24 1 price 1. SQL Code: UPDATE inventory SET price = price * CASE WHEN quantity > 20 THEN 0.375 4. SQL Case: item goldfish guppy blow fish quantity 12 24 1 price .75 WHEN quantity BETWEEN 10 AND 20 THEN 0.90 ELSE 0.9 0.00 Let's say we wanted to have a sale to clean out some of our overstock.50 5. We'll go ahead and take 25% off of all our items that we currently have 20 or more of (>20).
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue listening from where you left off, or restart the preview.