31 May 2024

PowerShell Interview Questions for SQL Server DBAs

 

Problem

With PowerShell playing a more important role in administration of various types of servers, more SQL Server DBA candidates should have PowerShell knowledge and skills. But I still do not see many good PowerShell interview questions targeting DBA candidates, can you provide some questions?

Solution

PowerShell (PS) is rich and deep in content itself, and it is almost impossible to come up with a comprehensive question list to check a candidate's knowledge on every aspect of PS. But in the context of DBA work, we may come up with some good questions to test a DBA's PowerShell knowledge.

I personally do not like to ask questions where the answer can be memorized, such as "what is a PowerShell cmdlet?", "What is an advanced PowerShell function?", etc. Instead, I'd prefer to ask "hands-on" questions such as "Write me a function to display disk size and its free space", "write me a script to read the SQL Server error log and report any entries with words like 'Error xxx occurred'"?, etc.

The questions listed below are designed with two simple rules:

  • Questions should be related to common SQL Server DBA tasks and are simple to complete in a few lines of PS code
  • No Books Online (BOL) is needed as you are expected to find the necessary information via PS self-exploring capability, i.e. get-member

There is one requirement though, the answers should not use T-SQL, such as in this way, invoke-sqlcmd -query "t-sql-code".

Assume SQLPS module (in SQL Server 2012+) is installed and also assume all operations are on a local server. This way, we can prepare a stand-alone test environment on a laptop for the candidate. No network, internet or Googling needed.

  1. Determine if the SQL Server service or SQL Server Agent service is running
  2. Start / stop a SQL Server service
  3. Find the SQL Server version / edition including the service pack level
  4. Find the SQL Server operating system information such as the OS version, processor number, physical memory, etc.
  5. Find the largest SQL Server database by size
  6. Find any SQL Server databases in full recovery without a transaction log backup in the past 3 hours
  7. Find the largest (by size or rows) 3 tables in the AdventureWorks2012 database
  8. Delete the SQL Server backup files in the D:\Backup folder if the file is older than 7 days
  9. Find any orphaned SQL Server database users (i.e. db users without logins)
  10. Script out a SQL Server Agent Job, based on a specific category
  11. Find all SQL Server Agent Jobs that failed during the last execution
  12. Kill all sessions connected to a SQL Server database

Answers to PowerShell Interview Questions for SQL Server DBA

Note: each answer is just one of many possible ways to address the question, and you may come up with better answers than the provided ones.

We need to load PowerShell 3.0 with the SQLPS module.  Here is the code:

#require -version 3.0
#we first need to import SQLPS module
Push-Location
import-module SQLPS -DisableNameChecking;
Pop-Location
$svr=get-item SQLServer:\SQL\<your server>\default # <your server>\default means the default sql instance on <your server>, 
                                              # replace <default> with <instance name> if you are interested in a named instance.

 

  1. Determine if the SQL Server service or SQL Server Agent service is running
get-wmiobject -class win32_service -filter "displayname like 'sql server%'" | select name, displayname, state
# or
get-service -name "*sql*" | select name, displayname, status
  1. Start / stop a SQL Server service
Stop-Service -Name MSSQLSERVER -Force; #note -name parameter value is case-sensitive.
Start-Service -name MSSQLSERVER;
  1. Find the SQL Server version / edition including the service pack level
$svr | select version, edition, productlevel;
  1. Find the SQL Server operating system information such as the OS version, processor number, physical memory, etc.
$svr | select OSVersion, Processors, PhysicalMemory;
  1. Find the largest SQL Server database by size
$svr.databases | select name, size | Sort-Object -Property size -Descending | Select-Object -First 1;
  1. Find any SQL Server databases in full recovery without a transaction log backup in the past 3 hours
$svr.databases | ?{ $_.RecoveryModel -eq 'Full' -and $_.lastlogbackupdate -lt (get-date).AddHours(-2)} | select name, lastbackupdate, lastlogbackupdate
  1. Find the largest (by rows or size) 3 tables in the AdventureWorks2012 database
# Size by row count
$svr.databases['AdventureWorks2012'].tables | select name, rowcount | Sort-Object -Property RowCount -desc | select -First 3



# Size by table storage
$svr.databases['AdventureWorks2012'].tables | select schema, name, @{name='size'; e={$_.dataspaceused+$_.indexspaceused }} | 
Sort-Object -Property size -desc | select -First 3;
  1. Delete the SQL Server backup files in the D:\Backup folder if the file is older than 7 days
