Library of Useful (Difficult) SQL scripts [closed] - sql

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Does anyone know where I can find a library of common but difficult (out of the ordinary) SQL script examples. I am talking about those examples you cannot find in the documentation but do need very often to accomplish tasks such as finding duplicates etc.
It would be a big time saver to have something like that handy.
EDIT: Thanks everyone, I think this is turning into a great quick reference. The more descriptive the more effective it would be, so please if you see your way open - please edit and add some descriptions of what one could find. Many thanks to those that have already done so!

You may find this wiki on LessThanDot useful, for the most part, it is by Denis Gobo, Microsoft SQL MVP.
EDIT:
The wiki includes 100+ SQL Server Programming Hacks, the list is, I think, too long to include here, however, there is a comprehensive index.
Also available from the same site: SQL Server Admin Hacks.

Here are a few that I find very useful:
SQL Server Best Practices - Microsoft SQL Server White Papers and Best Practices
vyaskn - A mixture of articles From DBA to Developer
Backup, Integrity Check and Index
Optimization
SQLServerCentral Scripts - Scripts for most most DBA tasks and more
Script Repository: SQL Server 2005 - TechNet Script Center
Scripts and Tools for Performance Tuning and Troubleshooting SQL Server 2005
SQL Server Query Processing Team - Hardcore advice from the MS SQL optimisation team
Common Solutions for T-SQL Problems
Davide Mauri's Index Scripts

Some Administration stuff
Glenn Berry: Five Very Useful Index Selection Queries for SQL Server 2005
Find "Missing" Indexes for the entire instance of SQL Server
Find "Missing" Indexes for a single table
Examine the current index structure for a single table
Look at index usage for a single table
Look for possible bad indexes inside the entire current database
Drill into your workload (Bonus)
SQL Server Central: Seven Monitoring Scripts
Failed jobs report
Free space by drive
Disabled jobs
Running jobs
Server role members
Last backup date
SQL Log
And last, but not least this resource: SQL Server Programming Hacks - 100+ List

Joe Celko's SQL Puzzles and Answers
The Art of SQL (slight Oracle bias)

Sql Cookbook has a variety of interesting example, though some will undoubtedly be unsupported by your RDBMS of choice. O'Reilly also has a T-SQL Cookbook, but I've never personally read it.

directly from MS Script Repository: SQL Server 2005:
http://www.microsoft.com/technet/scriptcenter/scripts/sql/sql2005/default.mspx?mfr=true
Nigel's very usefull stuff:
http://www.nigelrivett.net/#TransactSQL

