A Quick SQL Database Notes | Keys

SQL Database Keys

Ho ho ho , another Sunday morning and I am feeling much better than yesterday. Been a bit busy and stressed out with work , school and a visit to the Dentist. I couldn’t come up with anything that is more than a few lines last night but after reading on Databases , for my degree course , I came up with something interesting and related to Databases.

I be posting on database keys. Thats right , keys. I am sure you remember we talked about two such keys when I posted on the sample database. If you don’t remember or you have not seen it before , one such tutorial is here.They are “Primary” and “Foreign” keys.

A primary key is an unique key which is used to locate a particular row in the database. For example , finding an employee’s information using his employee id. You might wonder , why don’t we use his name? Well there might be two people with the same name! Thats also true for the birthday , address and phone number. On the other hand , the employee id is an internal numbering which is internally controlled by the company. It only makes sense that it should be the only way we are going to be able to find the employee information , unaffected by the outside influence.

A foreign key , on the other hand , is a primary key of a table on the another table. If you looked at our sample database page , you will see that employee id is also present in the department table. Therefore , employee id is a primary key in one table and a foreign key in another.

So what other types of keys have we not talked about? Plenty it seems. Below , I will be putting up a summary of the keys in the database , for easy reference for you and me. I am sure I will be looking back to this article every now and then.

  • Primary Key – A unique key that is used to quickly locate records by the database
  • Foreign Key – A primary key on one table that is used as a constraint in another table
  • Compound Key or composite Key – A key that includes more than one field
  • Superkey – A set of columns for which no two rows can have the exact same value
  • Candidate Key – A minimal superkey
  • Unique Key – A superkey used to require uniqueness by the database
  • Alternate Key – A candidate key that is not the primary key
  • Secondary Key – A key used to look up records but that may not guarantee uniqueness

Keys Conclusion

Phew. Thats all for keys. Glad I got something to write on. Cya!

Essential LINQ For Beginners

Essential LINQ

Alrighty , I shall now take a dive into LINQ from today onwards. SO what exactly is LINQ in the first place? This is one definition ,

LINQ (Language Integrated Query) is a Microsoft programming model and methodology that essentially adds formal query capabilities into Microsoft .NET-based programming languages. LINQ offers a compact, expressive, and intelligible syntax for manipulating data. The real value of LINQ comes from its ability to apply the same query to an SQL database, a DataSet, an array of objects in memory and to many other types of data as well. LINQ requires the presence of specific language extensions.

LINQ uses an SQL-like syntax to make query expressions well beyond the capabilities of embedded SQL as implemented in programming languages. That’s because embedded SQL uses a simplified, streamlined syntax to add SQL statements to other programming languages, where there’s no attempt to integrate such statements into the native syntax and typing mechanisms. Thus, you can’t invoke native language structures such as functions in embedded SQL statements, as you can using LINQ, because it is implemented to use native syntax, structures, and typing mechanisms. Furthermore, LINQ may be used to access all kinds of data, whereas embedded SQL is limited to addressing only databases that can handle SQL queries.”

Source Here.

LINQ Example

Well then what does it look like?

It looks like this ,

public void LinqExample()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    var numsPlusPlus =
        from n in numbers
        select n + 1;

    Console.WriteLine("Numbers++:");
    foreach (var i in numsPlusPlus)
    {
        Console.WriteLine(i);
    }
}

and this prints out ,

Numbers++:
6
5
2
4
10
9
7
8
3
1

If you remember or read the post on loops I did a while back , here is the link, you will notice that it looks very similar to the for loop we did back then , except that instead of going through numbers from start to finish , I went through a group or an array of lists.

An array is simply a container of objects such as an integers we have over here. One of the main usage is to have the group sliced and diced. You could for example , 5th place of an array or maximum values of the list. Of course , a table is also an array of data. You could select the maximum value in a specific column or choose a specific value. You could imagine here that there is a table with a column header named “numbers” and the values are entered as follow ,

Numbers
5
4
1
3
9
8
6
7
2
0

Then you would do a select all statement and then add 1 to the result. The result would be similar to above and that is one of the reason you would see such statements ,

var numsPlusPlus =
        from n in numbers
        select n + 1;

This in SQL would be

Select *  from numbers;