dir d:\backup\*.bak -Recurse | where creationtime -lt (get-date).AddDays(-7) | Remove-Item -Force;
  1. Find any orphaned SQL Server database users (i.e. db users without logins)
$svr.databases | % {$_.users | ? {$_.issystemObject -eq $false -and $_.login -eq ''} | select parent, name, login }
  1. Script out a SQL Server Agent Job, based on a specific category
$svr.JobServer.jobs | where Category -eq 'DBA Admin' | % {$_.script()} | Out-File -path c:\temp\DBA_Admin_Jobs.sql -force;
  1. Find all SQL Server Agent Jobs that failed during the last execution
$svr.JobServer.jobs | where lastRunOutcome -eq 'failed' | select name, lastrundate, lastrunoutcome
  1. Kill all sessions connected to a SQL Server database
$svr.EnumProcesses() | ? { $_.IsSystem -eq $false -and $_.database -eq 'AdventureWorks2012'} | % {$svr.KillProcess($_.spid)}

Summary

In this tip, I listed some common SQL Server DBA tasks that may be completed easier with PS than T-SQL. Most answers rely on SMO. Using these questions as an example, you can come up with your own PS+SMO questions, such as doing backup/restore processes, checking user/object permissions, index fragmentation or more complex ones like Replication, High Availability management, etc.

One thing we need to bear in mind based on my experience is that in an unprepared "hands-on" test, the majority of candidates will perform probably only at 70% (or lower) of their normal capacity. So it is unfair to design some complex questions (like you need to solve with 50+ lines of code) and expect a sound solution within a short time.

I consider PS as an administration automation tool/platform, and I believe in the near future, with PS, we DBAs will be able to create a software-defined database administration framework, in which we will customize our administration according to business requirements, but with our personal styles and flavors. With Microsoft starting to switch their product management from GUI based to a Unix-like command line interface (CLI), the line between traditional DBAs and developers will be blurred, and programming skills will be more important to SQL Server DBAs.

SQL Server Career Planning

 

Problem

I am looking for career advice.  I would like to know how to get started with my career and plan for changes over time.  Do you have any suggestions for building my career?  Check out this tip for some valuable career advice for new and experienced SQL Server Professionals.

In many respects starting and growing your SQL Server career have a number of the same considerations.  At any point in your career, you need to know the following:
  • What are you looking for in your SQL Server Career?
  • Starting Your SQL Server Career
  • Growing Your SQL Server Career
  • SQL Server Interview Recommendations

What are you looking for in your SQL Server Career?

Knowing what you want in your career is just as important as what you do not want.  Often times, many professionals really do not know what they do and do not want.  In my opinion, it is important to take some time for a self assessment and ask yourself what you want and do not want in your job. As a point of reference, here is a basic list of items I have heard from SQL Server Professionals:

  • Challenging technical problems to resolve
  • Listened to by management and the recommendations provided are respected and acted upon
  • Job security and stable work environment to not have to worry about whether you will have a job next week or not
  • Salary and benefits that are commensurate with the job responsibilities and experience
  • Flexible schedule and the ability to take vacations without having to respond to emails and phone calls
  • Less politics and ability to focus on technology
  • Low stress with reasonable deadlines
  • Educational benefits and paid training
  • Ability to work on the latest and greatest technology
  • New and exciting opportunities rather than a routine schedule

Are these the same items you are looking for in your career?  Are there others?  If so, please share your thoughts as a comment for this tip.


Starting Your SQL Server Career

When you are starting your career you need to make the decision to work in the technology field and figure out a few different jobs you would like to try.  Talk with everyone you know to get an understanding of what they do, how they do it, what they like, what they dislike, how to get started, etc.  They might even be able to point you in the right direction to get your first job.  Starting off you need to get your first opportunity and use it as a stepping stone for trying a few different types of jobs.  Most people with years of experience do not know what they want to do, so figuring out exactly what you want to do when you start off is challenging.

As you start your career you need to set some goals for yourself.  Be sure to record your goals and revisit them on a quarterly, semi-annual or annual basis.  As best as possible, try to quantify your goals and setup a time frame i.e. 1, 3, 5, etc. years.  Items to consider as you build your goals:

  • Education
    • Are you learning something new every day?
    • Do you have a test environment setup for you to learn and test items you have learned?
    • Is your employer encouraging you to work towards certifications, degrees, etc.?
  • Career
    • Do you have the opportunity to grow? 
    • Has your manager established a path for you at the company?
    • Are you working with the latest and greatest technologies?
    • Do you enjoy what you are doing?
    • Can you see yourself growing in your career and advancing in future years?
    • Do you want to try other technologies?
  • Family
    • What are the implications on your family?
    • Is there a separation between work and family?
  • Financial
    • Are you being paid a competitive salary and offered valuable benefits?

