Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am a SQL beginner programmer and I want to write an SQL code which should count the number of entries in a column in two different ways. Like first just count them and then count only those values which are greater than 5. I am using the following code but it is giving error. ``` SELECT table1.col1, Count(t...
``` select col1, count(col1) as Expr1, sum(case when col1 > 5 then 1 else 0 end) as expr2 from table1 group by col1 ``` or ``` select col1, count(col1) as Expr1, count(case when col1 > 5 then col1 end) as expr2 from table1 group by col1 ``` First one just add 1 for each `col1 > 5`. Second one...
You want conditional aggregation: ``` SELECT table1.col1, Count(table1.col1) AS Expr1, SUM(case when table1.col1 > 5 then 1 else 0 end) as expr2 FROM table1 GROUP BY table1.col1; ``` Some versions of SQL treat booleans as the integer values `0` and `1`. For these, you can simplify the expression to: ``...
Implement two different Operation on the same Column in a query using SQL
[ "", "sql", "" ]
I am getting this error when there is absolutely no usage of int anywhere. I have this stored procedure ``` ALTER procedure [dbo].[usp_GetFileGuid] @fileType varchar(25) as select [id] from fileTypes where dirId = @fileType ``` Here id is a uniqueidentifier in fileTypes table When I execute the following ``` ...
You are using `EXEC @fileGuid = procedure` syntax which is used for retrieving *return* values, not resultsets. Return values are restricted to `INT` and should only be used to return status / error codes, not data. What you want to do is use an `OUTPUT` parameter: ``` ALTER procedure [dbo].[usp_GetFileGuid] @file...
The value returned is an int as it is the status of the execution From [CREATE PROCEDURE (Transact-SQL)](http://technet.microsoft.com/en-us/library/ms187926.aspx) > Return a status value to a calling procedure or batch to indicate > success or failure (and the reason for failure). You are looking for an output param...
int is incompatible with uniqueidentifier when no int usage
[ "", "sql", "sql-server", "" ]
Does SQLite support common table expressions? I'd like to run query like that: ``` with temp (ID, Path) as ( select ID, Path from Messages ) select * from temp ```
As of Sqlite version 3.8.3 SQLite supports common table expressions. [Change log](http://www.sqlite.org/releaselog/3_8_3.html) [Instructions](http://www.sqlite.org/lang_with.html)
Another solution is to integrate a "CTE to SQLite" translation layer in your application : "with w as (y) z" => "create temp view w as y;z" "with w(x) as (y) z" => "create temp table w(x);insert into w y;z" As an (ugly, desesperate, but working) example : <http://nbviewer.ipython.org/github/stonebig/baresql/blob/mas...
Does SQLite support common table expressions?
[ "", "sql", "sqlite", "common-table-expression", "" ]
I have a column called Work Done where on daily basis some amount of work is caarried out. It has columns ## Id, VoucherDt, Amount Now my report has scenario to print the sum of amount till date of the month. For example if Current date is 3rd September 2013 then the query will pick all records of 1st,2nd and 3rd Sep...
``` SELECT SUM(AMOUNT) SUM_AMOUNT FROM <table> WHERE VoucherDt >= DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0) AND VoucherDt < DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 1) ```
I think that there might be a better solution but this should work: ``` where YEAR(VoucherDt) = YEAR(CURRENT_TIMESTAMP) and MONTH(VoucherDt) = MONTH(CURRENT_TIMESTAMP) and DAY(VoucherDt) <= DAY(CURRENT_TIMESTAMP) ```
Taking sum of column based on date range in T-Sql
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-server-2008-r2", "" ]
I've got a bit of a messy table on my hands that has two fields, a date field and a time field that are both strings. What I need to do is get the minimum date from those fields, or just the record itself if there is no date/time attached to it. Here's some sample data: ``` ID First Last Date Time ...
You can do this with `row_number()`: ``` select ID, First, Last, Date, Time from (select t.*, row_number() over (partition by id order by date, time) as seqnum from test t ) t where seqnum = 1; ``` Although storing dates and times as strings is not recommended, you at least do it right. The va...
Assuming `[Date]` and `[Time]` are the types I think they are, and not strings: ``` SELECT ID,[First],[Last],[Date],[Time] FROM ( SELECT ID,[First],[Last],[Date],[Time],rn = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY [Date], [Time]) FROM dbo.test ) AS t WHERE rn = 1; ``` Example: ``` DECLARE @x TABLE ( ...
SQL Statement to Get The Minimum DateTime from 2 String FIelds
[ "", "sql", "sql-server", "" ]
If I do: ``` SELECT * FROM A WHERE conditions UNION SELECT * FROM B WHERE conditions ``` I get the union of the resultset of query of A **and** resultset of query of B. Is there a way/operator so that I can get a short-circuit `OR` result instead? I.e. Get the result of `SELECT * FROM A WHERE conditions` ...
The short answer is no, but you can avoid the second query, but you must re-run the first: ``` SELECT * FROM A WHERE conditions UNION SELECT * FROM B WHERE NOT EXISTS ( SELECT * FROM A WHERE conditions) AND conditions ``` This assumes the optimizer helps out and short circuits the second query be...
You can do this with a single SQL query as: ``` SELECT * FROM A WHERE conditions UNION ALL SELECT * FROM B WHERE conditions and not exists (select * from A where conditions); ```
Short-circuit UNION? (only execute 2nd clause if 1st clause has no results)
[ "", "mysql", "sql", "set", "union", "resultset", "" ]
I need to extract some data from a postgresql database, taking a few elements from each of two tobles. The tables contain data relating to physical network devices, where one table is exclusively for mac addresses of these devices. Each device is identified by location (vehicle) and function (dev\_name). table1 (asset...
When using a `join` you can specify which columns have to match ``` SELECT a.vehicle, a.dev_name, dev_model, dev_serial, mac FROM assets a LEFT JOIN macs m ON m.vehicle = a.vehicle AND m.dev_name = a.dev_name WHERE interface = 'E0' ORDER BY a.vehicle, a.dev_name ```
Read about [SQL join](http://en.wikipedia.org/wiki/Join_%28SQL%29). ``` select a.vehicle, a.dev_name, a.dev_model, a.dev_serial, m.mac from assets as a inner join macs as m on m.dev_name = a.dev_name and m.vehicle = a.dev_name where m.interface = 'E0' order by a.vehicle, a.dev_name ``` In your case it's inner...
JOIN across two tables
[ "", "sql", "database", "postgresql", "select", "join", "" ]
Take a look at this execution plan: <http://sdrv.ms/1agLg7K> It’s not estimated, it’s actual. From an actual execution that took roughly **30 minutes**. Select the second statement (takes 47.8% of the total execution time – roughly 15 minutes). Look at the top operation in that statement – View Clustered Index See...
First I'd like to point out a little misconception here: although the delete statement is said to take nearly 48% of the entire execution, this does not have to mean it takes 48% of the time needed; in fact, the 51% assigned inside that part of the query plan most definitely should NOT be interpreted as taking 'half of...
Observations include: 1. Is this the biggest of these databases that you are working with? If so, size matters to the optimizer. It will make quite a different plan for large datasets versus smaller data sets. 2. The estimated rows and the actual rows are quite divergent. This is most apparent on the fourth query. "de...
View Clustered Index Seek over 0.5 million rows takes 7 minutes
[ "", "sql", "sql-server", "performance", "indexed-view", "indexed-views", "" ]
I have the following MySQL query that runs absolutely fine: ``` SELECT a.id, a.event_name, c.name, a.reg_limit-e.places_occupied AS places_available, a.start_date FROM nbs_events_detail AS a, nbs_events_venue_rel AS b, nbs_events_venue AS c, (SELECT e.id, COUNT(d.event_id) AS places_occupied FROM nbs_events_detail AS ...
You [can not use aliases](http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html), defined in query, in `WHERE` clause. In order to make your query works, use condition `a.reg_limit-e.places_occupied>0` in `WHERE` clause.
The `WHERE` clause is executed before the `SELECT` statement, so it doesn't know about that new alias `places_available`, [the logical order of operations in Mysql](http://www.bennadel.com/blog/70-SQL-Query-Order-of-Operations.htm) is like this: > 1. FROM clause > 2. WHERE clause > 3. GROUP BY clause > 4. HAVING claus...
WHERE clause on subtraction between two columns MySQL
[ "", "mysql", "sql", "where-clause", "" ]
I need to compare two strings character by character using T-SQL. Let's assume i have twor strings like these: ``` 123456789 212456789 ``` Every time the character DO NOT match, I would like to increase the variable @Diff +=1. In this case the first three characters differ. So the @Diff = 3 (0 would be default va...
for columns in table you don't want to use row by row approach, try this one: ``` with cte(n) as ( select 1 union all select n + 1 from cte where n < 9 ) select t.s1, t.s2, sum( case when substring(t.s1, c.n, 1) <> substring(t.s2, c.n, 1) then 1 else 0 end ) as diff from...
This code should count the differences in input strings and save this number to counter variable and display the result: ``` declare @var1 nvarchar(MAX) declare @var2 nvarchar(MAX) declare @i int declare @counter int set @var1 = '123456789' set @var2 = '212456789' set @i = LEN(@var1) set @counter = 0 while @i > 0 be...
T-SQL - compare strings char by char
[ "", "sql", "sql-server", "t-sql", "" ]
I use the following code to create a new database in SQL Server 2008 R2, program language is VB.NET: ``` Dim WEBconnString As String = "Data Source='NewName'; LCID=1032; Case Sensitive = FALSE; SSCE:Database Password=NewDBpass; Encrypt = TRUE;" Dim engine As New SqlCeEngine(WEBconnString) engine.CreateDatabase() ``` ...
1) It seems you are mixing *SqlServerCompact* (Local datatase which can be used in ASP.NET since version 4.0) and *SqlServer*. `SqlCeEngine` is part of `System.Data.SqlServerCe` namespace. So you create a SqCompact file and the `engine.CreateDatabase()` method raises an exception the second time. The connection string ...
It looks like you are opening the Server connection the the master database. The master database is where the sql server engine keeps all the important information and meta data about all databases on that server. I need to replace `database=master` to `database=WHATEVER DATABASE NAME YOU CREATED`. All else fails go t...
Create new Database in SQL Server 2008 R2
[ "", "sql", "database", "" ]
I am very new to using SQL and I am attempting to build my first query/report, and was hoping I could get some help on this (this seems to be the place to be for that!). Basically what I want to create is a report that shows when the last time an employee or contractor was paid. We have a database with all this informa...
You need to try something like ``` Select table1.Office, table1.EE_No, table1.Name, table1.Code, table1.Freq, (Select distinct MAX (table2.PayDate) from table2 where table1.UniqueID = table2.UniqueID ) as Last_Paycheck from table1 on where table1.EndDate is null ``` The other way would be something like ```...
Try changing this line: ``` (Select distinct MAX (table2.PayDate) from table2) as Last_Paycheck ``` To something like this: ``` MAX (table2.PayDate) OVER (PARTITON BY table2.UniqueID) as Last_Paycheck ``` With no `Select` needed - You've already stated the association needed in your join clause. Hope this does the...
SQL: Using Max function and returning max per client, not overall
[ "", "sql", "sql-server", "" ]
I have a table called `Sales` which has an `ID` for each sale and its date. I have another, called `SaleDetail`, which has the details of each sale: the `Article` and the `Quantity` sold. I want to show a list of all the articles and quantities of them that were sold between two dates. I'm using: ``` SELECT SaleDe...
Here the condition is supposed to be in where clause, but not having clause. Having only to groups as a whole, whereas the WHERE clause applies to individual rows. Here you are looking for rows with the specific dates. ``` SELECT SaleDetail.Article, SUM(SaleDetail.Quantity) AS Pieces FROM SaleDetail JOIN Sales ON Sale...
The HAVING Clause is for use when trying to filter on an Aggregate. In this case, Sales.Date is not being aggregated. So you can just use WHERE. ``` SELECT SaleDetail.Article, SUM(SaleDetail.Quantity) AS Pieces FROM SaleDetail JOIN Sales ON Sales.ID = SaleDetail.ID WHERE Sales.Date BETWEEN '10-01-2013' AND '20-01-2013...
Restrict joined and grouped SQL results
[ "", "sql", "sql-server", "" ]
I have a column called `MealType` (`VARCHAR`) in my table with a `CHECK` constraint for `{"Veg", "NonVeg", "Vegan"}` That'll take care of insertion. I'd like to display these options for selection, but I couldn't figure out the SQL query to find out the constraints of a particular column in a table. From a first gla...
This query should show you all the constraints on a table: ``` select chk.definition from sys.check_constraints chk inner join sys.columns col on chk.parent_object_id = col.object_id inner join sys.tables st on chk.parent_object_id = st.object_id where st.name = 'Tablename' and col.column_id = chk.parent_colu...
Easiest and quickest way is to use: ``` sp_help 'TableName' ```
How do I get constraints on a SQL Server table column
[ "", "sql", "sql-server", "" ]
i have a code that works, ``` CURSOR c_val IS SELECT 'Percentage' destype, 1 descode FROM dual UNION ALL --16028 change from union to union all for better performance SELECT 'Unit'destype, 2 descode FROM dual ORDER BY descode DESC; -- ``` i change the uni...
The choice between UNION and UNION ALL is not whether one of them works or not, or whether one of them is faster performing, but which one is correct for the logic you want to implement. UNION ALL is simply the results of the two queries combined into a single result set. You should consider the order of the result se...
``` "UNION" = "UNION ALL" + "DISTINCT" ``` So basically by going for `UNION ALL` you save a dedup operation. In this case you may find that the performance gain is negligible but it can be important on large datasets.
does union or union all make a big difference?
[ "", "sql", "oracle", "" ]
Using SQL Server 2008, this query works great: ``` select CAST(CollectionDate as DATE), CAST(CollectionTime as TIME) from field ``` Gives me two columns like this: ``` 2013-01-25 18:53:00.0000000 2013-01-25 18:53:00.0000000 2013-01-25 18:53:00.0000000 2013-01-25 18:53:00.0000000 . . . ``` I'm trying...
Assuming the underlying data types are date/time/datetime types: ``` SELECT CONVERT(DATETIME, CONVERT(CHAR(8), CollectionDate, 112) + ' ' + CONVERT(CHAR(8), CollectionTime, 108)) FROM dbo.whatever; ``` This will convert `CollectionDate` and `CollectionTime` to char sequences, combine them, and then convert them ...
The simple solution ``` SELECT CAST(CollectionDate as DATETIME) + CAST(CollectionTime as DATETIME) FROM field ```
Combining (concatenating) date and time into a datetime
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "datetime", "" ]
I will list some queries. Outputs are given later, towards the end. This query gives me 7 rows. ``` SELECT S.companyname AS supplier, S.country, P.productid, P.productname, P.unitprice FROM Production.Suppliers AS S LEFT OUTER JOIN Production.Products AS P ON S.supplierid = P.supplierid WHERE S.country = N'Japan' ORD...
A `LEFT JOIN` brings back every record from the 'LEFT' table, unless you limit it, as you did with your `WHERE` criteria. When you change it to be part of the `JOIN` criteria it's not limiting the results, just limiting which records have non NULL values from the right table.
Because you are doing Left join it always returns everything in the first table (Production.Suppliers). In the first example the Where clause filters the Suppliers table to just show 'Japan'. The query is something like: > "Give me all the suppliers **that are in** Japan and show me their products" When you do a joi...
Understanding the difference between ON with multiple conditions and WHERE in a JOIN
[ "", "sql", "sql-server", "" ]
I have a table with values like 0, 1, 2, 3 , -1, -2, 9, 8, etc. I want to put "blank" in column where number is less then 0, i.e. it should show all records and whereever the position is less than 0 it should show ''. I tried using STR but this made my query too slow. The query looks like this: ``` select CASE WHEN ...
You can put the `CASE` expression into the query, and replace `STR` with a `CAST`, like this: ``` SELECT CASE WHEN position < 0 THEN '' ELSE CAST(column1 as VARCHAR(10)) END as position , column2 FROM myTable ```
Try this way: ``` Select case when column1 <0 then null else column1 end as position, column2 from tab ```
Put blank in sql server column with integer datatype
[ "", "sql", "sql-server-2008", "" ]
I am running below : `sqlplus ABC_TT/asfddd@\"SADSS.it.uk.hibm.sdkm:1521/UGJG.UK.HIBM.SDKM\"` afte that I am executing one stored procedure `exec HOLD.TRWER` I want to capture return code of the above stored procedure in unix file as I am running the above commands in unix. Please suggest.
You can store command return value in variable ``` value=`command` ``` And then checking it's value ``` echo "$value" ``` For your case to execute oracle commands within shell script, ``` value=`sqlplus ABC_TT/asfddd@\"SADSS.it.uk.hibm.sdkm:1521/UGJG.UK.HIBM.SDKM\" \ exec HOLD.TRWER` ``` I'm not sure about...
I guess you are looking for `spool` ``` SQL> spool output.txt SQL> select 1 from dual; 1 ---------- 1 SQL> spool off ``` Now after you exit. the query/stroed procedure output will be stored in a file called output.txt
How to capture sqlplus command line output in unix file
[ "", "sql", "oracle", "unix", "sed", "awk", "" ]
Why do I get a syntax error on the following SQL statements: ``` DECLARE @Count90Day int; SET @Count90Day = SELECT COUNT(*) FROM Employee WHERE DateAdd(day,30,StartDate) BETWEEN DATEADD(day,-10,GETDATE()) AND DATEADD(day,10,GETDATE()) AND Active ='Y' ``` I am trying to assign the number of rows returned from my Se...
You need parentheses around the subquery: ``` DECLARE @Count90Day int; SET @Count90Day = (SELECT COUNT(*) FROM Employee WHERE DateAdd(day,30,StartDate) BETWEEN DATEADD(day,-10,GETDATE()) AND DATEADD(day,10,GETDATE())...
You can assign it within the `SELECT`, like so: ``` DECLARE @Count90Day int; SELECT @Count90Day = COUNT(*) FROM Employee WHERE DateAdd(day,30,StartDate) BETWEEN DATEADD(day,-10,GETDATE()) AND DATEADD(day,10,GETDATE()) AND Active ='Y' ```
Assign INT Variable From Select Statement in SQL
[ "", "sql", "database", "t-sql", "" ]
I have a messages table that has both a `to_id` and a `from_id` for a given message. I'd like to pass a user\_id to this query and have it return a non-duplicate list of id's, representing any users that has a message to/from the supplied user\_id. What I have right now is (using 12 as the target user\_id) : ``` SEL...
You can use a [`union`](http://dev.mysql.com/doc/refman/5.0/en/union.html): ``` select from_id as contact_id from messages where to_id = 12 union select to_id from messages where from_id = 12 ``` Also, from [the documentation](http://dev.mysql.com/doc/refman/5.0/en/union.html) (emphasis mine): > The default behavi...
Here's a solution avoiding a union statement. ``` SELECT distinct (case when to_id = 12 then from_id else to_id end) as contact_id FROM messages WHERE from_id = 12 OR to_id = 12 ```
Return id where one of two fields matches a value, but only the field other than that vaue
[ "", "mysql", "sql", "" ]
I am working on an Access database which keeps records of all the different batches arrived to and shipped from the warehouse. The locations in Warehouse are indicated by Lot\_ID. The table contains the following data: ``` Batch_ID | Lot_ID |Arrival_date | Shipping_date ----------------------------------------------...
Try ``` SELECT Lot_ID FROM Table1 GROUP BY Lot_ID HAVING SUM(IIF(Shipping_date IS NULL, 1, 0)) = 0 ``` Output: ``` |Lot_ID | |-------| | 1 | ```
you should check beluw link <http://www.w3schools.com/sql/sql_where.asp> should use where caluse like 'where shipping\_date = null '
Select ID from GROUP BY group if the group satisfied criteria
[ "", "sql", "select", "group-by", "" ]
I have two tables and I want in one query take few values. Tables: ``` users |user_id | |name | user_group_link |user_id | |group_id | ``` This is my query: ``` SELECT users.*, user_group_link.* FROM users LEFT JOIN user_group_link ON users.user_id = user_group_link.user_id WHERE user_group_link.group_id =...
The problem with this query: there is not a single row that has 10, 11 **AND** 12 as group\_id... you need **OR** here! ``` SELECT users.*, user_group_link.* FROM users LEFT JOIN user_group_link ON users.user_id = user_group_link.user_id WHERE user_group_link.group_id = 10 OR user_group_link.group_id = 11 OR user_g...
`user_group_link.group_id` can't be `10`, `11`, or `12` **at the same time**, you need `OR` instead of `AND`. So your query should be: ``` SELECT users.*, user_group_link.* FROM users LEFT JOIN user_group_link ON users.user_id = user_group_link.user_id WHERE user_group_link.group_id = 10 OR user_group_link.group_i...
How to make right sql query?
[ "", "mysql", "sql", "" ]
``` userid pageid 123 100 123 101 456 101 567 100 ``` I want to return all the `userid` with `pageid` 100 AND 101, should give me 123 only. This is probably super easy but I can't figure it out! I tried: ``` SELECT userid FROM table_name WHERE pageid=100 AND pageid=101 ``` ...
No record has 2 values of `pageid`. You probably want: ``` SELECT userid FROM table_name WHERE pageid=100 OR pageid=101 ``` In a cleaner version, you can use: ``` SELECT userid FROM table_name WHERE pageid IN (100,101) ``` **UPDATE:** Based on the question edit, Here is the answer: ``` SELECT userid FROM table_n...
According to your last edit you want to find all (distinct) `userid` where a `pageid` of 101 and also 101 exists. You can use `EXISTS`: ``` SELECT DISTINCT userid FROM TableName t1 WHERE t1.userid=123 AND EXISTS( SELECT 1 FROM TableName t2 WHERE t2.userid=t1.userid AND pageid = 100 ) AND EXISTS( SELECT 1 FROM ...
SQL: how to select multiple rows given condition
[ "", "sql", "" ]
I have a table that I select "project managers" from and pull data about them. Each of them has a number of "clients" that they manage. Clients are linked to their project manager by name. For example: John Smith has 3 Clients. Each of those Clients have his name in a row called "manager". Here's what a simple vers...
You should be able to use a self-join and the `count()` aggregate function to get the result: ``` select t.name, count(t1.name) TotalClients from yourtable t inner join yourtable t1 on t.name = t1.manager group by t.name; ``` See [SQL Fiddle with Demo](http://sqlfiddle.com/#!2/d72a87/2). If you want the result t...
You don't need a join here. A simple `group by` can do the work: ``` Select manager, count(*) as totalClients from yourtable group by 1, order by 2 desc ``` This will list all managers and the number of client's they have. The manager with the most clients comes first. This way you omit the join and the query will be...
SQL count trouble
[ "", "mysql", "sql", "" ]
As I'm sure you'll be able to tell from this question, I am very new and unfamiliar with SQL. After quite some time (and some help from this wonderful website) I was able to create a query that lists almost exactly what I want: ``` Select p1.user.Office, p1.user.Loc_No, p1.user.Name, p1.user.Code, p1.user.Default_...
``` SELECT X.p1.user.Office, X.p1.user.Loc_No, X.p1.user.Name, X.p1.user.Code, X.Default_Freq, X.Last_Paycheck FROM (Select p1.user.Office, p1.user.Loc_No, p1.user.Name, p1.user.Code, p1.user.Default_Freq AS Default_Freq, (Select distinct MAX(p2.pay.Paycheck_PayDate) from p2.pay where p1.user.Client_TAS_...
Use your current query as a derived table or a CTE (CTEs exists for SQL Server 2005+). And then you can do: ``` ;WITH CTE AS ( --- Your current query here ) SELECT * FROM CTE WHERE (Default_Freq = 'W' AND DATEDIFF(DAY,Last_Paycheck,GETDATE()) >= 7) OR (Default_Freq = 'B' AND DATEDIFF(DAY,Last_Paycheck,GETDATE()) >...
SQL: Filtering a query with multiple conditions
[ "", "sql", "sql-server", "" ]
I need to add a primary key on a table "usernames" I have 3 columns in it : ``` userid int(10) username char(20) user char(50) ``` and the primary key is set on 'username' field and i used it as a foreign key to link it to another table. Now i need to add primary key on 'userid' field also... so i tried out : ``` a...
There is: 1. Drop the FK constraint 2. Drop PK Constraint 3. Create New PK 4. Add Unique Constraint on the name column 5. Recreate FK Raj
I assume you use MySql (despite you tag your question as Sql Server). You can decide to: Disable all check and try to remove primary key but the new must have the same name or Drop foreign key constraints referred to your primary key and then remove your primary key and finally re-add foreign keys
adding a primary key when a foreign key already exists
[ "", "mysql", "sql", "sqlite", "mysql-workbench", "" ]
i have the following situation : I need to update customer information on a field in a database specifically on customers not in the EU. I've already selected and filtered the customers, now i've got the following question. There is a field lets call it "order\_note" which i need to update. I know how to do that norm...
``` UPDATE OrderTable SET order_note = 'Careful! Think of XY here. ' + order_note WHERE order_id = 1 ```
``` update customer_information set order_note = 'Careful! Think of XY here!\n' || order_note where customer_region != 'EU' ```
SQL: Update Records without losing their contents
[ "", "sql", "" ]
Suppose we have a table: ``` ╔═════════════════════════════════════╗ ║ Name Date Value ║ ╠═════════════════════════════════════╣ ║ John 2013-01-01 10:20:00 10 ║ ║ John 2013-01-01 12:20:11 20 ║ ║ Mark 2013-01-01 11:44:10 10 ║ ║ Mark 2013-01-02 12:00:00 20 ║ ║ Mark 2...
Try this: ``` SELECT NAME, SUM(CASE WHEN CAST(DATE AS DATE) = '2013-01-01' THEN VALUE ELSE 0 END) [2013-01-01], SUM(CASE WHEN CAST(DATE AS DATE) = '2013-01-02' THEN VALUE ELSE 0 END) [2013-01-02], SUM(CASE ...
If the dates are fixed: ``` SELECT [Name], SUM(CASE WHEN [Date] >= '20130101' AND [Date] < '20130102' THEN Value END) [2013-01-01], SUM(CASE WHEN [Date] >= '20130102' AND [Date] < '20130103' THEN Value END) [2013-01-02], SUM(CASE WHEN [Date] >= '20130103' ...
SELECT SUM () by DISTINCT intervals (Date)
[ "", "sql", "sql-server", "t-sql", "" ]
I have a stored procedure that runs nightly. It pulls some data from a linked server and inserts it into a table on the server where the sql agent job runs. Before the INSERT statement is run, the procedure checks if the database on the linked server is online (STATE = 0). If not the INSERT statement is not run. ``` I...
I don't think there's a way to conditionally prepare only part of a t-sql statement (at least not in the way you've asked about). The underlying problem with your original query isn't that the remote database is sometimes offline, it's that the query optimizer can't create an execution plan when the remote database is...
Unfortunately, the only way to keep sql from preparsing the statement is with dynamic SQL. I have the same issue where I add a column and then want to update it. There is no way to get the script to compile without making the update statement dynamic sql.
prevent error when target database in restore mode (sql preparation)
[ "", "sql", "sql-server-2008", "prepared-statement", "" ]
not sure if the title really makes the question clear but basically I am using "SELECT DISTINCT" in a combobox to look at distinct log times , however the format of the log tim column (which cannot be changed) is example : AUGUST 29th 9:21pm AUGUST 29th 9:22pm This is no good as even using distinct will judge thes...
If the data is stored on a `DATETIME` column and you are one a recent version of SQL-Server, you can cast to `DATE`: ``` SELECT DISTINCT CAST(created_at AS DATE) AS date_created_at FROM SSISLog ; ```
I guess you want something like following ``` SELECT DISTINCT(DATE(created_at)) FROM users; ```
Select distinct values using like
[ "", "sql", "sql-server", "distinct", "" ]
I have a problem here, Have an SSRS report for Bank Transfer see attached ![Bank Transfer Per Bank](https://i.stack.imgur.com/JZwKx.png) I would like to add a row expression which will Sum the total amount of the same bank, i.e, 03001 - Standard Chartered Bank Ltd BJL, 03002 - Standard Chartered Bank Ltd sk and 03002 ...
Have ended up creating a new group the groups bank branches by Banks then create a sum per group. Thank you guys, your answers gave me a new perspective.
You'll need something like this: ``` =Sum(IIf(Fields!BankAName.Value = "Standard Chartered Bank" , Fields!Amount.Value , Nothing) , "DataSet1") ``` This checks for a certain field (e.g. `BankAName`), and if it's a certain value that row's `Amount` value will be added to the total - this seems to be what you...
SSRS Sum Expression with Condition
[ "", "sql", "reporting-services", "ssrs-expression", "" ]
I have this Table which contains **Term** and **TermStartDate** and **TermEndDate**. I have to consider **Todays date** and then check in which term that falls under(Current Term) and then Consider a Date exactly 360 days from the TermEndDate of Current term(Calculated\_Date). Once I get that Date I have to check whic...
I think you are over complicating the problem, but as you requested, try this: ``` DECLARE @terms TABLE(term varchar(50),termStartDate date, termEndDate date) INSERT INTO @terms VALUES('Fall 2012','8/27/2012','12/15/2012') INSERT INTO @terms VALUES('Spring 2013','1/14/2013','4/26/2013') INSERT INTO @terms VALUES('Sumr...
``` DECLARE @lastTermEnd SELECT @lastTermEnd=DATEADD(d,-360,TermEndDate) FROM Students where GETDATE() between TermStartDate and TermEndDate SELECT TOP 1 * from Students WHERE TermStartDate between @lastTermEnd and GETDATE() ORDER BY TermStartDate ``` This will list first term which fall after the calculated date. ...
Date a year from now and check what is the next Term from that Date
[ "", "sql", "sql-server-2008", "t-sql", "" ]
Is it possible to display query results like below within mysql shell? ``` mysql> select code, created_at from my_records; code created_at 1213307927 2013-04-26 09:52:10 8400000000 2013-04-29 23:38:48 8311000001 2013-04-29 23:38:48 3 rows in set (0.00 sec) ``` instead of ``` mysql> select code, create...
> **--raw, -r** For tabular output, the “boxing” around columns enables one column value to be distinguished from another. For nontabular output (such as is produced in batch mode or when the --batch or --silent option is given), special characters are escaped in the output so they can be identified easily. Newline, t...
Not exactly what you need, but it might be useful. Add \G at the end of the query ``` select code, created_at from my_records\G; ``` Query result will look like this: ``` *************************** 1. row *************************** code: 1213307927 created_at: 2013-04-26 09:52:10 *************************** 2. r...
Display query results without table line within mysql shell ( nontabular output )
[ "", "mysql", "sql", "" ]
I have a table that looks like this: ``` create (DATETIME) | Message (TEXT) ========================================= 2013-08-05 9:00:00 "Hi there!" 2013-08-05 10:00:00 "Hi again!" 2013-08-07 14:00:00 "Hi from the future!" ``` I would like to be able to get all messages and group on `DATE(create)` so the messages ...
It is clearer with the example data :) Query #1: 1 group counting from 0 ``` SELECT m1.* FROM messages m1 JOIN ( SELECT DISTINCT date(created) OnlyDate FROM messages ORDER BY OnlyDate LIMIT 0,1 ) m2 ON date(m1.created) = OnlyDate; | CREATED | MESSAGE | |---------------------|-----------| | 2013-...
I think you would need to calculate the group id and do the `limit` manually: ``` SELECT m.* FROM messages m join (select date(create) as createdate, count(*) as cnt, @rn := @rn + 1 as groupnum from messages m cross join (select @rn := 0) const group by date(create) ) md on date(m.create) = ...
Paginating date data in groups
[ "", "mysql", "sql", "group-by", "pagination", "sql-order-by", "" ]
I recently discovered included columns in SQL Server indexes. Do included columns in an index take up extra memory or are they stored on disk? Also can someone point me to performance implications of including columns of differing data types as included columns in a Primary Key, which in my case is typically an in? T...
I don't fully understand the question: "Do included columns in an index take up extra memory or are they stored on disk?" Indexes are both stored on disk (for persistence) and in memory (for performance when being used). The answer to your question is that the non-key columns are stored in the index and hence are stor...
In SQL **Server 2005 or upper versions**, you can extend the functionality of nonclustered indexes by adding nonkey columns to the leaf level of the nonclustered index. By including nonkey columns, you can create nonclustered indexes that cover more queries. This is because the nonkey columns have the following benefi...
SQL Server 2008 included columns
[ "", "sql", "sql-server", "indexing", "" ]
I have data where I need to add leading zeros to it. But the problem is the data type is float. So whenever I add zeros, it automatically omits them. I have tried to add leading zero to it then try to convert it to varchar(50). I used following query (thanks to Mr. Damien\_The\_Unbeliever): ``` select '0' + convert ...
you can use the [str() function](http://msdn.microsoft.com/en-us/library/ms189527.aspx) and trim ``` select '0' + ltrim(rtrim(str(wallet_sys))) as wallet_sys from NewSysData1; ``` [SqlFiddle](http://sqlfiddle.com/#!6/77883/1)
I have done this using the following: ``` select right('00' + convert(varchar, MONTH(getdate())),2) ```
Add leading zero and convert as varchar to a float
[ "", "sql", "sql-server", "" ]
can we use regular expression to select the item from database? The table item is like below ``` Table column|name| 10.01.02 | a | 100.2.03 | b | 1021.10.04 | c | ``` Now my problem is that i need to select the column and get the substring like below ``` Table column|name| 10.01 | a | 100.2 | ...
Try this, ``` SELECT SUBSTRING(column1,0,(CHARINDEX('.',column1,CHARINDEX('.',column1)+1))) FROM Table1 ``` [SQL Fiddle Demo](http://sqlfiddle.com/#!3/bc9ee/8)
``` select left(a, datalength(a) - charindex('.', reverse(a))), b from ( select '10.01.02', 'a' union all select '100.2.03', 'b' union all select '1021.10.04', 'c' ) t(a,b) ``` I think there is no solution with regexp. **UPD** Another solution: ``` select reverse(parsename(reverse(a), 1)) + '.' + revers...
Sql Server select with regular expression
[ "", "sql", "sql-server", "regex", "database", "subquery", "" ]
I have a row in the table `users` with the username `test`. For some reason, though, this query returns an empty result set. ``` SELECT `id` FROM `users` WHERE `username` = "test" AND `id` != null; ``` However, if I remove the `` `id` != null `` segment, the query returns the result `id = 1`. But `1` != `NULL`. How ...
The query doesn't return a row because the predicate " `id != NULL` " will never return TRUE. Th reason for this is that boolean logic in SQL is three valued. A boolean can have values of `TRUE`, `FALSE` or `NULL`. And an inequality comparison will return `NULL` whenever one (or both) of the values being compared is ...
Your method of checking for NULL is probably the issue. In MySQL, try the following: ``` SELECT `id` FROM `users` WHERE `username` = "test" AND `id` IS NOT NULL; ``` To check for NULL and an empty string, you can use: ``` SELECT `id` FROM `users` WHERE `username` = "test" AND (`id` IS NOT NULL OR `id` != ""); ```
Why does this simple MySQL query not return the row?
[ "", "mysql", "sql", "select", "null", "" ]
I have a list of products and a count corresponding to the quantity sold in a single table. The data is laid out as such: ``` Product Name QTY_SOLD Mouse 23 Keyboard 25 Monitor 56 TV 10 Laptop 45 ... ``` I want to create a group ID where groups are created if the R...
When i first saw your question i thought it was a kind of bin-packing problem. But your query looks like you simply want to put your data into **n** buckets :-) Teradata supports the QUANTILE function, but it's deprecated and it doesn't fit your requirements as it creates buckets with equal size. You need WIDTH\_BUCKE...
Create a reference table and join it...then the change only needs to be done in a table (can even create a procedure to help automate the changes to the table later on) Psuedo create: ``` Create table group_nbr (low_limit,upper_limit,group_nbr) ``` Insert your case values into that table and inner join to it using g...
TERADATA Creating Group ID from Rolling SUM Limit
[ "", "sql", "group-by", "sum", "teradata", "" ]
I wrote a stored procedure to import and transform data from one database to another. Each import would take a single company ID and import all data related to this company. To help with the transformation step I use temporary tables. As part of script review, I was told to use table variables rather than temporary ta...
From [`CREATE TABLE`](http://technet.microsoft.com/en-us/library/ms174979.aspx): > Local temporary tables are visible only in the current session and (more importantly): > If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database E...
`##` is used for global temporary tables - will be available to the different imports. `#` is used for local temporary tables and only available in the current/inner scope.
Scope of temporary tables in SQL Server
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have a table in MS Access with rows which have a column called "repeat" I want to `SELECT` all the rows, duplicated by their "repeat" column value. For example, if repeat is 4, then I should return 4 rows of the same values. If repeat is 1, then I should return only one row. This is very similar to this answer: <...
First create a "Numbers" table and fill it with numbers from 1 to 1000 (or up to whatever value the "Repeat" column can have): ``` CREATE TABLE Numbers ( i INT NOT NULL PRIMARY KEY ) ; INSERT INTO Numbers (i) VALUES (1), (2), ..., (1000) ; ``` then you can use this: ``` SELECT t.* FROM TableX AS t JOIN ...
If repeat has only small values you can try: ``` select id, col1 from table where repeat > 0 union all select id, col1 from table where repeat > 1 union all select id, col1 from table where repeat > 2 union all select id, col1 from table where repeat > 3 union all .... ```
How can I select multiple copies of the same row?
[ "", "sql", "ms-access", "" ]
I am working on an SSIS job that contains a complex query. It has some thing like : ``` some sql statements left outer join ( select query joining two more tables ) table1 ``` here, i am unable to understand what that table1 mean ? Is it a kind of temporary view created . This table1 is used in the other...
`table1` is an *alisas* your subquery. It's the name of subquery you can use with columns for example `table1.col1`
**[Here is SQL Fiddel example](http://sqlfiddle.com/#!8/14284/8)** **Below is the sample query** ``` Select Temp1.id,Table1.id Table1_id from Temp1 left Outer join ( Select Temp2.id from Temp2 join Temp3 On Temp2.id = Temp3.id ) Table1 on Temp1.id =...
Unable to understand query
[ "", "sql", "sql-server-2008", "" ]
I have the following query: ``` SELECT DISTINCT YEAR(DateRegistered) as Years, Months.[MonthName], COUNT(UserID)as totalReg FROM Months WITH(NOLOCK) LEFT OUTER JOIN UserProfile WITH(NOLOCK) ON Months.MonthID = MONTH(DateRegistered) AND DateRegistered > DATEADD(MONTH, -12,GETDATE()) GRO...
If you want 12 months of data, then construct a list of numbers from 1 to 12 and use these as offsets with `getdate()`: ``` with nums as ( select 12 as level union all select level - 1 from nums where level > 1 ) select YEAR(thedate) as Years, Months.[MonthName], COUNT(Use...
Try this out: ``` ;With dates as ( Select DateName(Month, getdate()) as [Month], DatePart(Year, getdate()) as [Year], 1 as Iteration Union All Select DateName(Month,DATEADD(MONTH, -Iteration, getdate())), DatePart(Year,DATEADD(MONTH, -Iteration, getdate())), Iteration + 1 from date...
Normalization of Year bringing nulls back
[ "", "sql", "sql-server-2008", "" ]
I've got a many to many table p\_to\_t ``` +----------+-----------+-----------+ | p | t | weight | +----------+-----------+-----------+ | 1 | bob | 40 | +----------+-----------+-----------+ | 2 | sue | 24 | +----------+-----------+-----------+ | 3 | bo...
Just add a `GROUP BY` clause on t ``` SELECT t, SUM(weight) AS sWeight FROM p_to_t WHERE p IN(1,2,4,5) GROUP BY t ``` By the way, you will also get *Sue* with these values in the IN clause... And not `97` for *Bob*, as `40 + 33` are more often `73`
``` SELECT t, SUM(weight) AS sWeight FROM p_to_t WHERE p IN(1,2,4,5) GROUP BY t ``` **[FIDDLE](http://sqlfiddle.com/#!2/da370/1)**
MYSQL Summing of Column With Unique Results
[ "", "mysql", "sql", "group-by", "sum", "" ]
I have the following two tables with the following data. I would like to return all data when the two tables are joined. For instance, `SELECT t1.data, t2.data FROM t1 INNER JOIN t2 ON t2.t1_id=t2.id WHERE t1.id=1;` Now the tricky part. I don't want to return 3 rows but only one, and I would like t2.data to be CSVs. Fo...
You can use [`GROUP_CONCAT`](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat) which concatenates non-null values from a group using a delimiter (comma by default) ``` SELECT t1.data, GROUP_CONCAT(t2.data) FROM t1 JOIN t2 ON t1.id = t2.t1_id WHERE t1.id = 1; ``` Example on SQLFid...
You can use `CONCAT` or `CONCAT_WS` to "stick" column values together and `GROUP_CONCAT` to "stick" row values together. Example: ``` SELECT x, y, z FROM table; ``` Turns into: ``` SELECT GROUP_CONCAT(CONCAT('"', x, '","', y, '","', z, '"') SEPARATOR '\n') FROM table GROU...
INNER JOIN table and return all joined results as CSV (not separate records)
[ "", "mysql", "sql", "" ]
I want to make a query that returns all customers, but match orders only if they were placed in February 2008. This requires a join of tables Customers and Orders. I used two queries and got different answers. The second one is right, but why ? Logically speaking, I was expecting the first one to be right, but its not...
The first query will join Customers and Orders first, then it will filter out all rows as per your WHERE clause That is, customers that don't have a record (For them, orderdate and such will be null) in that date range will be excluded. The second query will return all Customers, but it will only join an Order record ...
The `from` clause is evaluated before the `where` clause. In the first case, if an order has no date in the range, then the results will be filtered out of the query. This means that there are no rows for the customer to include in the output. In the second case, if an order has no date in the range, then it fails th...
Filtering with WHERE while using JOIN?
[ "", "sql", "sql-server", "" ]
I am tracking customer store entry data in Microsoft SQL Server 2008 R2 that looks something like this: ``` DoorID DateTimeStamp EntryType 1 2013-09-02 09:01:16.000 IN 1 2013-09-02 09:04:09.000 IN 1 2013-09-02 10:19:29.000 IN 1 2013-09-02...
``` SELECT [Date] = CONVERT(DATE, DateTimeStamp), DoorID, HourOfDay = DATEPART(HOUR, DateTimeStamp), TotalInPersons = COUNT(*) FROM dbo.tablename WHERE EntryType = 'IN' GROUP BY CONVERT(DATE, DateTimeStamp), DoorID, DATEPART(HOUR, DateTimeStamp) ORDER BY [Date], DoorID, HourOfDay; ``` Of course if y...
How about something like this: ``` SELECT CAST(DateTimeStamp AS DATE) AS Date ,DoorID ,DATEPART(HOUR, DateTimeStamp) AS HourOfDay ,COUNT(*) AS TotalInPersons FROM StoreTable WHERE EntryType = 'IN' GROUP BY CAST(DateTimeStamp AS DATE) ,DoorID ,DATEPART(HOUR, DateTimeStamp) ```
Counting number of rows grouped by date and hour
[ "", "sql", "sql-server", "sql-server-2008-r2", "group-by", "" ]
I have a column in a database where I store pin numbers for a survey. Currently the list of numbers is 5100 - 6674. I need to keep those pin numbers there for a current survey but I also have to add a new list of pin numbers to the same column. I just want to make sure the query that I have created will insert the new ...
I would strongly suggest that you set the `type` at the same time as the pin and fix the increment step: ``` DECLARE @PIN INT; SET @PIN = 8100; WHILE (@PIN <= 8855) BEGIN Insert into Survey(Pin, Type) values (@PIN, @TYPE); set @PIN = @PIN + 1; END; ``` You can also do this with a single statement, if...
Well since you are inserting fewer numbers you can just select a range from the existing set and add a constant: ``` INSERT INTO Survey (PIN, Type) SELECT Pin + 3000, 'TM' FROM Survey WHERE Pin BETWEEN 5100 and 5855 ``` If you were inserting MORE values, you could use the same technique but in batches.
How to insert a list of numbers after an existing list of numbers
[ "", "sql", "" ]
Sorry for this simple question, but looked through some old questions and couldn't find the answer I needed. I have 3 tables all with user\_id (though named differently in each table), and I want to join them together with conditions from each table. I've only done JOIN with 2 tables before, and curious why my below q...
This query should solve your problem : ``` SELECT database_courses.user_id FROM database_all JOIN database_users ON database_all.userid=database_users.userid2 JOIN database_courses ON database_users.userid2=database_courses.userid WHERE database_all.date='2013-09-03' AND database_all.college=...
Try something more like this: ``` SELECT c.user_id FROM database_all AS a JOIN database_users AS u ON a.userid=u.userid2 JOIN database_courses AS c ON b.userid2=c.user_id WHERE a.data='2013-09-03' AND a.college='Harvard' AND c.num_courses<3 ``` Generally you need to put your `WHERE` clause at the end, and the `DBMS...
SQL: joining 3 tables
[ "", "sql", "" ]
Below is an example of the BCP Statement. I'm not accustomed to using BCP so your help and candor is greatly appreciated I am using it with a format file as well. If I execute from CMD prompt it works fine but from SQL I get the error. The BCP statement is all on one line and the SQL Server Agent is running as Local ...
First, rule out an xp\_cmdshell issue by doing a simple 'dir c:\*.\*'; Check out [my blog](http://craftydba.com/?p=1690) on using BCP to export files. I had problems on my system in which I could not find the path to BCP.EXE. Either change the PATH variable of hard code it. Example below works with Adventure Works....
Does the output path exist? BCP does not create the folder before trying to create the file. Try this before your BCP call: ``` EXEC xp_cmdshell 'MKDIR "E:\Storage\Export\Data\"' ```
Unable to open BCP host data-file
[ "", "sql", "sql-server", "bcp", "" ]
I am trying to update 1 column based on if the categories\_id is equal to 90 in a second table but getting an unknown column error. Here is my sql: ``` UPDATE products SET qty='20' WHERE products.products_id = products_to_categories.products_id AND products_to_categories.categories_id = '90' ``` The error I am gett...
In SQL, you have to introduce table names with `from` (or `update` or `delete`) statements. You may mean: ``` UPDATE products SET qty = '20' WHERE exists (select 1 from products_to_categories ptc where ptc.products_id = products.products_id AND ptc.c...
``` UPDATE products p, products_to_categories pc SET p.qty='20' WHERE p.products_id = pc.products_id AND pc.categories_id = '90' ``` **[FIDDLE](http://sqlfiddle.com/#!2/fd62d)**
update statement giving uknown column error
[ "", "mysql", "sql", "" ]
I am using SQL server 2008 and I am trying to unpivot the data. Here is the SQL code that I am using, ``` CREATE TABLE #pvt1 (VendorID int, Sa int, Emp1 int,Sa1 int,Emp2 int) GO INSERT INTO #pvt1 VALUES (1,2,4,3,9); GO --Unpivot the table. SELECT distinct VendorID,Orders,Orders1 FROM (SELECT VendorID, Emp1, Sa,...
An easier way to unpivot the data would be to use a CROSS APPLY to unpivot the columns in pairs: ``` select vendorid, orders, orders1 from pvt1 cross apply ( select emp1, sa union all select emp2, sa1 ) c (orders, orders1); ``` See [SQL Fiddle with Demo](http://sqlfiddle.com/#!3/3f20b/3). Or you can use CROSS APP...
The answer by Taryn is indeed super useful, and I'd like to expand one aspect of it. If you have a very un-normalized table like this, with multiple sets of columns for e.g. 4 quarters or 12 months: ``` +-------+------+------+------+------+------+------+-------+------+ | cYear | foo1 | foo2 | foo3 | foo4 | bar1 | bar...
SQL Unpivot multiple columns Data
[ "", "sql", "sql-server", "sql-server-2008", "unpivot", "" ]
I have a simple table like this: ``` user letter -------------- 1 A 1 A 1 B 1 B 1 B 1 C 2 A 2 B 2 B 2 C 2 C 2 C ``` I want to get the top 2 occurrences of 'letter' per user, like so ``` user letter rank(within user group) ---------------...
``` with cte as ( select t.user_id, t.letter, row_number() over(partition by t.user_id order by count(*) desc) as row_num from Table1 as t group by t.user_id, t.letter ) select c.user_id, max(case when c.row_num = 1 then c.letter end) as "1st-most-occurance", max(case when c.row...
Something like this: ``` select * from ( select userid, letter, dense_rank() over (partition by userid order by count(*) desc) as rnk from letters group by userid, letter ) t where rnk <= 2 order by userid, rnk; ``` Note that I replaced `user` with `userid` because using reserved w...
postgres: get top n occurrences of a value within each group
[ "", "sql", "postgresql", "group-by", "sql-order-by", "greatest-n-per-group", "" ]
I'm trying to write a mysql query and I'm having some issues with it. I'm trying to query WooCommerce data out of my Wordpress database. Basic invoice data is stored in the wp\_posts table and the rest of the data is stored in the wp\_postmeta table. Now 1 inovice in the wp\_posts table points to multiple items in the ...
Welcome to the **[Entity-Attribute-Value](https://perfectsmoked.com/best-gas-smoker/)** world. To have a normal representation of the resultset you might need not only `JOIN` these two tables but also `PIVOT` the resultset. You can do that with a query like ``` SELECT p.id, p.status, MAX(CASE WHEN m.meta_key =...
To start, I would do ``` select a.*, b.* from WP_POSTS a, wp_postmeta b where b.POST_ID = a.id ``` What have you done?
Can't get a complicated mysql query to work
[ "", "mysql", "sql", "wordpress", "woocommerce", "" ]
I have a code where I am pulling language knowledge and each employee has a plan year, they do not all complete them each year and in order to get their most recent one I use the MAX for plan year. Now one of the criteria is whether or not they are willing to move over seas, the issue arises that it will bring up their...
``` SELECT a.Employee_ID, a.Accept_International_Assignment, a.Plan_Year FROM dbo.v_sc08_CD_Employee_Availabilities a INNER JOIN (SELECT Employee_ID, MAX(Plan_Year) maxPlanYear from dbo.v_sc08_CD_Employee_Availabilities GROUP BY Employee_ID) m ON a.Plan_Year = m.maxPlanYear AND a.Employee_ID...
I suspect this will be more efficient than the accepted answer, at scale... ``` ;WITH x AS ( SELECT Employee_ID, Accept_International_Assignment, Plan_Year, rn = ROW_NUMBER() OVER (PARTITION BY Employee_ID ORDER BY Plan_Year DESC) FROM dbo.v_sc08_CD_Employee_Availabilities -- who comes up with these names? ) ...
How to get the MAX result even if the MAX is different
[ "", "sql", "sql-server", "" ]
I have two tables in my access DB, I can join the tables based on their primary key, Grant Number, however both tables contain an expiry date column and I want to see if the expiry dates match. ``` First Table: "Everything2013" Columns: Claim Name, Grant Number, Expiry Date Second Table: "Yukon Claims Govt" ...
``` select E.Claim_Name, E.Grant_Number, Y.StakingDate \ from Everything2013 e inner join Yukon_Claims_Govt y on E.[Grant_Number]=Y.[Grant_number] where E.Expiry_Date=Y.ClaimExpiryDate; ```
I assume you want to get the result set which have same grant number and expiry date from two tables. ``` select Grant_Number,Claim_Name, StakingDate from Everything2013 inner join Yukon_Claims_Govt on Everything2013.Grant_Number=Yukon_Claims_Govt.Grant_Number AND Everything2013.Expiry_Date=Yukon_Claims_Govt.ClaimEx...
Join two tables and compare two columns to see if they are equal
[ "", "sql", "database", "ms-access", "join", "" ]
I'm having a `sql table` with date column named `CREATED_TS` which holds the dates in different format eg. as shown below ``` Feb 20 2012 12:00AM 11/29/12 8:20:53 PM Feb 20 2012 12:00AM 11/29/12 8:20:53 PM Feb 20 2012 12:00AM 11/29/12 8:20:53 PM Nov 16 2011 12:00AM Feb 20 2012 12:00AM ...
As your data already in varchar, you have to convert it into date first: ``` select convert(varchar(10), cast(ts as date), 101) from <your table> ```
Use [`CONVERT`](http://technet.microsoft.com/en-us/library/ms187928%28v=sql.100%29.aspx) with the `Value` specifier of `101`, whilst casting your data to `date`: ``` CONVERT(VARCHAR(10), CAST(Created_TS AS DATE), 101) ```
how to convert date to a format `mm/dd/yyyy`
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
So for each distinct value in a column of one table I want to insert that unique value into a row of another table. ``` list = select distinct(id) from table0 for distinct_id in list insert into table1 (id) values (distinct_id) end ``` Any ideas as to how to go about this?
Whenever you think about doing something in a loop, step back, and think again. SQL is optimized to work with sets. You can do this using a set-based query without the need to loop: ``` INSERT dbo.table1(id) SELECT DISTINCT id FROM dbo.table0; ``` There are some edge cases where looping can make more sense, but as SQ...
``` insert into table1 (id) select distinct id from table0 ```
Insert distinct values from one table into another table
[ "", "sql", "sql-server", "" ]
I have a large CSV file (1.7GB - I believe around 4 million lines). The file is a dump from Cisco IronPort of all traffic for a range. My end goal is to import the text into either SQL/Access, or one of the data modeling applications out there to be able to show browsing habits for the unique ids within the file (actua...
First if you do this: ``` $csv = Import-csv $filename -Delimiter '|' ``` You load the whole file into memory as objects constructed from the fields. So no surprise memory consumption and performance are an issue. The second approach isn't too bad but it should be dumping out in CSV format. As it stands now, it dumps ...
Your second solution works faster because it does not put all the file in memory. You can try to change it like that : ``` $filename = 'Dump.csv' Import-csv $filename -Delimiter '|' | foreach { $_.URL = $_.URL -replace '^\"*(\w*)://([^/]*)/(.*)$','$1://$2'; $_ } |export-csv 'DumpParsed.csv' ```
Efficiently replace text from column within large CSV
[ "", "sql", "powershell", "csv", "" ]
I use below query but says `Incorrect syntax near if` how to solve this problem? ``` CREATE FUNCTION getCustomerAllReseller ( @code BIGINT ) RETURNS TABLE AS RETURN ( WITH Directories AS ( IF (@code < 0) SELECT code FROM CustomerAll WHERE code = @code ELSE SELECT c...
Try this one - ``` CREATE FUNCTION dbo.getCustomerAllReseller ( @code BIGINT ) RETURNS TABLE AS RETURN ( SELECT code FROM dbo.CustomerAll WHERE code = @code AND @code < 0 UNION ALL SELECT code FROM dbo.Customer WHERE code = @code AND @code >= 0 ) ```
The syntax for `with` expects a query, not a statement. You can use conditions in a query with a union: ``` WITH Directories AS ( select code from CustomerAll where @code<0 and code=@code union all Select code from Customer where @code>=0 and code=@code ) SELECT * FROM Directories ```
IF Else in function
[ "", "sql", "sql-server", "t-sql", "" ]
We have a DB that stores details of our contract clients - we need to check every month if they have moved base. So trying to run a query that will return any that have changed homebase in the last month. Using mySQL phpmyadmin localhost via Unix socket, for is set as the month i.e. '07-2013' as VARCHAR. ``` SELECT c...
Here is the solution for anyone interested: ``` SELECT A.employee_ID as crewcode, A.emp_firstname, emp_lastname, B.base, B.base_for AS 'Date' FROM `hs_hr_employee` as A, `employee_base_table` as B where B.base_for=(SELECT DATE_FORMAT(STR_TO_DATE( CURDATE( ) , '%Y-%m-%...
To look for changes in the last 30 days: ``` WHERE mydate > curdate() - interval 30 day ``` To look for changes in the last calendar month: ``` WHERE year(mydate) = year(curdate()) and month(mydate) = month(curdate()) - 1 ```
query for returning the changes in the last month
[ "", "mysql", "sql", "" ]
I have 3 queries which is shared same table, query 1 as below: ``` SELECT MAX(TranDate) AS MaxDate FROM tblTransaction WHERE AccNo = 12345 ``` After get the max transaction date of account 12345, I want to use the max date to find the max transaction ID in query 2 as below: ``` SELECT MAX(TransactionID) AS MaxTran F...
Assuming that `tblTransaction` has `TransactionID` as the primary key, you can use the simpler, for **MySQL**: ``` SELECT Commission FROM tblTransaction WHERE AccNo = 12345 ORDER BY TranDate DESC, TransactionID DESC LIMIT 1 ; ``` and for **SQL-Server**: ``` SELECT TOP (1) Commission FROM tblTransaction WHE...
``` SELECT Commission FROM tblTransaction WHERE AccNo = 12345 AND TransactionID = ( SELECT MAX(TransactionID) AS MaxTran FROM tblTransaction WHERE AccNo = 12345 AND TranDate = ( SELECT MAX(TranDate) AS MaxDate FROM tblTransaction WH...
SQL combine 3 query by using same table
[ "", "mysql", "sql", "sql-server", "" ]
I need to run a query on some data that brings back the moving 12 month total. I've already performed the average function on the data... so now I just need to loop through and get a moving 12 month period of data and SUM it up so I can graph it. Below is the current query i'm issuing but it isn't adding up correctly....
To get the desired result you need to order by `year_dt` column or combination of `year_dt` and `month_dt` columns: ``` select month_dt , year_dt , average_total_rainfall , sum(average_total_rainfall) over(order by year_dt, month_dt rows between 12 precedin...
I think you just need to include the year in the `order by` clause: ``` (SUM (AVERAGE_TOTAL_RAINFALL) OVER (ORDER BY YEAR_DT, MONTH_DT ROWS BETWEEN 12 PRECEDING AND CURRENT ROW)) as "12_MONTH_TOTAL" ```
Query Oracle for 12 month moving total (SUM) of data
[ "", "sql", "oracle", "oracle11g", "analytics", "" ]
Is there any way to get a datetime when the row was created? Is it stored anywhere? I just forgot to add a column which tells when the row was inserted, and lots of rows have been inserted and I don't know when they were inserted... Thanks.
Unfortunately there's no way to achieve that. `MySQL` doesn't store a `timestamp` of row creation, that's why you always have to create a column to do that, along with `ON UPDATE` clause which will update the column every time the row is updated
Nope. You need a column to record that, it's not stored in the system otherwise.
Get the date when the row was inserted MySQL
[ "", "mysql", "sql", "" ]
Please see the table structure below: ``` CREATE TABLE Person (id int not null, PID INT NOT NULL, Name VARCHAR(50)) CREATE TABLE [Order] (OID INT NOT NULL, PID INT NOT NULL) INSERT INTO Person VALUES (1,1,'Ian') INSERT INTO Person VALUES (2,2,'Maria') INSERT INTO [Order] values (1,1) ``` Why does the following query...
The problem here is that you're not using `Table.Column` notation in your subquery, table `Order` doesn't have column `ID` and `ID` in subquery really means `Person.ID`, not `[Order].ID`. That's why I always insist on using aliases for tables in production code. Compare these two queries: ``` select * from Person WHER...
This behavior, while unintuitive, is very well defined in Microsoft's Knowledge Base: [KB #298674 : PRB: Subquery Resolves Names of Column to Outer Tables](http://support.microsoft.com/kb/298674) From that article: > To illustrate the behavior, use the following two table structures and query: ``` CREATE TABLE X1 (...
SQL IN query produces strange result
[ "", "sql", "sql-server", "sql-server-2008", "" ]
In my app,I have a requirement to insert 600 rows and each row have 10 parameters that means I am inserting 6000 data for every 5 seconds.So I am deleting the previous value and inserting 600 rows for every 5 seconds.The other way is I can update the previous data using where Clause.So wondering to know which will have...
I totally agree with Aakash' answer that UPDATE is most probably the faster approach here. --- However I would like to clear up a potential misunderstanding (or lack of understanding) on how a relational database works: > *If i need the data for id 90000 then will the sql server search from beginning ID(ID=1) for ev...
Generally, **UPDATE is much faster** than DELETE+INSERT, it being a single command. The bigger the table (number of and size of columns) the more expensive it becomes to delete and insert rather than update. This is because you have to pay the price of UNDO and REDO. Also, keep in mind the actual fragmentation that o...
Which is faster insert query or update in sql?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
## The goal Add from the 5th value. ## The problem There is a table on my database called `markets`. Within it, there are 5 values: ``` +----+------+ | Id | Name | +----+------+ | 0 | NULL | +----+------+ | 1 | A | +----+------+ | 2 | B | +----+------+ | 3 | C | +----+------+ | 4 | D | +----+------...
On your `INSERT` statement, leave the `auto_increment` field out of the statement. This will leave MySQL to increment it and add it automatically.
Already there are four values are there in the table, So you can just insert next row. it will automatically take 5 as a next value. When we are using auto\_increment no need to specify that column in the insert command. ``` INSERT INTO markets(Name) VALUES('E'); ``` In case if you want to alter the auto\_increment ...
Add from the 5th value
[ "", "mysql", "sql", "" ]
I have a stored procedure that uses a simple UPDATE with some variables passed to it. But I don't want to update those fields when their variables aren't null. This is essentially what my statement looks like. ``` UPDATE myTable SET myColumn = @myColumn, mColumn1 = @myColumn1 WHERE myColumn2 = @myColumn2 ``` Is t...
[`COALESCE`](http://msdn.microsoft.com/en-us/library/ms190349.aspx) is your friend. It returns its first non-NULL argument. I'm not actually sure from your narrative which way around you want things, it's either: ``` UPDATE myTable SET myColumn = COALESCE(myColumn,@myColumn), mColumn1 = COALESCE(myColumn1,@myColum...
Try to use [coalesce](http://technet.microsoft.com/pl-pl/library/ms190349.aspx) function as below ``` UPDATE myTable SET myColumn = coalesce(myColumn,@myColumn), mColumn1 = coalesce(mColumn1,@myColumn1) WHERE myColumn2 = @myColumn2 ``` Above code updates your columns only when they are null. If they are not null ...
Can I check if a variable is NULL within an Update's SET?
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have a table with with two columns as shown below: ``` A001 A1;A2;A3 B002 B1 C003 C1;C2 D004 D1;D2;D3;D4 E005 E1 ``` The table has two columns, the second column has contains either a single value or multiple values as a string separated by a semicolon. What i would like to do is for each of the row...
``` with src as ( select 'A001' col1, 'A1;A2;A3' col2 from dual union all select 'B002', 'B1' from dual union all select 'C003', 'C1;C2' from dual union all select 'D004', 'D1;D2;D3;D4' from dual union all select 'E005', 'E1' fr...
``` select id, txt from table1 model partition by (id) dimension by (1 as n) measures (txt) ( txt[for n from regexp_count(txt[1], '[^;]+') to 1 decrement 1] = regexp_substr(txt[1], '[^;]+', 1, cv(n)) ) order by id, n ``` [fiddle](http://www.sqlfiddle.com/#!4/122f3/1)
SQL - Splitting a string into a new row
[ "", "sql", "plsql", "" ]
I'm having some difficulties trying to get the following to work in SQL Server: ``` CREATE TABLE table_X AS SELECT NEXT VALUE FOR GROUP_A AS GROUP_ID, RISK_ID FROM ( SELECT UNIQUE RISK_ID, FROM table_Y ) SS; ``` I am told: ``` "Incorrect syntax near the keyword 'SELECT'." "Incorrect syntax ...
``` CREATE TABLE Person ( FirstName Varchar(50), LastName Varchar(50) ); /* Insert Some Values Into Person */ CREATE SEQUENCE CountBy START WITH 1 INCREMENT BY 1 ; SELECT NEXT VALUE FOR CountBy OVER (ORDER BY LastName) AS ListNumber, FirstName, LastName INTO table_x FROM Person ```
``` SELECT NEXT VALUE FOR GROUP_A AS GROUP_ID, SS.RISK_ID INTO table_X FROM ( SELECT DISTINCT RISK_ID FROM table_Y ) SS ```
How to make SELECT NEXT VALUE work in SQL Server?
[ "", "sql", "sql-server", "syntax", "syntax-error", "porting", "" ]
I have a script that runs 2 rather slow SQL queries that are almost identical. One selects from the database records that are supposed to be "featured" on a page, i.e. they come first. Another selects from the database the regular records. Each query takes approximately 0.3 seconds, and since both run at the same time,...
You can do this with the `order by` alone: ``` SELECT * FROM records WHERE [other where conditions] ORDER BY (case when features >= $timestamp then featured else $timestamp end) DESC, created desc; ```
You can use [`IF()`](http://dev.mysql.com/doc/refman/5.6/en/control-flow-functions.html) for this. ``` SELECT * FROM records WHERE [other where conditions] ORDER BY IF(featured >= $timestamp, featured, created) DESC ```
MySQL order by value1 unless value1 < 0, then order by value2
[ "", "mysql", "sql", "" ]
I am pretty much new to bcp but I researched quite a bit and can not find any resource that says where we are actually sending the user name and password to the database with this command. So everyone can access the database? ``` bcp AdventureWorks2008.HumanResources.Employee out C:\Data\EmployeeData.dat -T ```
``` bcp AdventureWorks2008.HumanResources.Employee out C:\Data\EmployeeData.dat -T -c -U<login_id> -P<password> -S<server_name\instance_name> ```
You aren't sending the username and password with the -T argument. In fact, it won't send any specified username and password to SQL Server if -T is present in the command line. -T tells BCP to use Windows Authentication to connect to SQL Server. It will operate as the user who's running the command.
Where we are giving password by using BCP command?
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2005", "bcp", "" ]
I'm having a problem with grouping in SQL Server Express 2005 I have a `DATETIME COLUMN` but i want to group it only by date. Here my SQL Statement: ``` SELECT (u.FirstName + ' ' + u.LastName) AS [FullName],d.user_id,CONVERT(varchar,d.log_date,101) AS log_date, min(d.login_time) as LOG_IN, max(d.logout_time) as LOG_...
Just move `convert(varchar,d.log_date,101)` into `group by` clause: ``` select u.FirstName + ' ' + u.LastName as [FullName], d.user_id, convert(varchar, d.log_date, 101) as log_date, min(d.login_time) as LOG_IN, max(d.logout_time) as LOG_OUT, sum(d.totaltime) as TOTHrs from tbldtr d inner ...
Use the casting function so it should become something like: ``` GROUP BY CAST(d.log_date AS DATE) ```
How to group by DATE only in column datetime
[ "", "sql", "sql-server", "" ]
I have a simple table with two columns, like the one below: ``` Id | Name 0 | A 1 | A 2 | B 3 | B 4 | C 5 | D 6 | E 7 | E ``` I want to make a SQL query which will count how many times each "Name" appears on the table. However, I need a few of these values to count as if they were the same. Fo...
You can make translation with `case`. Also, you can use subquery or CTE so you don't have [to repeat yourself](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself): ``` with cte as ( select case Name when 'B' then 'A' when 'E' then 'D' else Name end as Name ...
If you need `A` and `B`, `D` and `E`, to count the same, you can build a query like this: ``` SELECT CASE Name WHEN 'B' THEN 'A' WHEN 'E' THEN 'D' ELSE Name END as Name , COUNT(*) FROM table GROUP BY CASE Name WHEN 'B' THEN 'A' WHEN 'E' THEN 'D' ELSE Name END ``` [Demo on sqlfiddle](http://www.sqlfiddle.com/#!3...
SQL Query with group by clause, but counting two distinct values as if they were the same
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
I have a table within a SQL Server 2008 database called `Meter`. This table has a column called `Name`. Each entry within the column `Name` has a prefix of the following `ZAA\`. I'd like to change this prefix to `ZAA_` without affecting the rest of the text within the column.
``` UPDATE Meter SET Name = 'ZAA_' + SUBSTRING(Name, 4, LEN(Name)) WHERE SUBSTRING(Name, 1, 4) = 'ZAA\' ``` Edit: Or as @Damien\_The\_Unbliever states, to use an index: ``` UPDATE Meter SET Name = 'ZAA_' + SUBSTRING(Name, 4, LEN(Name)) WHERE Name LIKE 'ZAA\%' ``` **EDIT** From your comment, try this statement to f...
MYSQL: ``` UPDATE Meter SET Name = CONCAT('ZAA' ,'_', SUBSTRING(Name, 4, LENGTH(Name))) WHERE Name LIKE 'ZAA\%' ```
Update substring of a column
[ "", "sql", "database", "sql-server-2008", "t-sql", "where-clause", "" ]
I have table called Rule. ``` RuleId Name 1 A1 2 A2 3 A3 . . . ``` Now I want all the names as single result. may be like `@allnames = A1,A2,A3` Can somebody advise how to write query for this without using loops? Thanks in advance...
Try this: ``` SELECT @allnames = STUFF((SELECT distinct ',' + Name FROM table1 FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') , 1, 1, ''); ``` * [SQL Fiddle Demo](http://sqlfiddle.com/#!3/1c24c3/5)
``` DECLARE @names NVARCHAR(MAX) SELECT @names = coalesce(@names + ',', '') + coalesce(Name, '') FROM (SELECT distinct Name FROM Rule) x print @names ```
concatinate all rows of a column into single value
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have a table with currency name, then currency sk. I have a second table with currency\_sk\_from, currency\_sk\_to and conversion\_rate. I want to get a new table which combines this so I get currency\_sk\_from, currency\_name, currency\_sk\_to, currency\_name\_to, conversion\_rate Can someone please help, when I t...
You could try using subqueries instead of joins:- ``` SELECT CURRENCY_SK_FROM, (SELECT CURRENCY_NAME FROM CURRENCY WHERE CURRENCY_SK = CURRENCY_SK_FROM) AS CURRENCY_NAME, CURRENCY_SK_TO, (SELECT CURRENCY_NAME FROM CURRENCY WHERE CURRENCY_SK = CURRENC...
If I have understood the question correctly below query will do the job : ``` SELECT DISTINCT cskf.currency_sk_from, cskfrom.currency_name, cskf.currency_sk_to, cskto.currency_name currency_name_to, cskf.conversion_rate FROM currency_sk cskfrom JOIN currency_sk_from cskf ON c...
Two SK's in one table
[ "", "sql", "join", "" ]
I've read numerous tutorials and graphical representations of MySQL joins, and they still don't make sense to me. I'm trying to type my own now, and they are working, but I just don't see how they're working. Take this set of tables ``` images squares ---------------------------- ------...
Let's start with the `FROM` clause, which in it's entirety is: ``` FROM squares LEFT JOIN images ON images.square_id=squares.square_id ``` (it's not just `FROM squares`). This defines the source of your data. You specify both tables, `squares` and `images` so they are both sources for the data that the query will w...
You should read the query as such: ``` SELECT images.image_id FROM squares LEFT JOIN images ON images.square_id=squares.square_id WHERE images.square_id=711464 ``` So you first join the `squares` table with the `images` table, combining entries in `images` which have the same `square_id` as in the `sq...
SQL Joins - Why does this simple join work, despite the syntax making no sense?
[ "", "mysql", "sql", "join", "" ]
I'm trying to run a query to update the user password using. ``` alter user dell-sys with password 'Pass@133'; ``` But because of `-` it's giving me error like, ``` ERROR: syntax error at or near "-" LINE 1: alter user dell-sys with password 'Pass@133'; ^ ``` Can Anyone shade a light on it?
I have reproduced the issue in my system, ``` postgres=# alter user my-sys with password 'pass11'; ERROR: syntax error at or near "-" LINE 1: alter user my-sys with password 'pass11'; ^ ``` Here is the issue, psql is asking for input and you have given again the alter query see `postgres-#`Th...
Wrap it in double quotes ``` alter user "dell-sys" with password 'Pass@133'; ``` Notice that you will have to use the same case you used when you created the user using double quotes. Say you created `"Dell-Sys"` then you will have to issue exact the same whenever you refer to that user. I think the best you do is t...
syntax error at or near "-" in PostgreSQL
[ "", "sql", "database", "postgresql", "syntax-error", "alter", "" ]
I've inherited a project that somehow ended up with random rows in the application settings table getting duplicated. I got the duplicate rows removed successfully, but then I noticed that the actual values, of type nvarchar, for said rows are also duplicated. For instance, one row has Key column `Error Email Address`...
Here is the query: ``` Update TableName set Col1=substring(Col1,0,charindex(',',Col1)) where substring(Col1,0,charindex(',',Col1))=substring(Col1,charindex(',',Col1)+1,500) ``` Replace Col1 with the column name, and TableName with the actual table name. It will only replace the rows where value before and after comma...
Here is an `update` that would solve the problem: ``` update t set value = left(value, len(val)/2) where left(value, len(val)/2) = right(value, len(val)/2) and substring(value, (len(val)/2) + 1, 1) = ','; ``` You can validate the logic by doing `select` first: ``` select value from t where left(val...
Nvarchar column value is doubled, how do I detect and fix this?
[ "", "sql", "sql-server", "" ]
first time asking a question on Stack Overflow... Amazing resource, but there's just one thing that's really baffling me as a newcomer to SQL. I have three tables and I would like to obtain the names of all the Mentors who are linked to Bob's students. Table 1: TEACHERS ``` ================ ID Name =============...
this should do the work ``` select distinct m.name from students s inner join mentor_ralationships mr on mr.student_id=s.student_id inner join mentors m on m.mentoir_id=mr.mentor_id where s.teacher_id=1; ```
Without joins (not preferred) ``` SELECT mentors.name FROM mentors WHERE mentors.id IN (SELECT MENTOR_RELATIONSHIPS.mentor FROM MENTOR_RELATIONSHIPS WHERE MENTOR_RELATIONSHIPS.student IN (SELECT students.id FROM students WHERE students.teacher = (SELECT teachers.id FROM teachers WHERE teachers.n...
SQL Query (or Join) for 3 tables
[ "", "sql", "join", "inner-join", "" ]
I have two tables both contains "callid,callnumber,callduration"..now i want to get a call which have same callnumber whereas callduration is greater than a given value.i.e ``` Select a.callnumber , b.callnumber from table a INNER JOIN table b ON ( a.callnumber = b.callnumber ...
the join condition in your original sql and your verbal explanation mismatch, so here are two versions: with the durations above a given value as opposed to their difference being greater than the given value: v1: ``` Select a.callnumber , min (a.callduration-b.callduration) mindiff from table a I...
``` Select a.callnumber, b.callnumber From table a Join table b On a.callnumber = b.callnumber And a.callduration - b.callduration > value And a.rowid < b.rowid ``` --- use rowid to avoid repetation of data ( I have tested it on Oracle)
How to select only distinct result based on particular criteria from tables using join
[ "", "mysql", "sql", "" ]
I'm having a very tough time trying to figure out how to do a dynamic pivot in SQL Server 2008 with multiple columns. My sample table is as follows: ``` ID YEAR TYPE TOTAL VOLUME DD1 2008 A 1000 10 DD1 2008 B 2000 20 DD1 2008 C 3000 30 DD1 2009 A 4000 40 DD1 2009 B 5000 50...
In order to get the result, you will need to look at unpivoting the data in the `Total` and `Volume` columns first before applying the PIVOT function to get the final result. My suggestion would be to first write a hard-coded version of the query then convert it to dynamic SQL. The UNPIVOT process converts these multi...
``` declare @stmt nvarchar(max) select @stmt = isnull(@stmt + ', ', '') + 'sum(case when T_YEAR = ''' + T.T_YEAR + ''' and T_TYPE = ''' + T.T_TYPE + ''' then TOTAL else 0 end) as ' + quotename(T.T_YEAR + '_' + T.T_TYPE + '_TOTAL') + ',' + 'sum(case when T_YEAR = ''' + T.T_YEAR + ''' and T_TYPE = ''' ...
SQL Server : dynamic pivot over 5 columns
[ "", "sql", "sql-server", "sql-server-2008", "pivot", "" ]
I'm returning results from a stored procedure and passing them off to a function for further processing. In some cases, it's possible (and perfectly fine) for one of the fields, a date value, to return null. However, whenever I pass the null into the function, an exception is thrown trying to convert the null into the...
You try can making the parameter [`Nullable`](http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2): ``` Public Function MyFunction(ByVal StartDate as DateTime, ByVal EndDate as DateTime?) As Object .... Return something End Function ``` But you might need to call it ...
Use a [nullable](http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1) DateTime parameter: ``` ByVal EndDate AS Nullable(Of DateTime) ``` Full example: ``` Public Function MyFunction(ByVal StartDate as Date, ByVal EndDate as Nullable(Of DateTime)) As Object .... Ret...
How to handle passing DBNull into a function?
[ "", "sql", ".net", "sql-server", "vb.net", "" ]
I have values like something ``` | UserName | SkillsID | |------------|------------------| | Sohil | 1,2,15,16,19, | | Ankur | 5,8,14,19, | | Lalu | 4,3,14,15, | | Vinod | 5, | | Milind | 8,11 | ``` now I want to search the Users who h...
You can do it with [FIND\_IN\_SET()](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set) function or regex: ``` SELECT * FROM t WHERE SkillsID REGEXP '(^|,)5($|,)' ``` But you're violating relation DB principle with storing multiple values in one field. You should create a link table fo...
## Never, never, never store multiple values in one column! As you see now this will only result in problems. Please normalize your DB structure first like this ``` User table +-------------------+ | userid | username | +-------------------+ | 1 | Sohil | | 2 | Ankur | +-------------------+ skil...
mysql db query for comma separate values
[ "", "mysql", "sql", "" ]
In Sweden the second to last digit in the [personal identity number](http://en.wikipedia.org/wiki/Personal_identity_number_%28Sweden%29) is ODD if you are a MAN and EVEN if you are a WOMAN. I want to make this query so that it only selects the women (even numbers). ``` SELECT COL1,COL2,COL3,COL4 FROM TABLE INNER JOIN...
``` WHERE CAST (LEFT(RIGHT(IDNUMBER,2),1) AS INT) % 2 = 0 ```
To pick even numbers, the remainder of the number divided by 2 must be 0, thus: ``` RIGHT(IDNUMBER,2) % 2 = 0 ``` But `RIGHT(IDNUMBER,2)` doesn't return the second last digit, it instead returns the last 2 digits. Divide it by 10 to get what you want: ``` RIGHT(IDNUMBER,2)/10 % 2 = 0 ``` Another way to get the 2 la...
Use a odd number in a condition SQL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have the following tables: ``` +---------+ +-----------+ +---------+ | USER | | USER_BOX | | BOX | | id | | user_id | | id | | name | | box_id | | name | | | | | | | +---------+ +-----------+ +---------+ ``` What I want...
``` SELECT b.id, b.name FROM BOX b LEFT JOIN ( USER_BOX ub JOIN USER u ON (user_id = u.id) ) ON (box_id = b.id) ORDER BY u.id IS NULL, b.id DESC ``` <http://sqlfiddle.com/#!2/a4f304/4/0> EDIT: Actually there's no need to join on `USER`. <http://sqlfiddle.com/#!2/a4f304/7/0>
Something like this: ``` SELECT a.id, a.name FROM BOX AS a LEFT JOIN USER_BOX AS b ON a.id = b.box_id ORDER BY CASE WHEN b.box_id IS NOT NULL THEN 0 ELSE 1 END ,a.id ```
many to many order by relantionship
[ "", "mysql", "sql", "" ]
I have set up a number of different models in my ruby on rails blog project. Currently the different model types are articles, quick tips, quotes and definitions. I've created a page where I would like to display all of these in a single flow ordered by creation time. **The question**: What is a smart/efficient way to...
So the way to do what I want is to make a superclass, say Post, and have all other content types inherit from this Model. This will create a Single Table Inheritance scheme where all of the subclasses attributes are kept in the "posts" table together with a "type" attribute which facillitates differentiating between th...
Just combine them. ``` (Tip.all + Quote.all + Article.all + Definition.all).order_by(:created_at).limit(10) ``` Or ``` tips = Tips.all.limit(10) quotes = Quotes.all.limit(10) (tips + quotes).order_by(:created_at).limit(10) ``` Get the idea? [Possibly useful similar question](https://stackoverflow.com/questions/749...
Retrieving many different kinds of models from the database at the same time
[ "", "sql", "ruby-on-rails", "ruby", "activerecord", "ruby-on-rails-4", "" ]
**ERROR MESSAGE: #1215 - Cannot add foreign key constraint** hello i can't create table foreign key... how to do this... i have two table.. the first table got two primary key then the 2nd table is 1 primary key... the first table is `courseid varchar(5)` and `courseyear int` and the second is `subj_id varchar(5)` ``...
Here it is sample [SQLFiddle](http://sqlfiddle.com/#!2/e850e) You have mandatory to add `primary key (subj_id)` in your `studentload` table In your foriegn relationship courseid is not tablename. It should be ``` "references course(courseid,courseyear)" ``` Like ``` CREATE TABLE IF NOT EXISTS `course` ( `coursei...
You have used "references `courseid`(`courseid`,`courseyear`) ". courseid is not your tablename. It should be "references `course`(`courseid`,`courseyear`) "
cannot add foreign key constraint
[ "", "mysql", "sql", "" ]
I have a large table with 100,000,000 rows. I'd like to select every n'th row from the table. My first instinct is to use something like this: ``` SELECT id,name FROM table WHERE id%125000=0 ``` to retrieve a even spread of 800 rows (id is a clustered index) This technique works fine on smaller data sets but with my...
If `id` is in an index, then I am thinking of something along these lines: ``` with ids as ( select 1 as id union all select id + 125000 from ids where id <= 100000000 ) select ids.id, (select name from table t where t.id = ids.id) as name from ids option (MAXRECURSION 1000); ```...
The time is not going into the modulus operation itself, but rather into just reading 124,999 unnecessary rows for every row that you actually want (i.e., the Table Scan or Clustered Index Scan). Just about the only way to speed up a query like this is something that seems at first illogical: Add an extra non-Clustere...
SQL server modulus operator to skip to every n'th row on a large table
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I'm working in Access 2010. I have the following query (which is named bird\_year\_species): ``` SELECT sub.Species, Min(sub.obs_year) AS First_sighting_year FROM (SELECT DISTINCT [Genus_BiLE] & " " & [Species_BiLE] AS Species, [Year_BiLE] AS obs_year FROM BiLE_Bound UNION ALL SELECT DISTINCT [Genus_BiMN] & " " & ...
I tried copying the code into a new query. I tried compacting an repairing. I tried saving the database under another name. Non of which worked. Eventually I opened the query, switched out of SQL view and into design view, back to SQL view and voila, that appeared to do it. So strange.
When this happens, check your properties, specifically look for references to Queryx in the filter and order by fields.
Why is this query asking for a parameter value?
[ "", "sql", "parameters", "ms-access-2010", "" ]
If I use an update statement in an update trigger, does that update statement in update trigger causes fire trigger?
Make sure your database property for `RECURSIVE_TRIGGERS` is set to off (which is the default anyway) so that it cannot be fired recursively. <http://technet.microsoft.com/en-us/library/ms190946.aspx>
By default, a trigger doesn't fire himself.
Does an update statement in update trigger, fire trigger again?
[ "", "sql", "sql-server", "triggers", "" ]
I am attempting to write an SQLite Query that orders a table `mytable` firstly by a column called `status_id` and secondly by a column called `name`, but with an extra constraint using: ``` SELECT name, status_id FROM mytable ORDER BY status_id, name ``` produces a table that is correctly sorted. e.g (name...
You still need to sort by status\_id and name, AFTER you sort by the CASE statement. ``` SELECT name , status_id FROM mytable ORDER BY CASE WHEN status_id = 2 THEN 1 ELSE 0 END DESC ,status_id ,name ```
Just sort the rest by `status_id` and add `name` yo your `ORDER BY`: ``` SELECT name, status_id FROM mytable ORDER BY CASE status_id WHEN 2 THEN -1 ELSE status_id END, name ```
Sort SQL based on two fields and extra constraint
[ "", "sql", "sqlite", "" ]
I am creating a SQL query in which I need a conditional `where` clause. It should be something like this: ``` SELECT DateAppr, TimeAppr, TAT, LaserLTR, Permit, LtrPrinter, JobName, JobNumber, JobDesc, ActQty, (ActQty-LtrPrinted) AS L, (ActQty-QtyInserted) AS M, ((A...
Try this ``` SELECT DateAppr, TimeAppr, TAT, LaserLTR, Permit, LtrPrinter, JobName, JobNumber, JobDesc, ActQty, (ActQty-LtrPrinted) AS L, (ActQty-QtyInserted) AS M, ((ActQty-LtrPrinted)-(ActQty-QtyInserted)) AS N FROM [test].[dbo].[MM] WHERE DateDropped = ...
Try this one - ``` WHERE DateDropped = 0 AND ( (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0) OR (ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0) ) ```
Conditional WHERE clause in SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "where-clause", "" ]
I have three tables (didn't create the database). They are essentially the same but with slightly different data, they have Company\_Id and Category\_Id. I also want to link the Category Name to this table, so I have to join in Category. Before the join this worked ``` Select Distinct CompanyId, Category_ID From Produ...
The `where` goes after the `from` clause. The `join` keyword is part of `from`, so it needs to go before `where`: ``` Select CompanyId, Category_ID From Product1 inner join Category on Category.Id = Product1.Category_ID where Product1.CompanyId = 10 union Select CompanyId, Category_ID From Product2 From Pro...
``` Select distinct CompanyId, Category_ID From Product1 inner join Category on Category.Id=Product1.Category_ID where Product1.CompanyId = 10 union Select distinct CompanyId, Category_ID From Product2 inner join Category on Category.Id=Product2.Category_ID where Product2.CompanyId = 10 union Selec...
Join Multiple tables (basically the same table) with Joins
[ "", "sql", "sql-server", "t-sql", "join", "" ]
I have a single value of 9/1/2013 for a mailing date. I also have 50 row primary key IDS that need to be updated with this single mail date of 9/1/2013. ``` UPDATE myTable SET MailingDate = CONVERT(DATETIME, '2013-09-01 00:00:00', 102) WHERE (tblID = 1) OR (tblID = 2) OR ...
You can use `IN` It should be fine for 50 values. If you expect hundreds or thousands of values then you should find some other way like temp table. ``` UPDATE myTable SET MailingDate = CONVERT(DATETIME, '2013-09-01 00:00:00', 102) WHERE tblID IN ( 1, 2,3,...) ``` If you are picking your ids from the res...
You can use something like this: ``` UPDATE myTable SET MailingDate = CONVERT(DATETIME, '2013-09-01 00:00:00', 102) WHERE tblID IN (Select tblID from myTable WHERE <some condition>) ``` the "some condition" is how you could list which ID's should be changed.
Update multiple rows using single value
[ "", "mysql", "sql", "t-sql", "sql-update", "" ]
I have a query join 2 table as below: ``` SELECT * FROM Staff s INNER JOIN Account a on s.AccNo = a.AccNo WHERE a.Status = 'Active' ``` The result as shown: ``` AccNo | Name | ID ------------------ 1 | Alex | S01 2 | John | S02 ``` After I get the staff ID,I write second query to find out the max sale ...
You can create a subquery and join it: ``` SELECT a.AccNo, b.Name, b.ID, c.maximum FROM transaction as a INNER JOIN Account as b ON a.AccNo = b.AccNo LEFT JOIN (SELECT StaffID, Max(Amount) as maximum FROM Sales GROUP BY StaffID) as c ON c.StaffID = b.ID WHERE b.Status = 'Active' ``` See the [SQLFiddle example](ht...
I think this should work Just do a join and retrieve the max amount associated with each staff SELECT t.AccNo , t.Name, t.ID, s.ProductID, Max(s.Amount) FROM Transaction t INNER JOIN Account a ON t.AccNo = a.AccNo INNER JOIN Sales s ON s.StaffID = a.ID WHERE a.Status = 'Active'; Thanks
Pass value from query 1 to query 2
[ "", "mysql", "sql", "sql-server", "" ]
In this procedure, the user passes one project ID. I'd like to be able to pass an indeterminate number of project IDs so I can change the where clauses from "ProjectID=@projectID" (for example) to "ProjectID IN (@ProjectID)". That way, I can delete a dozen projects with one call to the DB, rather than calling the DB r...
The only way I have been able to pass multible values to a stored procedure is to concat them to a string and pass the string to the SP and then parse the string in the beginning of the SP, something like this (the projetc\_id's are delimeted with , ``` CREATE PROCEDURE [dbo].[cpas_DeleteProject] @ProjectID varchar(...
Although it's possible to use table valued parameters in SQL Server, there's no way easy way of populating those parameters from Access, as far as I know. A solution could be to use dynamic SQL inside your Stored Procedure, and then having the project ID's in a varchar(max) that is created inside your Access applicati...
Parameter to populate an "IN" clause
[ "", "sql", "t-sql", "stored-procedures", "ms-access-2007", "" ]
I've been looking around for a while, and it seems it cant be found anywhere. I want to know how do you select the 100 highest and the 100 lowst values in a column? The MIN-function only chooses the lowest one and the MAX the highest one. Anyone out there who knows how you do this?
SQL Server * Top 100 Highest ``` SELECT TOP 100 * FROM MyTable ORDER BY MyCol DESC ``` * Top 100 Lowest ``` SELECT TOP 100 * FROM MyTable ORDER BY MyCol ASC ``` MySQL * Top 100 Highest ``` SELECT * FROM MyTable ORDER BY MyCol DESC LIMIT 100 ``` * Top 100 Lowest ``` SELECT * FROM MyTab...
You can do it as below, **Highest** ``` select * from tablename order by column DESC limit 0,100 ``` **Lowest** ``` select * from tablename order by column ASC limit 0,100 ``` **EDIT** For SQL Server replace `select * from` with `select TOP 100 * from` The `SELECT TOP` clause is used to specify the number of rec...
Select the 100 lowest values in SQL?
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]