Hmms … I can’t seems to find a function that adds a value to the select output .. But you get the drift. This is where we will be starting out on LINQ and I hope to have more examples in future. Cya!

Whats Been Done

Lets see what have we looked at so far

- Basic SQL ( CRUD – Creat , Read , Update , Delete )
- Basic Programming ( Loops , If-Else , Functions … )
- Basic OOP ( Classes/Subclasses/Constructors … )

This about covers all the basic , I think. Maybe we should move into integration with SQL and Programming Languages. Probably LINQ and PHP/MySQL. After all that , we can talk about basic networking. Once all that is done , next would be security. Great!

SQL SELECT DISTINCT Statement

SELECT DISTINCT

SELECT DISTINCT In Excel

Here is something very close to your heart if you been using spreadsheet programs such as Microsoft Excel. You have rows and rows of customer orders to process and you want , or your manager wants , to know how many customers are currently in the list. For this , you can’t just count how many rows you have. Maybe some of your customers ordered twice or in different time then you might have a problem of double counting them. What you need to is to know how many of them are DINSTINCT.

Here is how you might have done it in Excel ,

Data -> Sort & Filter -> Advanced Filter -> Select unique items & copy to a new range

How do we do the same in SQL? Imagine we have rows and rows of employees , from it you want to know how many of the employees have the same title.

Before I show you the code , here is the syntax of it ,

SQL SELECT DISTINCT Syntax

SELECT DISTINCT column_name(s)
FROM table_name;

I think by now you should be able to come up with the code , if not here it is ,

SELECT DISTINCT emp_title
FROM employee;

Play with it and hope it helps!

SELECT Statement with AND & OR Operators

Lets take a breather from JOIN statements we been looking at and lets look at AND and OR operators to be used in conjunction with with the SELECT statement to query information from the database.

Here is a sample SELECT statement using WHERE clause


select emp_name as 'Name', emp_sex as 'Sex', emp_salary as 'Salary' from employee where emp_sex = 'Male';

This will return you with 3 rows , excluding the lone female we have in the sample database.

Name Sex Salary
Michael Bay Male 90000.00
John Evan Male 5000.00
George Chan Male 50000.00

Its all fine but what if you want to select those who are BOTH Male AND has salary of more than 10000.00? Of course , this mean only two out of three will qualify. SO how do we do this in SQL?


select emp_name , emp_sex, emp_salary from employee where emp_sex = 'Male' and emp_salary > 5000;

Here we are looking for employees who are both Male and must have salary of more than 5000. The important thing to note is that using “AND’ means both the conditions must be satisfied. The query result for this statement is of just 2 rows.

Name Sex Salary
Michael Bay Male 90000.00
George Chan Male 50000.00

So what about OR? Try it. Replace ‘and’ with ‘or’ in the previous statement , like this ..


select emp_name , emp_sex, emp_salary from employee where emp_sex = 'Male' or emp_salary > 5000;

Guess what is the result from this query? If you say all three rows are returned as the first query then you are right. Because using ‘OR’ operator , only one of the conditions must be right. Either the employee is Male or has salary more than 5000. Since John Evan is Male , it qualifies him even though his salary is not more than 5000.

Hope this helps if you are wondering how is it possible to apply two conditions in SQL Select statement. See ya!

More SQL JOIN Statements

Lets look at another way of querying with JOIN statement. Just to recap from previous post that JOIN statement aka INNER JOIN return rows when there is at least one match in BOTH tables

select e.emp_name as "Employee Name" , d.dept_name "Department Name"
from employee e , department d
where e.emp_dept_id = d.dept_id and d.dept_budget > 500000;

So what is the difference compared to what we have looked at last time? The difference is slight , the main logic stays the same but how we name the names have changed. take a look at the second line

from employee e , department d

Here we are saying “employee” table from now on will be referenced by “e” for the lifetime of the SQL statement. If you come from traditional programming background , like me , you might find it odd that “e” can be used on the first line yet it is only defined in the second line. You definitely cannot use a variable that has not been defined!

Anyway , besides that weirdness , every other part remains the same. Of course they are now “e.emp_name” instead of “employee.emp_name”. This query will return ,

Employee Name Department Name
Michael Bay Asia
John Evan Finance
Christine May Sales
George Chan Asia