Growing Your SQL Server Career

As you progress in your career, some of the items you worked through when you started your career are still applicable, but you also need to include additional items such as:

  • Self Assessment
    • Determine your "comfort zone".
      • Whether this is development, operations, BI, etc., you need to know what you do well and why that is the case.  You also need to think about items such as your comfort in working with one portion of SQL Server or the entire stack.  Also think about your comfort level working on a team versus independently.  Do you have experience working in both scenarios?  Do you have a preference?
    • Determine areas of improvement.
    • Determine professional interests.
  • Educational Plan
    • Determine your opportunities to learn from your employer and your personal resources.
    • Grow your test environment to be able to test and learn.
    • Review online options to learn as well as local events such as user groups, SQL Saturdays, Code Camps, etc.
    • Build a plan to learn each new edition of SQL Server.
  • Network
    • Be sure to make a concerted effort to build your online and offline network.  If you run into an issue, make sure they will be your life line.
  • Goals
    • Review your goals to determine the items you have accomplished, what has changed and what you still need to accomplish.
    • Revise goals that have changed, remove goals that are no longer applicable and create new goals that align with your current interests.
    • Be sure to look forward in order to stay on top of technology changes.

SQL Server Interview Recommendations

As you begin your interview process, be sure you understand the process.  Ask questions to understand how the recruiter, manager, etc. works through the interview process at the company.  Traditionally speaking, the interview process is something like:

  • Find job that you are interested in and you meet the qualifications
  • Based on the needs, update your resume to best match the requirements
  • Contact the company\recruiter\hiring manager and send them your resume
  • If selected for the initial round of interviews, prepare for the phone interview which could be with the recruiter or hiring manager
    • This could be one or more rounds of interviews depending on the organization
  • If selected for the next round of interviews, prepare for an onsite interview with the team
    • This could include a peer interview to determine if you would be a good fit for the team
    • This could include a technical interview to determine your technical skills
  • Depending on the organization, a decision may be reached or there may be multiple onsite interviews\meetings with the team
  • Generally, the last step in the process if the employer is interested in your skills is to issue a background check and/or check your references

Over the years, I have seen this process change dramatically.  I have seen a much less rigid process in some organizations with entire interviews held over lunch while others are administering technical and aptitude tests.  I have also seen a much heavier reliance on learning about companies and potential employers based on information found online and networking web sites.  In some circumstances, Google performs your background checks for you.  These are just short term and long term considerations as you prepare for an interview.

As you prepare for the your interview be sure you know the following:

  • Understand the employer's needs.
  • Who will be involved in the interview and their role.
  • Where the interview will be held.
  • Everything about the company that you can find out.
  • Your commute time.
  • Travel requirements.
  • Work schedule including off hours work.
  • Your "sales pitch" to let the employer know why you can uniquely benefit them.

MS SQL Server - Assign Permissions

 Permissions refer to the rules governing the levels of access that principals have to securables. You can grant, revoke and deny permissions in MS SQL Server.

To assign permissions either of the following two methods can be used.

Method 1 – Using T-SQL

Syntax

Use <database name>
Grant <permission name> on <object name> to <username\principle>

Example

To assign select permission to a user called 'TestUser' on object called 'TestTable' in 'TestDB' database, run the following query.

USE TestDB
GO
Grant select on TestTable to TestUser

Method 2 – Using SSMS (SQL Server Management Studio)

Step 1 − Connect to instance and expand folders as shown in the following snapshot.

Assign Permissions

Step 2 − Right-click on TestUser and click Properties. The following screen appears.

Database TestUser

Step 3 Click Search and select specific options. Click Object types, select tables and click browse. Select 'TestTable' and click OK. The following screen appears.

Database TestUser

Step 4 Select checkbox for Grant column under Select permission and click OK as shown in the above snapshot.

Database TestUser

Step 5 Select permission on 'TestTable' of TestDB database granted to 'TestUser'. Click OK.

MS SQL Server - Create Users

 User refers to an account in MS SQL Server database which is used to access database.

Users can be created using either of the following two methods.

Method 1 – Using T-SQL

Syntax

Create user <username> for login <loginname>