Forgive me for the self-advertising, but I have posted a few on my blog (http://progblog.wordpress.com) because I'm rubbish at SQL and it's a good place to store things I know I'll need in the future :-) If anyone has anything more substantial then please post, I'm as keen as anyone to get hold of something like this!
I would guess that a copy of the "SQL Cookbook" would help too.

I've had some use of these SQL "hacks" for Oracle a couple of times.
Concatenate as grouping function
In query data generation for joining purposes

Here is another link for SQL Server: best practices - dozens of script examples
http://www.sqlusa.com/bestpractices2005/

Check Out SQLCAT.com (MS SQL BEST PRACTICES TEAM)

Riffing off the Celko answer: SQL For Smarties. This has great in depth chapters that will augment the SQL Puzzles book. Also there is another Celko book I just learned of named
Joe Celko's Trees and Hierarchies in SQL for Smarties.

Related

Online databases for trying out Oracle SQL queries? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am studying for an undergraduate databases course.
I'd like to know if there are any online sites that allow me to do queries against an already built and populated database (with a known schema), so I didn't have to install SQL and populate it with data myself.
I am currently doing some exercises by hand on a workbook I have here, but I'm a bit afraid that I might be doing them wrong and it's hard to check their correctness without testing them against the "real thing".
Thanks
(In our course we are using Oracle)
Have you tried SQLZoo ?
You can (for free) install SQL Server 2008 R2 Express Edition, and download and install already populated databases (such as AdventureWorks2008) from here. Both installs are straight forward.
If you don't want to go far, do try the StackExchange Data Explorer:
About
Stack Exchange Data Explorer allows you to run arbitrary queries on the Stack Exchange public data dumps.
It's fast and supports a SQLServer-like T-SQL syntax.
Give Stack Exchange's Data Explorer a spin.
For Oracle specific queries, you can signup for Oracle's Apex which gives you a pre-populated schema based on the Employees/Departments table
You can easily install MySQL/PostgreSQL/SQL Server Express and get up and running, also whatever test data might be installed on a publicly available server won't necessarily stay the same between queries, since anyone can access it.
So just go ahead and install one of the above, you'll thank yourself in the near future.
Maybe not exactly what you are looking for, by SQLZoo Tutorials allow you to practice some basic interactions, and also allow you to interact with a number of different SQL Engines.
http://sqlzoo.net/
Try out this Interactive SQL site. It looks what are you looking for
You could try installing WAMP Server. This comes with MySQL and a UI of phpMyAdmin that you can use to install and test databases. Then you can install the MySQL test employees database.
For very simple queries, you can try SQL queries online in the W3Schools SQL Try It page - http://www.w3schools.com/sql/sql_tryit.asp
Or you can use the online demo of phpMyAdmin at http://demo.phpmyadmin.net/STABLE/?pma_username=root for deeper use.
Oracle Apex provides online space for you to create and execute your sql queries. Please create an account with Oracle Apex and then enjoy with your personalised tablespace and schema. This is freeware and Oracle doesn't charge anything for this. It is the best way if you don't want to install Oracle on your system and don't want to slow down your system. Another advantage of Oracle Apex is that you have all your tables and data online and you don't have to maintain it, Oracle will do that for you. You can access your database from anywhere you want.

Looking for SQL Optimization Interview Questions

I'm on a project where I was asked to take a quick peek at some reporting SQL (in a SQL Server 2K5 environment) and was surprised at what I found: 4 to 5 levels of subquerys, distinct clauses, unions, and NoLock hints (which were needed because the SQL was running so long it was blocking standard processing) - all in the same set!.
Because I (foolishly :) mentioned that I thought the SQL was inefficient I've been labeled the "expert" and have been tasked with creating a test for a couple of interviewees to do that will assess their SQL optimizing abilities. I'm hoping someone can point me to some URLS, or maybe provide a list that I can use to help weed out the good from the bad.
Since you mentioned the SQL Server 2005 environment:
More SQL Server interview questions than you possibly could have imagined:
The classic set. Most interviewees will probably have studied these...maybe a good way to gauge who has prepared.
Another classic
Questions from one of the original Stack Overflow DBAs
Another link for best SQL questions and answers
I would give them a Query plan (via EXPLAIN, or whatever your flavor of SQL uses as a keyword) and see if they can decipher what it means, what the weak points are, and how to improve the query.
Look at MySQL's Explain Documentation for help using MySQL's explain and what it means.

Looking for exercises to learn SQL, using the Northwind database [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I am trying to become more familiar with SQL by writing queries against the Northwind database.
I am looking for some exercises that would help me to learn SQL and features of SQL Server. It is important that the exercises have solutions, and in complicated cases, it would be great if there was an explanation for the query.
Thanks for the answers so far but I still have not found what I am looking for:
Is there any free resource, available online, without registration, that I can find a list of these exercises?
sql-ex is very userful site to learn sql.
Wikibooks have few exercises: SQL Exercises
I would pick up Inside Microsoft SQL Server 2005: T-SQL Querying. This book is great and has exercises + answers
I did an interview with the author a while back about this book, you can find that here: Interview With Itzik Ben-Gan Author Of Inside Microsoft SQL Server 2005: T-SQL Querying
A few things to focus on that will exercise a lot of areas of SQL that you should know if you're going to be writing a lot of it:
Joins - INNER and OUTER (difference between LEFT and RIGHT JOIN)
GROUP BY clause and working with aggregate functions such as SUM, MIN, MAX, etc..
WHERE - for filtering records returned in a query
Subqueries - Subqueries and Correlated subqueries
CASE, COALESCE, BETWEEN, CONVERT, CAST functions/statements
Find a good data set and try to run some meaningful queries on it. Make sure you start with a problem you want to solve (i.e. what is the average order amount for people who live in WA in the Northwind database?).
For a few simple problems/exercises:
http://caml2010.wordpress.com/2010/06/12/northwind-exercise/
The best way to learn in my opinion would be to work on a small hobby project.
For instance, lets say you are interested in sports, pick up your favorite sport and envision how you would model the sport statistics in the most elegant way in the form of a SQL database. You would start thinking on the lines of how to pull data out of the db, update the data , so on and so forth.
Whenever you encounter an issue, you can go look at the reference books (The T-SQL querying book mentioned above is a very good one) and figure out the best way of doing it.
Toy examples,exercises are good. But in my opinion, unless you really face a problem and solve it on your own, the fundamentals don't stick into your head.
Articles like this http://www.sommarskog.se/dynamic_sql.html are also extremely helpful, since they provide insight into how, why and why not.
Also check out this link http://www.sql-server-performance.com/tips/related_web_links_p1.aspx
If you have Reporting Services handy, or even Visual Studio, creating a few reports with aggregates, sums, counts etc will give you a little insight to how data can be used as information and really boost your SQL skills.
I work in a telephony company where this goes on all the time. I have this book sitting on my desk which I have found really handy.
Good luck! :)

Can you recommend a good source for Teradata Best Practices?

Looks like my data warehouse project is moving to Teradata next year (from SQL Server 2005).
I'm looking for resources about best practices on Teradata - from limitations of its SQL dialect to idioms and conventions for getting queries to perform well - particularly if they highlight things which are significantly different from SQL Server 2005. Specifically tips similar to those found in The Art of SQL (which is more Oracle-focused).
My business processes are currently in T-SQL stored procedures and rely fairly heavily on SQL Server 2005 features like PIVOT, UNPIVOT, and Common Table Expressions to produce about 27m rows of output a month from a 4TB data warehouse.
One place to start is here: http://www.teradataforum.com/
This might be a little late, but there are a few things which I can warn you about Teradata which I have learned.
Use the most recent version as often as possible.
For V12 the optimizer was re-written and the database performs much better now.
Try to realize that SQL Server and Teradata are very different beasts, most of the concepts will not transition well.
Do not underestimate the importance of a primary index.
The locks that teradata uses are very primitive when compared to other databases.
Do NOT use TERA mode. You do not have any code which is legacy, ANSI mode is far superior and is widely encouraged.
Join indexes are very helpful tools, but they do not provide all the answers.
Parallelism, take the time to understand how FASTLOAD, MULTILOAD, and TPUMP works and find out how one can leverage it with their ETL strategy.
If you are attempting to run a query which needs to be performant, do not use any casts, the optimizer will not use statistics to generate the best execution plan.
Working with dates are going to be a pain, just a warning.
Teradata is very DDL oriented, try to understand all the syntax related when creating a table.
Compression is a wonderful tool, if you have any values which are repeated in a table, make use of it.
There are not many tools available with Teradata, be prepared to build a lot. The tools that exist are very expensive.
Unfortunately, I do not know much about SQL Server, so I cannot say what tools in SQL Server appear in Teradata.
Hope this helps
I would also look into the recently launched Teradata Developer Exchange as well as the TeradataForum and forums on Teradata's main website.
I don't know of any good references available online. Teradata has some design manuals that are available for download, but they're more instruction manuals and not "best practices" as such. check them out here: http://www.info.teradata.com/DataWarehouse/eTeradata-BrowseBy.cfm?page=Teradata%20Database
Alternatively, you need to find a friendly Teradata expert to bounce ideas off. Try Teradata themselves, or find a local consultant with Teradata experience.
Best Practices on Teradata isn't a topic that gets lots of discussions and most of the best tricks tend to be proprietary knowledge of the person/people who discovered them.
Sorry,
David Stewardson
Satyam Computer Services
Top of the list on a Google search for "Teradata Best Practices" gave me TERADATA ADVISORY GROUP SETS BEST PRACTICES FOR BUSINESS OBJECTS AND TERADATA CUSTOMERS
EDIT: Seeing as that's just advertising, as you've pointed out, see how you go with these. Please bear in mind that I don't have a clue what Teradata is and can't see myself using it any time this side of the 22nd century AD.
Teradata Discussion Forums
Best Practices for Teradata Deployments
Best Study Guides For NCR Teradata Certifications
The middle one looks promising with it's nice long link tree at the top
Oracle® Business Intelligence Applications Installation and Configuration Guide > Preinstallation and Predeployment Considerations for Oracle BI Applications > Teradata-Specific Database Guidelines for Oracle Business Analytics Warehouse >
and the first link, to the forums, should put you in touch with the right people.

How to learn MDX [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am currently learning OLAP & MDX after many years of relational database development.
Any tips on getting started in MDX? What are the best books and resources to learn MDX?
A classic, albeit a bit dated, book is Fast Track to MDX. It's a great overview and a quick read, though it doesn't cover the new MDX features of SQL Server 2005.
The Spofford book MDX Solutions is more up date and a little deeper, but a bit harder to get through.
I also highly recommend the blogs of Mosha Pasumansky, Chris Webb, and Darren Gosbell.
Here is an MDX gentle introduction.
I found the Spoffard book not very helpful. MDX is such an oddity compared to other languages you'll learn, it's so hard to grasp from a dry book. I really would recommend a training course, otherwise you will flounder for ages. A course will really jump-start you, and it provides access to an expert when you have questions which don't seem to have online answers.
The worst trap to fall into, is to continually compare it with SQL! It uses some of the same keywords, but they mean something totally different, which makes the mental jump annoyingly harder.
I think the most efficient way to learn either OLAP or MDX would be to find someone who knows it, and get them to show you around, begin with some small changes, or some very simple queries.
You should also try and get hold of MDX Studio, a free MDX query tool written by Mosha Pasumansky (one of the original creators of MDX). It has similar MDX functionality to SQL Management Studio, but also allows you to parse and format queries, which can be very handy when trying to decipher them.
I prefer dragging and dropping fields around in MS Excel, and then using SQL Server profiler to capture trace against SSAS. This way, you get an awesome frontend for building queries, and then you can get the queries that Excel is using through the profiler.
If you create a Pivot Table that uses a cube (in Excel), you can see the query that is being sent using this (towards the bottom of the page)
http://www.codeplex.com/OlapPivotTableExtend
That might be a good way of getting a feel for the simpler stuff.
N.B. This is only in Excel2007, not sure about earlier versions
Book: MDX Step by Step
Video tutorials, e.g. MDX tutorial and Analysis Services introduction
There are more.
I would recommend
MDX with Microsoft SQL Server 2008 R2 Analysis Services Cookbook
We used the LearnItFirst.com training videos and found them to be a very thorough introduction to SSAS and MDX. There are around 40 hours of content plus exercises including around 6 hours of pure MDX Training.
The details for the SSAS Course can be found at:
Learn IT First SSAS Training
Besides the books and resources mentioned by others, the easiest way to kick-start your MDX learning is to get a copy of ProClarity. Unfortunately getting your hands on ProClarity is nowhere near as easy as it used to be. Microsoft bought the company in 2006, and it is now licensed through PerformancePoint, I believe. Oh yeah, and they quit development on the product.
Having said all that, if you are able to get a copy, you can build queries by dragging and dropping dimensions and measures onto your rows and columns. The results of the query are then displayed in either a grid, a chart, or both.
How does this help you learn MDX? ProClarity lets you see the MDX for each query. It isn't always the most elegant MDX, but it will help you quickly learn how to write lots of different queries.