Example

To create user name 'TestUser' with mapping to Login name 'TestLogin' in TestDB database, run the following query.

create user TestUser for login TestLogin

Where 'TestLogin' is the login name which was created as part of the Login creation

Method 2 – Using SSMS (SQL Server Management Studio)

Note − First we have to create Login with any name before creating a user account.

Let’s use Login name called 'TestLogin'.

Step 1 − Connect SQL Server and expand databases folder. Then expand database called 'TestDB' where we are going to create the user account and expand the security folder. Right-click on users and click on the new user to see the following screen.

Database User New

Step 2 − Enter 'TestUser' in the user name field and click on ellipse to select the Login name called 'TestLogin' as shown in the following snapshot.

Testuser

Step 3 − Click OK to display login name. Again click OK to create 'TestUser' user as shown in the following snapshot.

Create Users

28 May 2024

MS SQL Server - Restoring Databases

 Restoring is the process of copying data from a backup and applying logged transactions to the data. Restore is what you do with backups. Take the backup file and turn it back into a database.

The Restore database option can be done using either of the following two methods.

Method 1 – T-SQL

Syntax

Restore database <Your database name> from disk = '<Backup file location + file name>'

Example

The following command is used to restore database called 'TestDB' with backup file name 'TestDB_Full.bak' which is available in 'D:\' location if you are overwriting the existed database.

Restore database TestDB from disk = ' D:\TestDB_Full.bak' with replace

If you are creating a new database with this restore command and there is no similar path of data, log files in target server, then use move option like the following command.

Make sure the D:\Data path exists as used in the following command for data and log files.

RESTORE DATABASE TestDB FROM DISK = 'D:\ TestDB_Full.bak' WITH MOVE 'TestDB' TO 
   'D:\Data\TestDB.mdf', MOVE 'TestDB_Log' TO 'D:\Data\TestDB_Log.ldf'

Method 2 – SSMS (SQL SERVER Management Studio)

Step 1 − Connect to database instance named 'TESTINSTANCE' and right-click on databases folder. Click Restore database as shown in the following snapshot.

Management Studio Testinstance

Step 2 − Select device radio button and click on ellipse to select the backup file as shown in the following snapshot.

Select Backup Device

Step 3 − Click OK and the following screen pops up.

Restore Database

Step 4 − Select Files option which is on the top left corner as shown in the following snapshot.

Restore Database TestDB

Step 5 − Select Options which is on the top left corner and click OK to restore 'TestDB' database as shown in the following snapshot.

Restore Database TestDB

MS SQL Server - Creating Backups

 Backup is a copy of data/database, etc. Backing up MS SQL Server database is essential for protecting data. MS SQL Server backups are mainly three types − Full or Database, Differential or Incremental, and Transactional Log or Log.

Backup database can be done using either of the following two methods.

Method 1 – Using T-SQL

Full Type

Backup database <Your database name> to disk = '<Backup file location + file name>'

Differential Type

Backup database <Your database name> to 
   disk = '<Backup file location + file name>' with differential

Log Type

Backup log <Your database name> to disk = '<Backup file location + file name>'

Example

The following command is used for full backup database called 'TestDB' to the location 'D:\' with backup file name 'TestDB_Full.bak'

Backup database TestDB to disk = 'D:\TestDB_Full.bak'

The following command is used for differential backup database called 'TestDB' to the location 'D:\' with backup file name 'TestDB_diff.bak'

Backup database TestDB to disk = 'D:\TestDB_diff.bak' with differential

The following command is used for Log backup database called 'TestDB' to the location 'D:\' with backup file name 'TestDB_log.trn'

Backup log TestDB to disk = 'D:\TestDB_log.trn'

Method 2 – Using SSMS (SQL SERVER Management Studio)

Step 1 − Connect to database instance named 'TESTINSTANCE' and expand databases folder as shown in the following snapshot.

Creating Backups

Step 2 − Right-click on 'TestDB' database and select tasks. Click Backup and the following screen will appear.

Backup

Step 3 − Select backup type (Full\diff\log) and make sure to check destination path which is where the backup file will be created. Select options at the top left corner to see the following screen.

Backup Database

Step 4 − Click OK to create 'TestDB' database full backup as shown in the following snapshot.

Full Backup

Creating Backups2

SQL Server Copilot AI

 Here are some of the latest tips and advanced concepts for Microsoft SQL Server (MS SQL) in 2024: 1. SQL Server Copilot AI Microsoft has in...