Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have some data like ``` code amount month aaa1 100 1 aaa1 200 2 aaa1 300 3 aaa4 450 2 aaa4 400 3 aaa6 0 2 ``` From the above, for each code I want to get the row with max(month) ``` code amount month aaa1 300 3 aaa4 400 3 aaa6 0 2 ``` How ...
``` ;WITH MyCTE AS ( SELECT code, amount, month, ROW_NUMBER() OVER(PARTITION BY code ORDER BY code,month DESC) AS rownum FROM table ) SELECT * FROM MyCTE WHERE rownum = 1 ```
You can use the [ranking function](http://technet.microsoft.com/en-us/library/ms189798.aspx) [**`ROW_NUMBER()`**](http://technet.microsoft.com/en-us/library/ms186734.aspx) with `PARTITION BY code ORDER BY month DESC` to do this: ``` WITH CTE AS ( SELECT code, amount, month, ROW_NUMBER() OVER(PARTITION BY...
Get the row with max(column) for distinct key
[ "", "sql", "sql-server-2008", "" ]
I need to check in MySQL to see if two date intervals intersect. To explain better my issue: I have an event management module. If we have an event that was added like this: > start date : `'2013-09-09 08:00:00'` > > end date : `'2013-09-09 10:00:00'` and now I want to add another event that's like this: ## case A: ...
Test just that the start times of already assigned time blocks or the to be assigned time block do not fall between each other. ``` select * from `events` as e where '2013-09-09 08:00:00' between e.ev_date_start and e.ev_date_end or e.ev_date_start between '2013-09-09 08:00:00'and '2013-09-09 11:00:00' ```
The idea is to check if they DO NOT intersect, and then negate. ``` NOT ('2013-09-09 08:00:00' >= e.ev_date_end OR e.ev_date_start >= '2013-09-09 11:00:00') ``` which is logically equivalent to ``` '2013-09-09 08:00:00' < e.ev_date_end AND e.ev_date_start < '2013-09-09 11:00:00' ```
Check if two date intervals intersect
[ "", "mysql", "sql", "select", "" ]
Is there a way I could keep track of modified tables in Oracle? Is there a master table that keeps track of all other table's row? For example if I add a row to table1 it would update the row count stating that table1 now has 5 rows. I was thinking of tracking either `dba_tables` or `all_tables` or `user_tables` but ...
``` SELECT TABLE_NAME, NUM_ROWS FROM USER_TABLES ``` I highly doubt you're actually using Oracle 3.1. This query works at least in 11g (I don't have other instances to test at the moment). Keep in mind that this is a data dictionary table and it won't update automatically after you insert a row in any schema table. T...
You can get an improvement on the just querying user/all/dba\_statistics by combining them with information gathered by table monitoring. The views DBA/ALL/USER\_TAB\_MODIFICATIONS are populated with the number on insets, updates, deletes and truncates on the table since statistics were last gathered. The view is popu...
Tracking row numbers in Oracle
[ "", "sql", "oracle", "" ]
When I use this mysql code ``` update catalog_product_entity_decimal set value = "6.0000" where attribute_id = 75 and entity_in ( SELECT product_id from `catalog_category_product` WHERE category_id =37 ); ``` i'm getting this error ``` #1064 - You have an error in your SQL syn...
You are missing the IN clause after entity\_in. Use this: ``` update catalog_product_entity_decimal set value = "6.0000" where attribute_id = 75 and entity_id IN ( SELECT product_id from `catalog_category_product` WHERE category_id =37 ); ```
I think catalog\_category\_product will not contain the ' symbol. Try the query without using the ' symbol
#1064 Syntax Error : In "Update Query"
[ "", "mysql", "sql", "" ]
I'm completely stumped. I have the following block: ``` IF NOT EXISTS(SELECT * FROM sys.schemas WHERE name = 'Test') BEGIN CREATE SCHEMA Test; END; ``` If I run this against our SQL Server 2008, I get "Msg 156, Level 15, State 1, Line 3: Incorrect syntax near the keyword 'SCHEMA'" but if I run just the `CREATE SC...
The error message is a bit of a red herring here.... Execute the following to see what the "real" error is: ``` SELECT * FROM sys.schemas CREATE SCHEMA Test ``` > Msg 111, Level 15, State 1, Line 2 > > > 'CREATE SCHEMA' must be the first statement in a query batch. To get around this problem you can use the `EXEC` f...
If you need to create schema in another database rather than current context, you should run following script. ``` set @myScript = 'exec '+ QUOTENAME(@DBName) + '..sp_executesql N''create schema MySchema''' execute(@myScript) ```
Can't create schema inside begin block
[ "", "sql", "sql-server", "" ]
I have a store procedure which i have planned to use for search and get all values. **Scenario:** If the parameter passed is `NULL` it should return all the values of the table and if the parameter passed is not `NULL` it should return the values according to the condition which is in LIKE. //Query: ``` ALTER proced...
You can use condition like this in you `where` clause ``` where @Keyword is null or CustomerName like '%' + @Keyword + '%' ```
I just want to point out another way of solving this problem. The issue is that the default value for `@KeyWord` is `NULL`. If you change the default to `''`, then the problem goes away: ``` ALTER procedure [dbo].[usp_GetAllCustomerDetails] ( @Keyword nvarchar(20) = '' ) ``` Any non-NULL customer name would then be l...
LIKE and NULL in WHERE clause in SQL
[ "", "sql", "sql-server", "sql-server-2008", "where-clause", "sql-like", "" ]
In something I need to work on, at a given time, I need to find all nodes of a tree (made using the materialized path + adjacent nodes) that have 0 or 1 children. The columns are something like: ``` id int parent_node int treepath VARCHAR(255) deepness int ``` When I try to come up with a solution to this, I'm ...
Without sample data, this is just a guess: ``` SELECT t1.*, t2.numchildren FROM user_tree t1 LEFT JOIN ( SELECT parent_id, COUNT(*) AS numchildren FROM user_tree GROUP BY parent_id ) t2 ON t1.id = t2.parent_id WHERE t2.numchildren IS NULL OR t2.numchildren = 1; ``` [SQL-Fiddle from sample data...
Query ``` SELECT parent_id, COUNT(id) AS n FROM user_tree GROUP BY parent_id HAVING n = 1 ``` finds parents having one child. You may want to add INDEX(parent\_id). Query ``` SELECT id FROM user_tree WHERE id NOT IN (SELECT DISTINCT parent_id FROM user_tree) ``` finds leaves. The same index will help.
Find all nodes within a subtree that has 0 or 1 children
[ "", "mysql", "sql", "" ]
I am trying to update a database via an update query,but I am getting an error that says ``` Error com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'add=null,col=null,wok=null...
ADD is a reserved word in mysql use backticks ``` \`add\`=? ``` <http://dev.mysql.com/doc/mysqld-version-reference/en/mysqld-version-reference-reservedwords-5-5.html>
ADD is reserved word. Please quote it or change field name
Error in SQL Update Syntax
[ "", "mysql", "sql", "jsp", "" ]
Is there a way to drop all objects in a db, with the objects belonging to two different schemas? I had been previously working with one schema, so I query all objects using: ``` Select * From sysobjects Where type=... ``` then dropped everything I using ``` Drop Table ... ``` Now that I have introduced another sch...
Use [`sys.objects`](http://technet.microsoft.com/en-us/library/ms190324.aspx) in combination with [`OBJECT_SCHEMA_NAME`](http://technet.microsoft.com/en-us/library/bb326599%28v=sql.110%29.aspx) to build your `DROP TABLE` statements, review, then copy/paste to execute: ``` SELECT 'DROP TABLE ' + QUOTENAME(OBJECT...
Neither of the other questions seem to have tried to address the **all objects** part of the question. I'm amazed you have to roll your own with this - I expected there to be a drop schema blah cascade. Surely every single person who sets up a dev server will have to do this and having to do some meta-programming befo...
Drop all objects in SQL Server database that belong to different schemas?
[ "", "sql", "sql-server", "database-schema", "" ]
I want to use the following SQL statements in a VB.NET app: ``` select * from information_schema.parameters where specific_name='GetTaskEvents' SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME= 'GetTaskEvents' ``` I spoke to the DBA about it today and he seemed unkeen, but did not give a reas...
If you know what the stored procedure *is* but not sure what the parameters are - a better way to use [SqlCommandBuilder.DeriveParameters](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder.deriveparameters.aspx) method to get the number of parameters as well as their types and names. *UPD...
Best practice should come down to what kind of risk you are willing to expose your company to in order to get the type of data you need. Risk / benefit analysis. In this case the risk I see is that you are making your code depend on Microsofts behind the scenes system tables and schemas. These do tend to change from v...
Using system tables in VB.NET
[ "", "sql", "vb.net", "" ]
I want to get all selected columns from a single select statement without performing the execution . The query may use join or union , then the query may consist more than just one table , so I can not simply use the statement ``` select column_name, data_type from user_tab_cols where table_name = 'my_table_name' ``` ...
There is no easy way to do it using a single select statement, however, you can look into `dbms_sql` approach ([DOC](http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_sql.htm#i997238)). ``` 14:32:26 SYSTEM@dwal> ed Wrote file S:\spool\dwal\BUFFER_SYSTEM_329.sql 1 DECLARE 2 c NUMBER; 3 ...
I believe there is no option to find the datatype in the query. Instead you have to make a `create table as` or to `create view as` clause with the query and use then desc or some data dictionaries like user\_tab\_cols.
oracle 10g get all selected columns and datatype from a single select statement
[ "", "sql", "oracle", "" ]
Is it possible to write a query to loop through the rows of a two column table, checking the first column for a certain identifier and copy the data in the second column into a new table? Example: ``` tblSurveyData FirstColumn Second Column A0 John A2 Smith A3 05-01-1973 tb...
Use [INSERT INTO](http://msdn.microsoft.com/en-us/library/office/bb208861%28v=office.12%29.aspx) with a SELECT statement ``` INSERT INTO tblSurveyReport(FirstName) SELECT FirstName FROM tblSurveyData where FirstColumn = 'A0' INSERT INTO tblSurveyReport(MiddleName) SELECT MiddleName FROM tblSurveyData where FirstColum...
You will need something that would link your records together. What happens if the data gets re-sorted? How would you know that all the info in your example should be in the same record? I believe the only way to do something like this would be to create a 3rd field in your first table that determines which data belong...
Access query or VBA code to move data from one table to another depending on first row unique identifier
[ "", "sql", "vba", "ms-access", "" ]
Think I have two table and each table have one index . now I join tables by indexed column my question is that is there any different on time whether each table have 100 rows or 1 million rows ?
Let say you are searching for your a book in a library. Is there any different on time whether the library has 100 books or has 100 million books? Even the library nicely organize the book by category and by alphabetical order. It makes different. Computer is nothing different from us human, just it can perform some ta...
Of course there is a difference (And this is one reason why you should never use a developement database that has significantly fewer records than the production database, you don't want to find performance problems when you push to Prod). First assume you are going to return all the records. If you have 100 record ta...
Different between 100 rows and 100 million rows
[ "", "mysql", "sql", "sql-server", "" ]
Two parameters that allow user to choose either one to sort data. ``` SELECT comment, comment_type,user FROM comments WHERE (comments.comment_type = @ctype) OR (comments.user = @user) ``` The user must be able to select each commenttype or user from available values dropdown. The problem is ssrs will not let me leave...
How about ``` (comments.comment_type = @ctype AND comments.user IS NOT NULL) OR (comments.comment_type IS NOT NULL AND comments.user = @user) ```
You should check `Allow null value` in `Report parameters` window. Than you can try your query or below query. ``` SELECT comment, comment_type,user FROM comments WHERE (comments.comment_type = coalesce(@ctype,comments.comment_type)) OR (comments.user = coalesce(@user,comments.user)) ``` [**More information**](http:...
How to implement two parameters that are each optional with available values for each parameter?
[ "", "sql", "sql-server", "t-sql", "reporting-services", "" ]
I want an SQL code which should perform the task of data scrubbing. I have two tables both contain some names I want to compare them and list out only those name which are in table 2 but not in table 1. Example: ``` Table 1 = A ,B,C Table 2 = C,D,E ``` The result must have D and E?
``` select T2.Name from Table2 as T2 where not exists (select * from Table1 as T1 where T1.Name = T2.Name) ``` See [**this article**](http://www.sqlperformance.com/2012/12/t-sql-queries/left-anti-semi-join) about performance of different implementations of anti-join (for SQL Server).
``` SELECT t2.name FROM 2 t2 LEFT JOIN 1 t1 ON t1.name=t2.name WHERE t1.name IS NULL ```
Compare two tables and give the output record which does not exist in 1st table
[ "", "sql", "" ]
In My WHERE Clause I am using a CASE that will return all rows if parameter is blank or null. This works fine with single valuses. However not so well when using the IN clause. For example: This works very well, if there is not match then ALL records are returned! ``` AND Name = CASE WHEN @Name_ != '' THEN @Name_ EL...
Maybe `coalesce` will resolve your problem ``` AND Name IN (Select Names FROM Person Where Names like coalesce(@Name,Name)) AND ``` As Mattfew Lake said and used, you can also use `isnull` function ``` Name IN (Select Names FROM Person Where Names like isnull(@Name,Name)) ```
You should almost definitely use an IF statement with two selects. e.g. ``` IF @Name IS NULL BEGIN SELECT * FROM Person END ELSE BEGIN SELECT * FROM Person --WHERE Name LIKE '%' + @Name + '%' WHERE Name = @Name END ``` N.B. I've changed like to...
Using a CASE with the IN clause in T-SQL
[ "", "asp.net", "sql", "t-sql", "case", "where-clause", "" ]
What kind of relational algebra operator would a [LOAD](http://dev.mysql.com/doc/refman/5.0/en/load-data.html) keyword be mapped into? If it it's not a logical operator but only a physical one then how is it handled during the logical to physical operator transformation process by the database query processor? Or, if i...
The `LOAD` keyword is internally mapped in the database after query parsing into a *logical* operator but it's not an *algebra* operator. All algebra operators are logical operators but not all logical operators are algebra operators.
You have got to distinguish between algebraic operators such as natural join, transitive closure, ... and keywords/commands of the data manipulation language. Algebraic operators do computations on given values, and return the computed value as their result. And then you have programming and data manipulation languag...
Is LOAD a relational algebra operator?
[ "", "mysql", "sql", "relational-database", "relational-algebra", "first-order-logic", "" ]
I have a table like this : ``` Server CompliancePercentage A 25 B 15 C 45 D 75 E 17 F 82 ``` I want to get from a single query the results in the following way: ``` Conformity% 00-20 20-40 40-60 60-80 80-100 Server Cou...
You can use an aggregate function with a CASE expression to get the result: ``` select 'ServerCount' Conformity, count(case when CompliancePercentage >= 0 and CompliancePercentage <20 then 1 end) Per00_19, count(case when CompliancePercentage >= 20 and CompliancePercentage <40 then 1 end) Per20_39, count(case ...
Assuming the following table: ``` create table dummyTable ( srv char(1), comp int ) ``` You can write out the query similar to ``` select [00-19] = (SELECT COUNT(1) FROM dummyTable where comp between 0 and 19), [20-39] = (SELECT COUNT(1) FROM dummyTable where comp between 20 and 39) ``` If your tab...
Nested SQL Queries: How to get multiple counts on same elements based on different criteria
[ "", "sql", "" ]
I have a table of customer ID's and a table of customer data. A customer can change ID's, but I want to query their earliest date in some cases, and the latest date in others. For example, I have two tables: ``` tbl_a id active_id a aa b aa c aa d bb e bb tbl_b id ...
If you can use windowed functions (and don't have access to `first_value` function): ``` with cte as ( select row_number() over(partition by a.active_id order by b.date asc) as rn1, row_number() over(partition by a.active_id order by b.date desc) as rn2, a.active_id, b.date, b.city from...
Try something like this: ``` ;WITH DATA AS (SELECT T1.ACTIVE_ID, T2.* FROM TABLEA T1 INNER JOIN TABLEB T2 ON T1.ID = T2.ID), DATA2 AS (SELECT T1.ACTIVE_ID, SUM(T2.VALUE) TOT_VALUE FROM TABLEA T1 ...
Most Efficient Way to Process Subquery For First Record
[ "", "sql", "sql-server", "" ]
I have the following 3 Oracle Database Tables: ``` application (app_id, application_name) ``` eg. (1, firstapp) ``` item_request (app_id, item_id, qty_requested) ``` eg. (1, 111, 5), (1, 112, 3), (1, 113, 7) ``` item (item_id, item_code) ``` eg. (111, "COMPUTER"), (112, "PHONE"), (113, "DESK") I want to produce ...
You can achieve this using dynamic SQL, e.g. with a ref cursor. You have to a)iterate over all existing items b)build your SELECT list by adding all items c)perform the pivoting (either by using PIVOT or with the traditional MAX / CASE / GROUP BY) approach ``` create table application(app_id number primary key, app...
Oracle has limited support for Pivot functions. See e.g. <http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html>. In short, for regular output you are stuck with having a static list of columns that you are pivoting into. For dynamic pivot tables you can use the pivot xml function. But this produces t...
Oracle Database - Dynamic number of columns
[ "", "sql", "oracle", "dynamic", "" ]
How to set row level lock in Informix?
``` CREATE TABLE customer(customer_num serial, lname char(20)...) LOCK MODE ROW; ``` Read more here: [Row and Key Locks](http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.perf.doc/perf227.htm)
You can use: ``` ALTER TABLE customer LOCK MODE(ROW); ``` (PAGE is the default) More [here](http://www.ibm.com/support/knowledgecenter/SSGU8G_12.1.0/com.ibm.sqls.doc/ids_sqs_0083.htm). If you want to find the current lock mode of a table: ``` SELECT tablename, lockmode FROM systables ```
How to set row level lock in Informix?
[ "", "sql", "locking", "informix", "" ]
I have a table like below - ``` Student ID | History | Maths | Geography 1 A B B 2 C C E 3 D A B 4 E D A ``` How to find out how many students got A in history, B in maths and E in Geography with a...
If you want to get number of students who got A in History in one column, number of students who got B in Maths in second column and number of students who got E in Geography in third then: ``` select sum(case when [History] = 'A' then 1 else 0 end) as HistoryA, sum(case when [Maths] = 'B' then 1 else 0 end) a...
If you want independent counts use: ``` SELECT SUM(CASE WHEN Condition1 THEN 1 ELSE 0 END) AS 'Condition1' ,SUM(CASE WHEN Condition2 THEN 1 ELSE 0 END) AS 'Condition2' ,SUM(CASE WHEN Condition3 THEN 1 ELSE 0 END) AS 'Condition3' FROM YourTable ``` If you want multiple conditions for one count use: ``` SE...
multiple count conditions with single query
[ "", "sql", "" ]
I have a stored procedure where want check that a date is between a fixed date and the current date/time (with `GETDATE()`): ``` SELECT a, b FROM myTbl WHERE DATE BETWEEN 'Day start datetime' AND GETDATE() ``` ...for example : ``` WHERE DATE BETWEEN '2013-09-10 00:00:00.00' AND 'GETDATE()' ``` How to do...
A pair of `DATEADD`/`DATEDIFF` calls will round a date down to the previous midnight: ``` SELECT a , b FROM myTbl WHERE DATE BETWEEN DATEADD(day,DATEDIFF(day,0,GETDATE()),0) and GETDATE() ``` Alternatively, if you're on SQL Server 2008 or later: ``` SELECT a , b FROM myTbl WHERE DATE BETWEEN CONVERT(date,GETDATE()) ...
`'GETDATE()'` is a string literal, `GETDATE()` is a `T-SQL` function. Your query should look like: ``` SELECT a , b FROM myTbl WHERE DATE BETWEEN '2013-09-10 00:00:00.0' and GETDATE() ```
Check date between two dates in T-SQL
[ "", "sql", "sql-server", "t-sql", "between", "" ]
I have a large database with 300,000 rows (1.6 GB). I need to delete them all EXCEPT the ones that has the following features: ``` main_sec=118 main_sec=Companies type=SWOT ``` Here is the code I prepared, but somehow, it's deleting all the rows of the table: ``` DELETE FROM `swots` WHERE (main_sec <> '118') OR ...
It would be faster to insert the rows that you want to keep (assuming they are fewer then the remaining rows) in a new table like : ``` INSERT INTO main_sec_new SELECT * FROM main_sec WHERE main_sec IN ('118','Companies') and type = 'SWOT' ``` And then just drop the old table
``` DELETE FROM `swots` WHERE main_sec not in ('118', 'Companies') and type <> 'SWOT' ```
Delete all rows except specifics
[ "", "mysql", "sql", "sql-delete", "" ]
I am trying to update values in a MySQL table and really getting stuck. Basically I want to update a column's value to 1 where another column (in the same row) = "N". It should be quite simple but I can't fathom it. ``` UPDATE household SET allowsDogs=1 WHERE allowsCats="N" ``` In my mind the above query should, for...
The syntax you have specified is correct, and should work. I believe this is where you are getting tripped up: > But instead I get an empty result set. `UPDATE` queries do not return any result set. They do their work and then return an empty result set. However, your client library or application should provide a wa...
Presumably, you mean one of the following: ``` UPDATE household SET allowsDogs = 1 WHERE allowsCats = 0; ``` or ``` UPDATE household SET allowsDogs = 'Y' WHERE allowsCats = 'N'; ``` Mixing numbers and characters for flags is like, well, mixing cats and dogs.
How to update a MySql field based upon value of another field in the same record
[ "", "mysql", "sql", "" ]
I have a table with companies and one with categories. I'm using SQL Server Free Text search, and searching companies (by name and description) works fine. But now I also want to include the category table. I want to search for something like: `ABC 24 Supermarket`. Now, `ABC 24` should make a match with the `Name` co...
Imho the right way to do this is to create an indexed view containing the primary key of the main table ('company' in your example) and a second column containing all the stuff you're actually want to search, i.e. ``` create View View_FreeTextHelper with schemabinding as select CO.PrimaryKey, ...
If we assume that the name of columns are unique per row, then you can use below query. The following example returns all rows that contain either the phrase "ABC", "24" or "Supermarket" in each of the columns ``` DECLARE @SearchString nvarchar(100) = N'ABC 24 Supermarket' SET @SearchString = REPLACE(LTRIM(RTRIM(@Sear...
SQL Server Free Text search: search words from a phrase in two tables
[ "", "sql", "sql-server", "contains", "freetext", "" ]
I have two tables `users` and `distance`. In a page I need to list all users with a simple query such as `select * from users where active=1 order by id desc`. Sometimes I need to output data from the `distance` table along with this query where the user ID field in `users` is matched in the `distance` table in EITHER...
You need a left join between 'users' and 'distance'. As a result (pun not intended), you will always get the rows from the 'users' table along with any matching rows (if any) from 'distance'. I notice that you are using the SQL-89 join syntax ("implicit joins") as opposed to SQL-92 join syntax ("explicit joins"). I wr...
Use a left join ``` select a.*, b.distance from users a left join distance b on (b.userID_1=? and a.id=b.userID_2) or (b.userID_2=? and a.id=b.userID_1) where a.active=1 order by a.id desc ``` and use a prepared statement. Substituting text into a query is vulnerable to SQL Inject...
Not sure how to approach this with a mySQL query for two tables
[ "", "mysql", "sql", "" ]
I have two tables one I use to store `Album_Name` and other table I use to store `Album_Photos` I want to write a query so that it will get me following details ``` Album_Name Album_ID Album_Date ImageSmall Album One 1 2013-08-02 100.jpg Album Two 2 2013-09-09 55.jpg...
You are getting duplicate because there are multiple photos per album. To get one, use `row_number()`: ``` SELECT Album_Name AS Album_Name, a.Album_Date AS Album_Date, a.Page_ID AS PageID, p.Image_ID AS Image_ID, p.Image_Small AS Image_Small FROM Album_Name a left outer JOIN (select p.*, row_number() over...
I assume your Album table is called `Album` not `Album_Name` ``` SELECT .Album_Name AS Album_Name , a.Album_Date AS Album_Date , a.Page_ID AS PageID , p.Image_ID AS Image_ID , p.Image_Small AS Image_Small FROM Album a left outer JOIN Album_Photos p ON a.Album_ID = p.Album_ID WHERE p.Image_ID = ( SELECT MIN(Image...
Get Distinct rows from a result of JOIN in SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have read and retried rebuilding the below in many ways but to keep it clear I will show my last attempt. Aim - To get the Max value of column "UniqueID" The column field 'uniqueID' is set as a bigint I assume the error is in the line with addwithvalue in as I get "int" as the return value If I run the query `SEL...
I personally wouldnt mess around with the output parameter. Simply use ``` ALTER PROCEDURE [dbo].[spUniqueUserID] AS BEGIN SELECT MAX(UniqueID) FROM tblResults END ``` in your proc, and ``` Dim sqlConnection1 As New SqlConnection("Your Connection String") Dim cmd As New SqlCommand Dim returnValue As Object cmd...
Try with ``` command5.Parameters.AddWithValue("@UniqueID", 0L) ``` The AddWithValue determines the DataType of the parameter to pass to the underlying engine looking at the datatype of the second parameter. You pass a string and this is certainly wrong. In alternative you could define explicitly the parameter ``` ...
Returning Max with a stored procedure
[ "", "sql", "sql-server", "vb.net", "" ]
What query will count the number of rows, but distinct by three parameters? Example: ``` Id Name Address ============================== 1 MyName MyAddress 2 MySecondName Address2 ``` Something like: ``` select count(distinct id,name,address) from mytable ```
To get a count of the number of unique combinations of `id`, `name` and `address`: ``` SELECT Count(*) FROM ( SELECT DISTINCT id , name , address FROM your_table ) As distinctified ```
Get all distinct `id`, `name` and `address` columns and count the resulting rows. ``` SELECT COUNT(*) FROM mytable GROUP BY id, name, address ```
Count distinct value pairs in multiple columns in SQL
[ "", "sql", "count", "distinct", "" ]
I have the following query ``` with CTE as ( select Barkod, sum(kolicina) as Kolicina from stocks where Barkod = '555' group by Barkod ) select s.Barkod, s.Kategorija, s.Artikal, s.Opis, s.Kolicina, s.N_cena, s.N_Iznos, s.P_cena, s.P_Iznos, s.datum, s.Golemina from Stocks as s join CTE as b on b.Barkod ...
You're very close...just one last grouping. ``` select s.Barkod, s.Kategorija, s.Artikal, s.Opis, sum(s.Kolicina), s.N_cena, s.N_Iznos, s.P_cena, s.P_Iznos, s.datum, s.Golemina from Stocks as s group by s.Barkod, s.Kategorija, s.Artikal, s.Opis, s.N_cena, s.N_Iznos, s.P_cena, s.P_Iznos, s.datum, s.Golemina ``` Any o...
You need to find some way to aggregate the other columns. e.g. ``` select Barkod, sum(kolicina) as Kolicina, Max(Kategorija) as Kategorija, Max(Artikal) as Artikal, Max(Opis) as Opis, Max(N_cena) as N_cena, Max(N_Iznos) as N_Iznos, Max(P_cena) as P_cena, Max(P_Iznos) as P_Izn...
Getting correct result with Group By query in SQL Server
[ "", "sql", "sql-server", "" ]
I have 4 sql scripts that I want to run in a DACPAC in PostDeployment, but when I try to build the VS project for 3 of them I get this error: > Only one statement is allowed per batch. A batch separator, such as 'GO', might be required between statements. The scripts contain only `INSERT` statements in different tabl...
I have found the problem. When I added the file in VS I forgot to set `Build Action = None` from the file properties. So changing that fixed the problem and the project now compiles.
Regardless this seems to be pretty old I stuck for some hours with that as well and I think this way could be helpful for many. In `Database project`, files set as `Build` are considered as Database structure so just one statement is allowed in such file by design. `Go` nor any other batch terminator will change that ...
Error in SQL script: Only one statement is allowed per batch
[ "", "sql", "sql-server", "visual-studio-2012", "dacpac", "" ]
I have a data column which is in a datetime format. The date is shown like this: ``` 2013-09-07 00:00:00.000; 2012-12-09 00:00:00.000; 2013-08-19 00:00:00.000; ``` I want the date to be like this ``` 26-JUN-13; 08-FEB-12; 28-NOV-12; ``` I used following query: ``` select [003 AccptReg].[dbo].[SysDB].[st...
TRY THIS ``` SELECT CONVERT(varchar(50),(CONVERT(DATETIME,'2013-09-07 00:00:00.000')),106) ``` you don't need to convert into datetime as your column must be in same format
Use this query : ``` SELECT UPPER(REPLACE(CONVERT(CHAR(9), GETDATE(), 6), ' ', '-')) ``` This should solve your issue.
Convart varchar to date format with a twist
[ "", "sql", "sql-server", "type-conversion", "" ]
I have a single table which I need to pull back the 5 most recent records based on a userID and keying off of documentID (no duplicates). Basically, I'm tracking visited pages and trying to pull back the 3 most recent by user. Sample data: ``` ╔══════════════════════════════════════════════╗ ║UserID DocumentID Cr...
``` SELECT TOP 3 UserId, DocumentId, MAX(CreatedDate) FROM MyTable WHERE UserId = 71 GROUP BY UserId, DocumentId ORDER BY MAX(CreatedDate) DESC ```
You could try using a [CTE](http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx) and [ROW\_NUMBER](http://technet.microsoft.com/en-us/library/ms186734.aspx). Something like ``` ;WITH Vals AS ( SELECT UserID, DocumentID, ROW_NUMBER() OVER(PARTITION BY UserID, DocumnentID...
SQL Server Group By Order By Where
[ "", "sql", "sql-server", "sql-server-2008", "group-by", "sql-order-by", "" ]
Why do I get duplication of `Jim` in the results of the following? ``` CREATE TABLE #B (Name VARCHAR(10), Age INT) INSERT INTO #B values ('Jim', 21), ('Jim', 21), ('Jim', 19), ('Jim', 20), ('Nick', 20), ('Nick', 2), ('Nick', 20); SELECT DISTINCT Name, Age FROM #B A WHERE EXISTS ( ...
As the SQL Fiddle shows ([here](http://www.sqlfiddle.com/#!6/ee7c6/1)), your query is not doing what you think it is. Instead of getting the `max()`, it is fetching everything except the minmum. This version would get the `max()`: ``` SELECT DISTINCT Name, Age FROM B A WHERE NOT EXISTS ...
Because you have 2 rows corresponding ? ``` A.Age > B.Age and a.name = b.name ``` so ``` Jim 20 > Jim 19 Jim 21 > Jim 19 Jim 21 > Jim 20 ``` With the distinct, you get `Jim 20 and Jim 21` (as `Jim 21` are merged in one) **Solution without EXISTS** ``` select Name, Max(Age) FROM #B GROUP BY Name; ```
Using EXISTS to find rows with Maximum value
[ "", "sql", "sql-server", "" ]
Not sure what is going on here and why this is not working. I'm receiving the following error: "All expressions in a derived table must have an explicit name" - working with teradata. ``` select clm.c_clm ,clm.c_loc from (select * from pearl_p.TLTC900_CLM clm) as cl left join (select ...
Your max(av.d\_usr\_udt\_lst) in your subquery doesn't have an explicit name. You need to alias it like this: ``` max(av.d_usr_udt_lst) as "MaxThing" ``` So the query looks like ``` select clm.c_clm ,clm.c_loc from (select * from pearl_p.TLTC900_CLM clm) as cl left join (select max(av.d...
Apart from that error, you have another error in your join: ``` select clm.c_clm, clm.c_loc from (select * from pearl_p.TLTC900_CLM clm ) cl left join (select max(av.d_usr_udt_lst) from pearl_p.TLTC913_AVY av group by 1 ) as avy on cl.i_sys_clm = avy.i_sys_clm ---------------------...
Issue with subquery - All expressions must have explicit name
[ "", "sql", "teradata", "" ]
I have a table like this: **Email\_tbl**: ``` plcid Ecode ----------- ----------- 23 001646 24 001646 25 E004 25 2274 25 2208 25 1868 ``` I have another table `Employee`: ``` Ecode Ename E004 jaseem 2274 jasir 2208 deepu 1868 rupa 0016...
``` SELECT em.Ename FROM dbo.Email_tbl e JOIN dbo.EmployeeMaster_tbl em ON em.Ecode = e.ECode WHERE e.plcid = 25 ```
Why are you even joining the tables? And why are there 3 answers 'fixing' an unnecessary join? ``` SELECT em.Ename FROM dbo.EmployeeMaster_tbl em WHERE em.Ecode IN (SELECT Ecode FROM Email_tbl WHERE plcid = 25) ```
When joining tables duplicate data is being returned from SQL Server
[ "", "sql", "sql-server", "" ]
I want to apply the conditional where clause That is if my `barcode` parameter comes null then i want to fetch all the records and if it comes with value then i want to fetch only matching records for the second part i am able to fetch the matching records but i am stuck at fetching the all records in case of null valu...
I might have misunderstood what you ask, but the logic [OR](http://technet.microsoft.com/en-us/library/ms188361.aspx) operator might help: ``` SELECT item FROM tempTable WHERE @barcode IS NULL OR tempTable.barcode LIKE @barcode+'%' ``` If `@barcode` is `NULL`, it returns all the records, and when it is not `NULL...
I think you could simplify it to: ``` SELECT item FROM tempTable WHERE @barcode IS NULL OR tempTable.barcode LIKE @barcode+'%' ``` so when @barcode is null you'll get everything - i.e. the Like part of the where won't need to execute. If @barcode has a value then the Like will be executed.
Conditional where clause?
[ "", "sql", "sql-server", "sql-server-2008", "where-clause", "" ]
I have a database (change) which I am trying to create an sql report on the detail field value. The issue is that the detail value displays a "phrase" and I need to evaluate based on this phrase, or a part of it. SQL ``` SELECT * FROM change WHERE change.detail LIKE '%To: [Step Two]%' ``` I want it to display all of...
Presuming you're using SQL Server/TSQL, the problem you have is that [the square bracket characters have a special meaning:](http://technet.microsoft.com/en-us/library/ms179859.aspx) > [ ] Any single character within the specified range ([a-f]) or set > ([abcdef]). > > WHERE au\_lname LIKE '[C-P]arsen' finds author la...
If this is Microsoft SQL Server then you can escape brackets: ``` SELECT * FROM change WHERE change.detail LIKE '%To: \[Step Two\]%' ESCAPE '\' ``` Brackets used `LIKE` clause stand for a character range, So `[Step Two]` matches a character after `To:` that is either S,t,E,p, ,w, or o. You can read about this on [MS...
SQL LIKE for partial sentence value
[ "", "sql", "sql-like", "phrase", "" ]
I have troubles in combining concatenation with order by in Postgre (9.1.9). Let's say, I have a table borders with 3 fields: ``` Table "borders" Column | Type | Modifiers ---------------+----------------------+----------- country1 | character varying(4) | not null country2 ...
``` select country1 || '_' || country2 collate "C" as a from borders order by 1 ``` **`sql fiddle demo`** Notes according to discussion in comments: 1.) `COLLATE "C"` applies in the `ORDER BY` clause as long as it references the expression in the `SELECT` clause by *positional parameter* or *alias*. If you repeat th...
Just order by the two columns: ``` SELECT country1||'_'||country2 FROM borders ORDER BY country1, country2; ``` Unless you use aggregates or windows, PostgreSQL allows to order by columns even if you don't include them in the SELECT list. As suggested in another answer you can also change the collation of the combi...
Combining concatenation with ORDER BY
[ "", "sql", "postgresql", "sql-order-by", "concatenation", "collation", "" ]
I have a table with a set of data like ``` record_date | id | category | model | name | alternate_name ------------------------------------------------------------------- 9/1/2012 | N42 | X | ABC | blah | blah 10/1/2011 | N42 | Y | No Code | #N/A | #N/A 6/1/2012 | N42 | ...
Thank you for the suggestions however neither seemed to work quite right. I ended up doing this in two steps. ``` use myDB; drop table if exists tmp_myTable; create temporary table tmp_myTable like myTable; insert into tmp_myTable select * from myTable as t1 where record_date in (select max(record_Date) from myT...
Here is one method that uses three correlated subqueries: ``` update "table" t set model = (select model from "table" t2 where t2.id = t.id and t2.record_date < t.record_date and model <> 'No Code' order by t2.record_date limit 1), name = (select name from "table" t2 where t2.id = t.id and t2.record_date <...
MySQL query to fill in a table with other data from that table
[ "", "mysql", "sql", "" ]
I am trying to pivot on multiple columns. I am using SQL server 2008. Here is what I have tried so far ``` CREATE TABLE #t ( id int, Rscd varchar(10),Accd varchar(10),position int) INSERT INTO #t Values (10,'A','B',1) INSERT INTO #t Values (10,'C','D',2) Select id,[1],[2],[11],[12] FROM (SELECT id, Rscd,Accd, posit...
I would unpivot the columns into pairs first, then pivot them. Basically the unpivot process will convert the pairs of columns (`rscd`, `position` and `accd`, `aposition`) into rows, then you can apply the pivot. The code will be: ``` select id, [1], [2], [11], [12] from ( select id, col, value from #t cross app...
``` Select id,sum([1]),sum([2]),sum([11]),sum([12]) FROM (SELECT id, Rscd,Accd, position , position +10 as Aposition From #t) As query PIVOT (MAX(Rscd ) FOR Position IN ([1],[2])) AS Pivot1 PIVOT (MAX(Accd ) FOR Aposition IN ([11],[12])) AS Pivot2 group by id ```
SQL server Pivot on Multiple Columns
[ "", "sql", "sql-server", "pivot", "" ]
I get the error "Conversion failed when converting the nvarchar value '23,24,3,45,91,' to data type int." The error seems to be occuring on the ON clause. E.ID is an integer field while F.LegalIssue is a varchar field of integers separated by commas. Below is the code with that error. ``` SELECT F.[FDTitle], E.Primary...
If `LegalIssue` contains a string of comma-delimited numbers, then you really want an association table. Lacking that, here is a convenient (but not efficient) way to do the join: ``` SELECT F.[FDTitle], E.PrimaryOpID as [FD Primary OP ID], F.County as [FD County], F.Status as [FD Status], F.IssueDate as [FD Da...
Using xml datatype, you can explode your string to integers like this. Good candidate for a user defined function I would say :-) ``` declare @test varchar(max) set @test = '1,2,3,4,5' select T2.item.value('(./text())[1]','int') from (select convert(xml,'<items><t>'+replace(@test,',','</t><t>')+'</t></it...
T-SQL How to convert comma separated string of numbers to integer
[ "", "sql", "string", "delimited", "" ]
I will just go straight to the problem. This query is supposed to a list of records where PFlag is set to 'No' However, when I run it, I get blank results. If I remove the WHERE clause (where pFlag='No'), I get results. So, the WHERE clause is presenting a problem. Any idea what is wrong? Here is the code I am cu...
try rewriting the WHERE statement like this: ``` WHERE t.PFlag like '%No%' ``` hope it helps.
Check your table columns definitions. if the type of field `pFlag` is `CHAR` with particular length, e.g. `CHAR[4]`, then any string in that column will be filled up to 4 chars. In that case the real data stored in your table will be `No[space][space]`. If this is the case, convert your column type to `VARCHAR`, and ...
Does anyone know why I am not getting any results with this query?
[ "", "sql", "sql-server-2008", "sql-server-2005", "" ]
Essentially, my problem is that I need to run a query in Oracle that unions a static list of values ('Static' meaning it's obtained from somewhere else that I cannot get from the database, but is actually an arbitrary list of values I plug into the query) with a dynamic list of values returned from a query. So, my ini...
``` select '18776' as instanceid from dual union all select '18775' as instanceid from dual ``` or ``` select column_value from table(sys.odcivarchar2list('18776', '18775')) ``` or some sort of hierarchical query that could take your comma separated-string and split it into a set of varchars. Union these to your in...
I think you want to break it into two subqueries: ``` select * from ((select '18776' as instanceid from dual) union (select '18775' as instanceid from dual) union (<more complex query>) ) t; ``` Note that `union all` performs better than `union`. If you know there are no duplicates (or ...
Selecting static values to union into another query
[ "", "sql", "oracle", "oracle11g", "" ]
I am currently doing this tutorial (<http://sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial>) and I can't answer question 8 : **Some countries have populations more than three times that of any of their neighbours (in the same continent). Give the countries and continents.** .. and my current query won't be accepted as...
The issue with your query is that you're not excluding the "bigger" country itself from the result in the inner query. The correct query is: ``` SELECT x.name, x.continent FROM world x WHERE x.population > ALL( SELECT (y.population*3) FROM world y WHERE x.continent=y.continent AND x.name<>y.name ) ``` ...
Simple answer: ``` Select name, continent From world x Where population > all(Select max(population)*3 From world y Where x.continent = y.continent AND y.name != x.name) ```
SQLzoo, SELECT within SELECT tutorial
[ "", "sql", "" ]
I'm trying to count rows in a table `events` where a date in column `EventDate` occurs between two dates given in another table `customers`. CUSTOMERS ``` ID EventFrom EventTo -- ---------- ----------- 1 2011-01-01 2012-01-01 2 2012-12-10 2013-12-10 3 2010-05-01 2011-05-01 4 2011-01-01 2012-01-01 5 ...
[SQL Fiddle](http://sqlfiddle.com/#!2/b3819/2) **MySQL 5.5.32 Schema Setup**: ``` CREATE TABLE CUSTOMERS (`ID` varchar(2), `EventFrom` varchar(10), `EventTo` varchar(11)) ; INSERT INTO CUSTOMERS (`ID`, `EventFrom`, `EventTo`) VALUES ('1', '2011-01-01', '2012-01-01'), ('2', '2012-12-10', '2013-12-10')...
User `left join`. Put the date condition in the `on` clause. Then count the matches in the table using `count(e.ID)` (which counts non-NULL values): ``` SELECT c.ID, c.EventFrom, c.EventTo, COUNT(e.ID) as "Events" FROM customers c LEFT JOIN events e ON e.ID = c.ID and e.EventDate BETWEEN c.Eve...
MySQL count rows in one table based on dates in another table
[ "", "mysql", "sql", "" ]
I have an SQL query that is meant to select a list of things from different tables using a subquery. I am meant to find those things with the lowest value in a particular column. This is the query that i currently have. I know the minimum rate is 350 but i cant use it in my query. Any effort to change it to MIN(rate) ...
``` SELECT DISTINCT name FROM table1 NATURAL JOIN table2 WHERE table2.code = (SELECT CODE FROM RATE WHERE RATE=(SELECT MIN(RATE) FROM RATE)) ``` Considering you are expecting only one record of minimum value.
Most general way to do this would be ``` select distinct name from table1 natural join table2 where table2.code in ( select t.Code from rates as t where t.rate in (select min(r.rate) from rates as r) ) ``` if you have windowed functions, you can use [`rank()`](http://technet.micros...
SQL selecting minimum value in a sub query when exact value is unknown
[ "", "sql", "min", "" ]
Data transfer from Excel to SQL table. Before transfer i need to validate the data(basic data validation). 1. Want to check if ColT is not blank or not Null 2. Want to check if ColB is Integers only 3. Want to check if ColG is Alpha only. I kind of have an idea how to do this, using Staging tables before transferring...
You can do two things if you don't wanna go in script task. 1.get everything in database and then perform what ever check you want to do. 2.Else go for condition Split and check these condition and then only insert the record. Need any more help Shout. :)
I didn't get the complete answer but got a start.
SSIS data validation checks for data transfer
[ "", "sql", "ssis", "" ]
I have 2 tables, one that contains the final results I need, and another that contains the list of columns I need to select from based on a set level. For example : ``` table_levels level | name | [selected-columns] 1 | startdate | start_date 1 | end date | end_date 1 | contract | contract ``` So...
I got it to work by doing what @lobo said with a slight change. ``` DECLARE @listStr varchar(MAX); set @liststr = ( select [column] + ',' from dbo.columns where nwlevel = '1' for xml path('') ) DECLARE @query varchar(MAX); set @query = ( 'SELECT ' + LEFT(@listStr, LEN(@listStr)-1) + ' ...
My previous answer was for mysql. Since the tag has been updated on the question since then, here is the query for `sql-server-2008`. Build a list of columns from the values in `table_levels`, remove the last `,`, build a query string to get you the results from `table_results`, and then execute. ``` DECLARE @listStr...
Select columns from one table based on the column names from another table
[ "", "sql", "sql-server-2008", "" ]
The below is a practice for myself: I've created a table with some values, as: ``` CREATE TABLE my_test AS SELECT ROWNUM ID, TRUNC(SYSDATE)+(LEVEL*5/24/60/60)date_time , 111 person_id FROM dual CONNECT BY LEVEL <= (24*60*60)/5 ORDER BY 1; ``` Now, I updated table , `person_id = 222` for `date_time` between `5:30 am...
The `ORDER BY` clause is always the last to be interpreted in a single query, here however it is in a subquery so the main query `GROUP BY` will "overwrite" your `ORDER BY`. You could write for instance: ``` SELECT time_range, COUNT(DISTINCT person_id) PERSON_COUNT FROM (SELECT person_id, date_time, ...
First, you should have the `order by` in the *outer* query rather than the inner query. `order by` in inner queries is generally not guaranteed to work. But, even if you put: ``` order by date_time; ``` at the end, you still won't get what you want. For that, try ordering by the `date_time` itself, as in: ``` order...
Oracle query for time range
[ "", "sql", "oracle", "" ]
I have to query a table with few millons of rows and I want to do it the most optimized. Lets supose that we want to controll the access to a movie theater with multiples screening rooms and save it like this: ``` AccessRecord (TicketId, TicketCreationTimestamp, TheaterId, ShowId, MovieId, SeatId, ...
Try this: ``` select a.* from AccessRecord a where not exists( select 'next' from AccessRecord a2 where a2.movieid = a.movieid and a2.theaterid = a.theaterid and a2.showid = a.showid and a2.checkintimestamp > a.checkintimestamp ) ``` In this way you pick the last row as timestamp for the same ...
Using analytical functions may speed up the query, more specifically [ROW\_NUMBER](http://technet.microsoft.com/en-us/library/ms186734.aspx), it should reduce the number of reads: ``` WITH CTE AS ( SELECT TicketId, TicketCreationTimestamp, TheaterId, ShowId, MovieId, ...
Performance of SQL query
[ "", "sql", "sql-server", "performance", "datetime", "" ]
In reference to my [question](https://stackoverflow.com/questions/18695466/stored-procedure-confusion#18695836) I am trying this select statement and getting error ``` Select * From (SELECT * FROM FruitCrate WHERE FruitName IN (' +@FruitNames+ ')) WHERE FruitCrate.Eatable= 1 ``` Error > Incorrect syntax near t...
You can't pass a comma seperated string to the `in` operator. And you need just 1 query if you use `and` for the conditions. ``` exec('SELECT * FROM FruitCrate WHERE FruitName IN (' +@FruitNames+ ') and FruitCrate.Eatable= 1' ``` If you want to execute a dynamic query (which is the case here) that...
You should name your subquery as below ``` Select * From (SELECT * FROM FruitCrate WHERE FruitName IN (' +@FruitNames+ ')) tab WHERE tab.Eatable= 1 ``` and you shoud use the code as dynamic sql ``` exec('Select * From (SELECT * FROM FruitCrate WHERE FruitName IN (' +@FruitNames+ ')) tab WHE...
What's wrong with this SQL Statement
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have a table called EMP which has a column called JOB. Now, JOB column has various entries like CLERK, SALESMAN, MANAGER, etc. I want to fetch all rows(&columns) where JOB = 'CLERK' but instead of displaying 'CLERK' I want to display 'NEW CLERK'. I am not supposed to change the value in the table but display it diffe...
It is possible. Something like this should work: ``` select case JOB when 'CLERK' then 'NEW CLERK' else JOB end as JOB from your_table ```
One way to do this is with a CASE expression, for example: ``` SELECT CASE WHEN t.job = 'CLERK' THEN 'NEW CLERK' ELSE t.job END AS job , t.other_col FROM emp t ``` This will return the value from the `JOB` column, except replace occurrences of `'CLERK'` with the literal value of `'NEW CLERK'`. If you have sev...
How to format query result in Oracle?
[ "", "sql", "oracle", "select", "" ]
So I have a MySQL database that tracks events on a calendar. I have a table called calendar that has all the dates that concern me. At my job we have contracts that have certain values; for the sake of simplification we will use only 1 and 2. These contracts have a start date and a end date. I want to take all the cont...
``` SELECT calendar.datefield AS DATE, SUM(contract.time_slots) AS Slots_taken FROM contract RIGHT JOIN calendar ON calendar.datefield BETWEEN contract.start_time AND contract.end_time GROUP BY DATE LIMIT 600 , 30 ```
``` SELECT calendar.datefield date , SUM(contract.time_slots) slots_taken FROM calendar LEFT JOIN calendar ON calendar.datefield BETWEEN contract.start_time AND contract.end_time GROUP BY date LIMIT 600 , 30; ```
How to sum rows after paging?
[ "", "mysql", "sql", "" ]
I have a non clustered index I would like to drop (it is a duplicate of the clustered index). However, it is being used by a foreign key constraint. I would like to be able to identify which constraint is using the index, so I can update it to use the primary key index. When I try to drop it: ``` DROP INDEX [idx_dupl...
Something like ``` Select f.name, object_name(f.parent_object_id) From sys.foreign_keys f inner join sys.indexes i on f.referenced_object_id = i.object_id and f.key_index_id = i.index_id Where i.name = 'idx_duplicate' and i.object_id = object_id('[dbo].[MyTable]') ```
This will tell you the tables, the foreign key and the columns involved: ``` select f.name , parentTable = o.name , parentColumn = c.name , foreignTable = ofr.name , foreignColumn = cfr.name from sys.foreign_keys f inner join sys.foreign_key_columns fc on f.object_id = fc.constraint_object_id inner join sy...
How to find what foreign key references an index on table
[ "", "sql", "sql-server", "" ]
I have a problem in writing a query. I'd like to select the first row of each set of rows grouped My table is `Transactions`: ``` userID | Date | StoreID --------------------------- 1 | 8-9-2013 | 10 1 | 9-9-2013 | 10 1 | 10-9-2013| 20 2 | 7-9-2013 | 30 2 | 8-9-2013 | 10 2 | 9-9-20...
[SQL Fiddle](http://sqlfiddle.com/#!3/e536a/34) **MS SQL Server 2008 Schema Setup**: ``` CREATE TABLE Transactions ([userID] int, [Date] datetime, [StoreID] int) ; INSERT INTO Transactions ([userID], [Date], [StoreID]) VALUES (1, '2013-08-09 00:00:00', 10), (1, '2013-09-09 00:00:00', 10), (1, '20...
You could use Row\_Number(). ``` select UserId, Date, StoreId from (select row_number() over(partition by UserId order by date) as RowNumber, UserId, Date, StoreId from Transactions ) as View1 where RowNumber = 1 ``` <http://sqlfiddle.com/#!6/e536a/7>
How To get the First Row Form SQL Group Query?
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2005", "" ]
When I try and delete a movie from my database I get a the above error. I believe I have some how made the rated table have precedence over the films table. How do I make the film table have precedence of the rated table ``` DELETE FROM `film`.`films` WHERE `films`.`movie_id` =16 -- -- Table structure for table `fi...
The foreign key you have defined on `movie_id` by default restricts the deletion: with the current schema **you cannot delete a film as long as it has ratings.** You can automatically delete the ratings when you delete the film using *cascading delete*. Whether this is the best option for your application is for you t...
Since there is a foreign key constraint you have to first delete any child records before you can delete the parent.
Cannot delete or update a parent row
[ "", "mysql", "sql", "" ]
We restored databases to our `UAT` environment and set up `AlwaysOn`. Whenever I try and backup the log I'm getting "The log was not truncated because records at the beginning of the log are pending replication or Change Data Capture. Ensure the Log Reader Agent or capture job is running or use `sp_repldone` to mark tr...
The production database, which is what this DB was restored from, does have replication set up. Even though this copy was restored without any replication there was a transaction in the log still from prod. To fix this I set up a new publication with one table from the problem database, didn't even create a subscriptio...
Running the below solved the problem for us: ``` use myDB go EXEC sys.sp_cdc_enable_db go EXEC sys.sp_cdc_disable_db go EXEC sp_removedbreplication myDB ```
Log Can't be truncated but no CDCs or Replication exists
[ "", "sql", "sql-server", "" ]
I have a SQL Server table with several columns, an index starting from 1 as primary key. Now I need to clone this table but without the data and with a different index, let's say starting from 100 000. I have never done this before so I am quite unsure about how to do it. I know how to create a new table, ``` CREATE ...
`SQL Server` does not support `CREATE TABLE AS SELECT`. Use this ``` SELECT * INTO new_table FROM old_table ``` or ``` SELECT TOP 0 * INTO new_table FROM old_table ```
Try this ``` CREATE TABLE new_table AS SELECT TOP 0 * FROM old_table ```
SQL Server Express : clone table with a different index but without data
[ "", "sql", "sql-server-express", "" ]
I have two tables `TableA` and `TableB`. `TableA` has a column `newValue` and `oldValue`. `TableB` has a column `value`. I want the following result: get all the rows from `TableA` where `newValue` exist in `TableB` and `oldValue` not exist in `TableB`. Both tables has many rows so performance is important! How woul...
``` Select Distinct A.* From TableA A Inner Join TableB B on A.newValue = B.Value Where A.OldValue NOT In (Select Value From TableB) ```
I think avoiding `EXISTS` and `IN` helps with speed here: ``` SELECT * FROM TableA WHERE (SELECT TOP 1 1 FROM TableB WHERE value = newValue) IS NOT NULL AND (SELECT TOP 1 1 FROM TableB WHERE value = oldValue) IS NULL ```
SQL query - how to use exist and not exist conditions at the same time
[ "", "sql", "sql-server", "" ]
I've been reading up on how to use MySQL insert on duplicate key to see if it will allow me to avoid Selecting a row, checking if it exists, and then either inserting or updating. As I've read the documentation however, there is one area that confuses me. This is what the documentation says: > If you specify ON DUPLIC...
If I were you, I would make a primary key out of event\_id and user\_id. That will make this extremely easy with `ON DUPLICATE`. [SQLFiddle](http://sqlfiddle.com/#!2/39957/1) ``` create table attendance ( event_id int, user_id int, status varchar(100), primary key(event_id, user_id) ); ``` Then with ...
The quote includes "a duplicate value in a UNIQUE index". So, your values do not need to be the primary key: ``` create unique index attendance_eventid_userid on attendance(event_id, user_id); ``` Presumably, you want to update the existing record because you don't want duplicates. If you want duplicates sometimes, b...
MySQL "Insert ... On Duplicate Key" with more than one unique key
[ "", "mysql", "sql", "sql-insert", "on-duplicate-key", "" ]
I am attempting to migrate/update an old table that allowed a nullable varchar in a supposed "date" field. I want to find all rows that don't match this format: **`%e-%b-%y`**. How can I accomplish this query? \*\*EDIT: I should mention that the field does contain a few "CANCELLED", null, or other string values instea...
One more approach is to try to recover as much dates as possible with different formats using `STR_TO_DATE()` which will return `NULL` if extracted value is invalid and `COALESCE()` to chain different date formats. To show only rows with unrecoverable dates: ``` SELECT * FROM table1 WHERE COALESCE(STR_TO_DATE(NULL...
You can use regular expressions in MySQL; see <http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_not-regexp> Here's an expression that returns rows where the date field (dt) is null or does not match 1-2 digits + dash + 3 alphabetic characters + dash + 2 digits (for example, 06-Sep-13) ``` select * from tab...
Select all rows that dont match a date format?
[ "", "mysql", "sql", "" ]
I would like to have a model that belongs to another one. In my controller, I'd like to get all items in that model, but I want the attributes from the table it belongs to as well. For example: ``` class Comment extends Eloquent { public function post() { return $this->belongsTo('Post'); } } ``` ...
From the [documentation on eager loading](http://laravel.com/docs/eloquent#eager-loading): > Thankfully, we can use eager loading to drastically reduce the number of queries. The relationships that should be eager loaded may be specified via the with method [...] Using the `with()` parameter will use a **constant num...
If you want to get the results only with one query done on the background, without using `with()`, you can use `fluent` and `join()`. ``` SELECT * FROM comments LEFT JOIN posts ON comments.post_id = posts.id ``` is equal to: ``` DB::table('comments') ->join('posts','comments.post_id','=','posts.id','left') -...
Laravel 4 model with attributes from multiple tables
[ "", "sql", "join", "orm", "laravel", "laravel-4", "" ]
I'm trying to write a query to select users of a database whose birthdays are in the next 7 days. I've done a lot of research but I can't come up with a working solution. The birthday field is stored as a varchar eg '04/16/93' is there any way to work with this? This is what I have so far: ``` SELECT * FROM `PER...
To get all birthdays in next 7 days, add the year difference between the date of birth and today to the date of birth and then find if it falls within next seven days. ``` SELECT * FROM persons WHERE DATE_ADD(birthday, INTERVAL YEAR(CURDATE())-YEAR(birthday) + IF(DAYOFYEAR...
Its very easy and simple. No need to use any if conditions or anything else you just need to use DATE\_FORMAT() function of mysql. Here is my sql query that is ``` SELECT id,email ,dob FROM `users` where DATE_FORMAT(dob, '%m-%d') >= DATE_FORMAT(NOW(), '%m-%d') and DATE_FORMAT(dob, '%m-%d') <= DATE_FORMAT((NOW() + INT...
mySQL SELECT upcoming birthdays
[ "", "mysql", "sql", "database", "" ]
I'd like to view grants on redshifts. I found [this view for postgres](http://postgresql.1045698.n5.nabble.com/quot-SHOW-GRANTS-FOR-username-quot-or-why-z-is-not-enough-for-me-td5714952.html): ``` CREATE OR REPLACE VIEW view_all_grants AS SELECT use.usename as subject, nsp.nspname as namespace, c.relname as...
Another variation be like: ``` SELECT * FROM ( SELECT schemaname ,objectname ,usename ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'select') AND has_schema_privilege(usrs.usename, schemaname, 'usage') AS sel ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'insert') AND ha...
Something along the lines off: ``` select tablename, HAS_TABLE_PRIVILEGE(tablename, 'select') as select, HAS_TABLE_PRIVILEGE(tablename, 'insert') as insert, HAS_TABLE_PRIVILEGE(tablename, 'update') as update, HAS_TABLE_PRIVILEGE(tablename, 'delete') as delete, HAS_TABLE_PRIVILEGE(tablename, 'reference...
How do I view grants on Redshift
[ "", "sql", "amazon-redshift", "" ]
We at college are making an application to generate PDF document from Excel sheet records using Java SE. I have though about two approaches to design the database. In one approach, there will be one table that will contain a lot of records (50K every year). In other approach, there will be a lot of tables created (1000...
When building a relational database the basic rule would be to **avoid redundancy**. Look over your data and try to separate things that tend to repeat. If you notice a column or a group of columns that repeat across multiple entries create a new table for them. This way you will achieve the best performance when quer...
Multiple tables of identical structure almost never makes sense. Databases are designed to have many records in few tables.
Which database structure is efficient? One table with 10,000 records or 1000 tables with 10 records?
[ "", "sql", "" ]
I have a table with two columns, name and year of birth(from 1960-1980). How can I write a single sql query which lists each year and the number of people born that year? something like: ``` Year Number of people born 1960 5 1961 3 1962 4 ... .. 1980 4 ```
``` Select Year, Count(*) as 'Number of people born' From SomeTable GROUP BY Year ORDER BY Year ASC ```
``` SELECT YEAROFBIRTH, COUNT(*) FROM YOURTABLE GROUP BY YEAROFBIRTH ```
sql list number of people born every year
[ "", "sql", "" ]
I wanted to create a table using dynamic SQL. If I creates a table using ``` CREATE Table TodayTemp(id varchar(20)) DROP TABLE TodayTemp ``` Then there is no problem. It works fine. But problem using this is I can't create columns dynamically. Hence I tried using store create script in a variable and then finally ex...
Add parentheses around your variable when executing ``` Declare @CreateTableCmd varchar(max) SET @CreateTableCmd = 'CREATE Table TodayTemp (id varchar(20))' Exec (@CreateTableCmd) ^---------------^--------here ``` ## [SQLFiddle demo](http://sqlfiddle.com/#!3/fa387)
if you want to exec your script with exec, call it like this: ``` Exec (@CreateTableCmd) ``` Another way to do this is to use [sp\_executesql](http://technet.microsoft.com/en-us/library/ms188001.aspx) stored procedure: ``` exec sp_executesql @stmt = @CreateTableCmd ``` there're many links comparing this two approac...
Msg 2812 : "Create Table Using Dynamic Script"
[ "", "sql", "sql-server", "sql-server-2008", "dynamic-tables", "" ]
I have a phonenumber field like: ``` **phonenumbers** 0729643482 0723412678 0734231567 0745297334 0729643482 0720606706 0729643482 0720606706 ``` There are thousands of entries. I wanted to get top 10 phonenumbers with greatest count. this can be displayed as ``` **phonenumber count** 0729643482 3 072060670...
You don't need the rank function, you can use a normal count with `TOP 10`: ``` SELECT TOP 10 phonenumber, [count] = COUNT(*) FROM ozekiout GROUP BY Phonenumber ORDER BY [count] DESC; ``` If you want to include more than 10 results if there are ties e.g. ``` Phonenumber count 01111111111 18 01111111112 15 0...
Try this : ``` select phonenumber,Count(*) as count from ozekiout group by phonenumber order by count desc limit 10; ```
Get Count() for DISTINCT values for each field SQL Server
[ "", "sql", "sql-server", "" ]
Is there a way to count number of columns in a temp (#temptable) table in sql server ?
``` SELECT COUNT(*) FROM tempdb.sys.columns WHERE object_id = object_id('tempdb..#mytemptable') ```
**Query to get column counts for specified table** ``` SELECT Count(*) as cnt into #TempTable FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'TableName' ``` **Query to get column names for specified table** ``` SELECT COLUMN_NAME into #TempTable FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'TableName' ``` ...
Count of Columns in temp table in SQL Server
[ "", "sql", "sql-server", "" ]
I want to select some data using simple sql and insert those data into another table. Both table are same. Data types and column names all are same. Simply those are temporary table of masters table. Using single sql I want to insert those data into another table and in the where condition I check E\_ID=? checking part...
You can use merge statement if I understand your requirement correctly. [Documentation](http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm) As I do not have your table structure below is based on assumption, see whether this cater your requirement. I am assuming that e\_id is primary key or cha...
You could try this: ``` insert into table1 ( col1, col2, col3,.... ) SELECT col1, col2, col3, .... FROM table2 where (you can check any condition here on table1 or table2 or mixed) ``` For more info have a look [here](https://stackoverflow.com/questions/5907206/mysql-insert-into-tbl-select-from-another-table-and-...
How to select data and insert those data using single sql?
[ "", "sql", "database", "select", "insert", "oracle10g", "" ]
I have a database which is used to store information about different matches for a game that I pull in from an external source. Due to a few issues, there are occasional gaps (which could be anywhere from 1 missing ID to a few hundred) in the database. I want to have the program pull in the data for the missing games, ...
The idea is to look at where the gaps start. Let me assume you are using SQL Server 2012, and so have the `lag()` and `lead()` functions. The following gets the next `id`: ``` select t.*, lead(id) over (order by id) as nextid from t; ``` If there is a gap, then `nextid <> id+1`. You can now characterize the gaps usin...
I like the "gaps and islands" approach. It goes a little something like this: ``` WITH Islands AS ( SELECT GameId, GameID - ROW_NUMBER() OVER (ORDER BY GameID) AS [IslandID] FROM dbo.yourTable ) SELECT MIN(GameID), MAX(Game_id) FROM Islands GROUP BY IslandID ``` That query will get you the list of contiguous ...
Find all integer gaps in SQL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I want to `check date` in `between two dates` or can pass as a `NULL` using stored proc code ``` declare @fromDate date = null declare @toDate date = null select * from Mytable where date betweeen @fromDate and @toDate OR NULL (how to check for both parameters) ``` I have other 2 more parameters so irrespective wi...
Try with coalesce function as below ``` declare @fromDate date = null declare @toDate date = null select * from Mytable where date between coalesce(@fromDate,date) and coalesce(@toDate,date) ```
Pretty much convert your English to SQL: ``` where (date is null or date betweeen @fromDate and @toDate) ```
check date between two dates or NULL in sql
[ "", "mysql", "sql", "sql-server", "t-sql", "" ]
I am trying to join two tables based on whether or not a string from the first table is contained in part of a long string in the second table. I am using PROC SQL in SAS, but could also use a data step instead of a SQL query. This code works fine on smaller datasets, but rapidly gets bogged down since it has to make ...
This is a partial answer that makes it run 4-5X faster, but it isn't ideal (it helps in my case, but wouldn't necessarily work in the general case of optimizing a Cartesian product join). I originally had 4 separate index() statements like in my example (my simplified sample had 2 for A.first and A.last). I was able ...
The Cartesian product might be best for your data but here is something to try. What I am doing is using CALL EXECUTE() in a data step to build the step matching into a data step. This means you only have to tranverse each table once. However, you will have 4000 IF/THEN clauses in your written data step. Doing this bri...
Efficiently joining/merging based on matching part of a string
[ "", "sql", "sas", "" ]
I have a database table which holds error logs reported from an application. If certain errors occur, the application requires human intervention before becoming active again. I need to sort through the logs and determine the total amount of time that has accrued between every pair of events. So when the app goes in...
``` ;WITH x AS ( SELECT ErrorID, ErrorMessage, ErrorDateTime, rn = ROW_NUMBER() OVER (ORDER BY ErrorDateTime, ErrorID) FROM dbo.YourLogTable WHERE ErrorMessage IN ('ERROR', 'App Restarted') ) SELECT y.ErrorID, x.ErrorID, [Back_Up] = y.ErrorDateTime, SecondsDown = DATEDIFF(SECOND, y.ErrorDateTime, x...
The following query gets the restart time for each error: ``` select l.*, (select top 1 ErrorDateTime from logs l2 where l2.ErrorId > l.ErrorId and l2.ErrorMessage = 'App Restarted' order by l2.ErrorId ) as RestartTime from logs l where l.ErrorMessage = 'ERROR'; ``` ...
How can I determine down time from logs in database table
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have to get an instructor approval date from a table called section. If that table doesn't have the date (null), then I have to get a date from offering table, and even if that table doesn't have what I am looking for, then from Term table. AND if all three are null, then I need to get absoluteExpireDate in same man...
Given you're checking for null, you could use `Coalesce`: ``` select coalesce ( (select 1 a where 1=2) --returns null , (select 2 a where 2=3) --returns null , (select 3 a where 4=4) --returns result , 100 --default ) x ``` For me this would be cleaner / easier to read than a case statement, and I s...
a bit hard to say without having the whole query, what `a` stands for? Looks like your `case` is part of the bigger query, but ``` SELECT @dInstructApprDate = case when a.InstructorApprovalDate is null then ( select o.InstructorApprovalDate ...
Case within Case statement
[ "", "sql", "sql-server-2008", "case", "" ]
I had a table with almost 20000 records with columns ``` Id SubjectId UniqueId 1 54 1 1 58 2 1 59 3 1 60 4 2 54 5 2 58 6 2 59 7 2 60 8 2 60 9 3 ...
use `EXISTS()` ``` SELECT a.* FROM tableName a WHERE EXISTS ( SELECT 1 FROM tableName b WHERE a.ID = b.ID AND a.SubjectID = b.subjectID GROUP BY Id, SubjectId HAVING COUNT(*) > 1 ) ``` * [SQLFiddle Demo](htt...
You can utilize analytic `COUNT()` since you're using **SQL Server 2008** ``` SELECT id, subjectid, uniqueid FROM ( SELECT id, subjectid, uniqueid, COUNT(*) OVER (PARTITION BY id, subjectid) cnt FROM table1 ) q WHERE cnt > 1 ``` or another way ``` SELECT t.* FROM ( SELECT id, subjecti...
How do I find repeating records In a SQL table
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
I have a SQL server table in which there are 2 columns that I want to update either of their values according to a flag sent to the stored procedure along with the new value, something like: ``` UPDATE table_Name SET CASE WHEN @flag = '1' THEN column_A += @new_value WHEN @flag = '0' THEN colum...
The current answers are fine and should work ok, but what's wrong with the more simple, more obvious, and more maintainable: ``` IF @flag = 1 UPDATE table_name SET column_A = column_A + @new_value WHERE ID = @ID; ELSE UPDATE table_name SET column_B = column_B + @new_value WHERE ID = @ID; ``` This is much easi...
Something like this should work: ``` UPDATE table_Name SET column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END, column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END WHERE ID = @ID ```
if condition in sql server update query
[ "", "sql", "sql-server", "sql-server-2008", "stored-procedures", "" ]
I am having trouble finding the correct syntax to make this work? I have a table with the columns id and color and I want to print out all of the id's for a specific color. ``` if exists(select id from mytable where color = 'red') print id if exists(select id from mytable where color = 'red') print SCOPE_ID...
`PRINT` only prints one value. It looks like you want to loop through the results and print each value, which will require a cursor: ``` DECLARE @id INT DECLARE id_cursor CURSOR FOR SELECT id from mytable where color = 'red' OPEN id_cursor FETCH NEXT FROM id_cursor INTO @id WHILE @@FETCH_STATUS = 0 BEGIN PRIN...
id isnt defined. The id in the exists subquery doesnt exist outside that subquery. You could do this: ``` declare @id int; select @id = id from table_name; if (@id is not null) print @id; ```
Cannot access if exists select variable
[ "", "sql", "sql-server", "" ]
I have a multi-table join (only two shown in example) where I need to retain all rows from the base table. Obviously I use a LEFT JOIN to include all rows on the base table. Without the WHERE clause it works great – When a row doesn’t exist in the Right table the row from the Left table still shows, just with a 0 from ...
You are filtering on the second table in the `where`. The values could be `NULL` and `NULL` fails the comparisons. Move the `where` condition to the `on` clause: ``` SELECT 1.Label, COUNT(2.values) FROM Table1 1 LEFT JOIN Table2 2 ON 1.fk = 1.pk AND 2.Date BETWEEN 1/1/2010 AND 12/31/2010 GROUP B...
simply move the condition in `WHERE` clause to the `ON` clause. ``` LEFT JOIN Table2 2 ON 1.fk = 1.pk AND 2.Date BETWEEN '1/1/2010' AND '12/31/2010' ```
SQL Left Join losing rows after filtering
[ "", "sql", "left-join", "" ]
I have a table and I want to write a `query` which will give duplicate rows of that table based on the value of column `quantity` in that table. Suppose the table is one given below ``` name | quantity ------|---------- a | 1 b | 1 c | 3 d | 2 e | 1 ``` And I want to be able to write a `que...
try this: ``` With Ints(n) As (Select 1 Union All Select n + 1 From Ints Where n < 1000) Select t.Name, i.n from myTable t join Ints i on i.n <= t.Quantity option(MaxRecursion 1000) ```
Create a numbers table and do a join: ``` with numbers as ( select 1 as n union all select 1 + n from numbers where 1 + n <= 50 ) select t.name, numbers.n, t.quantity from t join numbers on t.quantity <= numbers.n; ``` This assumes the maximum quantity is 50. You could put ...
Add multiple rows in a SQL SELECT query
[ "", "sql", "sql-server", "t-sql", "select", "" ]
I have the following SQL, ``` SELECT TD.MyTempTableID ,TD.ID ,TD.Name ,TD.PhoneNumber ,TD.Featured ,TD.Price ,TD.Available ,TD.ModelNumber ,TD.Searchable ,TD.Brand ,TD.Tags ,TD.ShortDescriptions ,TD.Variations ,TD...
I would add a column to the temporary table `IsValid BIT DEFAULT(1)`. Next I would run each validation routine per column: ``` UPDATE MyTempTable SET IsValid = 0 WHERE IsNumeric(PhoneNumber) = 0 -- don't process rows that have already failed AND IsValid = 1 ``` Repeat the above for each column, replacing the WHERE c...
``` Declare @ID as varchar(500) Declare @Name as varchar(30) Declare @MOBILE as varchar(20) --AND OTHER vARUIABLE FOR oTHER FIELDS Declare MY_data CURSOR FOR SELECT TD.MyTempTableID ,TD.ID ,TD.Name ,TD.PhoneNumber ,TD.Featured ,TD.Price ,TD.Available ,TD.ModelN...
How to validate list of records in a SP?
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I have to prepare update statement dynamically in stored procedure based on 4 input variables. suppose take `test`, `test1`, `test2` and `test3` are input parameters. then I have to prepare query like ,please help me to build this: ``` update emp set empid='1' where test = test and test1 = test1 and te...
If there is a change that one or more parameters that you are passing in a procedure are going to be `NULL` you could write your `UPDATE` statement as follows. There is really no need of using dynamic SQL. In this example procedure's parameters are prefixed with `p_`: ``` update emp set empid='1' where (test = ...
Create a SQL statement based on your input parameters like ``` 'SELECT '||'Colum_nmae from table' || where var1=var2 ..... ``` then use execute immediate to execute this query
preparing update statement based on input parameters dynamically
[ "", "sql", "oracle", "" ]
In a Postgres DB, I need to filter a set of several hundred thousand rows in a table A by including only those rows for which an IP address column (of type inet) in the row matches any of several thousand IP address blocks (of type cidr) in another table B. I've tried various indexes on the inet addresses in the first ...
Case closed. To make things fast, do the following: * Use the ip4r types available from <http://pgfoundry.org/projects/ip4r>, as pointed out by user bma. This type supports indexing where Postgres's (up to Postgres 9.3) native ones don't. * Do not use the ip4r type directly, but expand it into lower and upper values a...
This is an old question but prominent in Google results, so posting my 2 cents here: With Postgres 9.4 and later you can use GIST indexes for inet and cidr: <https://www.postgresql.org/docs/current/static/gist-builtin-opclasses.html> E.g. the following query will use the gist index (assuming a table from MaxMind's fr...
Speeding up checking of IP address membership in CIDR ranges, for large datasets
[ "", "sql", "postgresql", "indexing", "ip-address", "cidr", "" ]
I've installed SQL Developer on my system. No connections are being shown in my system yet. How do I create a new connection. Must I create a database first? If yes, then how do I create a new database. The SQL Query Editor window is not opening because there is no connection. All of this because there is no database. ...
This tutorial should help you: [Getting Started with Oracle SQL Developer](http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/11g/r2/prod/appdev/sqldev/sqldev_mngdb/sqldev_mngdb_otn.htm) See the prerequisites: 1. Install Oracle SQL Developer. ***You already have it.*** 2. Install the Oracle Database. Downl...
1. Connect to sys. 2. Give your password for sys. 3. Unlock hr user by running following query: `alter user hr identified by hr account unlock;` 4. Then, Click on new connection 5. Give connection name as HR\_ORCL `Username: hr` `Password: hr` `Connection Type: Basic` `Role: default` `Hostname: ...
Creating a new database and new connection in Oracle SQL Developer
[ "", "sql", "oracle", "database-connection", "oracle-sqldeveloper", "" ]
I would like to group all the merchant transactions from a single table, and just get a count. The problem is, the merchant, let's say redbox, will have a redbox plus the store number added to the end(redbox 4562,redbox\*1234). I will also include the category for grouping purpose. ``` Category Merchant restauran...
The short answer is there is no way to accurately do this, especially with just pure SQL. You can find exact matches, and you can find wildcard matches using the `LIKE` operator or a (potentially huge) series of regular expressions, but you cannot find *similar* matches nor can you find potential misspellings of match...
You can use LIKE ``` SELECT COUNT(*) AS "COUNT", "BURGER KING" FROM <tables> WHERE restaurant LIKE "%king%" UNION ALL SELECT COUNT(*) AS "COUNT", "JACK IN THE BOX" FROM <tables> Where resturant LIKE "jack in the box%" ``` You may have to move the wildcards around depending on how the records were spelled out.
TSQL grouping on fuzzy column
[ "", "sql", "sql-server", "t-sql", "grouping", "fuzzy", "" ]
I have a set of records which store weekly events by using a datetime... `start_at` from the first week they began. It's not the REAL DATE, it's storing the DAY (DOW) and TIME, but is not the date I'm actually looking for. I'm trying to figure out how I can convert/abstract the `start_at` date in a way so using that ...
If I understand you correctly you may be over thinking it. If all you're looking for is a recurring datetime 24 hour before you could do something like: ``` SELECT * FROM events EXTRACT(dow FROM start_at) = 1 ``` Where 1 is the DOW (for Monday)... you abstract the DOW from the date ``` The day of the week as Sunday(...
If you mean the next 24 hours: ``` SELECT * FROM events WHERE start_at BETWEEN now() AND now() + INTERVAL '1 day' ``` If you mean the next 24 hour period starting at midnight (i.e. all day tomorrow): ``` SELECT * FROM events WHERE start_at BETWEEN now()::date + INTERVAL '1 day' AND now...
SQL abstract out date and find the next one this week
[ "", "sql", "postgresql", "postgresql-9.2", "" ]
I have a row in which two different teams are displace with their ID and name.I want to display them in a dropdown.For that I need to display them in a Format which is one above the other.THis is my query and the Image is the current result I am getting.. ``` SELECT Match_Schedule.Match_Serno as 'Id', FirstHomeTeam.Se...
You acheive this by doing an `UNPIVOT` on your `Match_Schedule` table and then doing a `JOIN` to the `Team_Detail` table to get the team name. ``` SELECT U.TeamID, TD.Team_Name FROM Match_Schedule UNPIVOT (TeamID FOR TeamName IN (HomeTeam, AwayTeam)) U JOIN Team_Detail TD ON U.TeamID = TD.Serno WHERE Match_Serno = 436...
You need to massage your data into producing two rows, then query those rows with an outer query like this: ``` SELECT Id, TeamID FROM ( SELECT Serno as ID, Team_Name as TeamID, 'H' as TeamType FROM Team_Detail WHERE Serno = (SELECT HomeTeam FROM Match_Schedule WHERE Match_Serno = 436) UNION ALL ...
Displaying values one above the other instead of in the same line which belong to the same row
[ "", "sql", "sql-server", "rows", "" ]
I’m trying to execute a query like this one: ``` SELECT (17 + 4) AS foo, foo * 2 AS bar; ``` It fails, returning `Unknown column 'foo' in 'field list'`. So I did this: ``` SELECT (@foo := 17 + 4) AS foo, @foo * 2 AS bar; ``` Which works. The problem now is that I want to integrate this computed value (`foo`...
I found the solution, it works using the `HAVING` clause instead of `WHERE`, like this: ``` SELECT (@foo := ipsum * 2) AS foo, @foo * 2 AS bar FROM lorem HAVING foo = 66; ``` Returns: ``` +------+------+ | foo | bar | +------+------+ | 66 | 132 | +------+------+ ``` With: ``` SELECT * FROM lorem; +-------...
Subselect! ``` SELECT foo , foo * 2 As bar FROM ( SELECT (17 + 4) AS foo ) As hey_look_at_me WHERE foo = 42 ```
Accessing SELECT's computed values in WHERE clause
[ "", "mysql", "sql", "" ]
I get an error;Invalid column name 'phase'. I've tried every permutation I can think of. ``` <cfargument name="locationFilter" default="" /> <cfargument name="educationFilter" default="" /> <cfargument name="workFilter" default="" /> <cfargument name="diversityFilter" default="" /> <cfargument name="ph...
try this ``` SELECT (case when datepart(year,getdate())-cast(yearstarted as integer) > 29 then '5' when datepart(year,getdate())-cast(yearstarted as integer) > 13 then '4' when datepart(year,getdate())-cast(yearstarted as integer) > 5 then '3' when datepart(year,getdate())-cast(yearstarted as in...
Your syntax is wrong. This code should run: ``` SELECT * FROM (SELECT case when datepart(year,getdate())-cast(yearstarted as integer) > 29 then '5' when datepart(year,getdate())-cast(yearstarted as integer) > 13 then '4' when datepart(year,getdate())-cast(yearstarted a...
Why SQL case isn't working
[ "", "sql", "sql-server-2008", "coldfusion", "case", "cfquery", "" ]
I want to store the top 2 results in 2 variables. ``` create table t(id int); insert into t (id) values (1),(2),(3),(4); declare @id1 int declare @id2 int select top 2 @id1 = first id, @id2 = next id from t ``` ## [SQLFiddle](http://sqlfiddle.com/#!6/89b4e/4) Can I do it in one query without usin...
``` declare @id1 int,@id2 int ;with cte as ( select top (2) id from t order by id ) select @id1 = min(id), @id2 = max(id) from cte select @id1,@id2 ``` **[Fiddle demo](http://sqlfiddle.com/#!3/d95e6/6)**
``` with cte as ( select top 2 id, row_number() over(order by id) as rn from t order by id ) select @id1 = (select id from cte where rn = 1), @id2 = (select id from cte where rn = 2) ``` or ``` with cte as ( select top 2 id, row_number() over(order by id) as rn from t order by id ) sel...
Select TOP 2 results in variables without loop
[ "", "sql", "sql-server", "sql-server-2008", "variables", "" ]
I'm trying to use Inner join on 2 tables sharing same column name. The first table is temp table but the column name equals the others table Primary key column name. How can I join between them without changing the names of the column (in the temp table of course)? ``` SELECT * FROM [dbo].[Apps] INNER JOIN #stats...
You need to specify the table in your `WHERE` clause: ``` WHERE Apps.AppId IN ``` You can also alias the tables, as shown below: ``` SELECT * FROM [dbo].[Apps] App INNER JOIN #statsForManagerApps on App.AppId = #statsForManagerApps.AppId WHERE App.AppId IN (SELECT AppId FROM [AppsForManagers] WHERE [Managerid] = @M...
You should specify all columns with table aliases as below ``` SELECT A.col1,A.col2, TA.col1,TA.col2 FROM [dbo].[Apps] A INNER JOIN #statsForManagerApps TA on A.AppId = TA.AppId WHERE A.AppId IN (SELECT AppId FROM [AppsForManagers] WHERE [Managerid] = @ManagerId) AND A.Enabled=1 ``` if yo really can't use table na...
SQL inner join on specified columns
[ "", "sql", "join", "" ]
The goal here is to: 1. Fetch the row with the most recent date from EACH store for EACH ingredient. 2. From this result, compare the prices to find the cheapest store for EACH ingredient. I can accomplish either the first or second goal in separate queries, but not in the same. How can i filter out a selection and th...
This question is really interesting! So, first, we get the row with the most recent date from EACH store for EACH ingredient. (It is possible that the most recent dates from each store can be different.) Then, we compare the prices from each store (regardless of the date) to find the least price for each ingredient. ...
This probably needs a couple of sub queries joined together. This isn't tested (as I don't have your table definitions, nor any test data), but something like this:- ``` SELECT i.name AS ingredient, ip.price, ip.date, s.name AS storename, b.name AS brandname FROM ingredient i INNER JOI...
MySQL Filter result again
[ "", "mysql", "sql", "" ]
In the Security/Users folder in my database, I have a bunch of security groups, include "MyApplication Users". I need to check if I am (or another user is) in this group, but I have no idea how to query for it or where I could see this information. I tried looking in the properties, but couldn't find anything. Any idea...
Checking yourself or the current user: ``` SELECT IS_MEMBER('[group or role]') ``` A result of 1 = yes,0 = no, and null = the group or role queried is not valid. To get a list of the users, try xp\_logininfo if extended procs are enabled and the group in question is a windows group : ``` EXEC master..xp_logininfo ...
For a quick view of which groups / roles the current user is a member of; ``` select [principal_id] , [name] , [type_desc] , is_member(name) as [is_member] from [sys].[database_principals] where [type] in ('R','G') order by [is_member] desc,[type],[name] ```
Check users in a security group in SQL Server
[ "", "sql", "sql-server", "security", "sql-server-2005", "active-directory", "" ]
I have two related tables, data(no, name, citycode, age) and city(code, city) Table city ``` +------+------------+ | code | city | +------+------------+ | A1 | Jakarta | | A2 | Bali | | A3 | Semarang | | A4 | Surabaya | | C1 | Dili | | C2 | Jayapura | | C3 ...
You need to remove the `WHERE` clause which causes to filter out records which has employee of age `27` only. `SUM(age = 27)` is a mysql specific statement only which basically summed up the boolean result of the expression. It can be further modified into using `CASE` which is a more RDBMS friendly, `SUM(CASE WHEN age...
I think you want the 'age' check inside the `ON` clause: ``` SELECT city.city , count(data.name) AS Nmb_of_employees FROM city LEFT JOIN data ON data.citycode = city.code AND data.age = 27 GROUP BY city.city; ``` Otherwise you correctly get the table (with blanks) but then filte...
bring all categories of data using where
[ "", "mysql", "sql", "" ]
I have to find a `SELECT DISTINCT [COL1] from {TABLE}` there can find all from [COL1] there have 'A' in [COL2] but not 'B' in [COL2] In this case '3' and '4' should be the result **TABLE** ``` [COL1] [COL2] ---- ---- '1' 'A' '1' 'B' '1' 'C' '2' 'B' ...
``` SELECT [COL1] from {TABLE} WHERE [COL2] = 'A' EXCEPT SELECT [COL1] from {TABLE} WHERE [COL2] = 'B' ``` Or ``` SELECT [COL1] FROM {TABLE} GROUP BY [COL1] HAVING MAX(CASE WHEN [COL2] = 'A' THEN 1 ELSE 0 END) = 1 AND MAX(CASE WHEN [COL2] = 'B' THEN 1 ...
``` SELECT DISTINCT [COL1] FROM {TABLE} t1 WHERE t2.[COL2] = 'A' AND NOT EXISTS ( SELECT 1 FROM {TABLE} t2 WHERE t2.[COL1] = t1.[COL1] AND t2.[COL2] = 'B' ) ```
SQL Server : SELECT DISTINCT [COL1] from {TABLE} WHERE [COL2] = 'A' AND [COL2] <> 'B'
[ "", "sql", "sql-server", "select", "distinct", "multiple-records", "" ]
Here's what I'm trying to do. Let's say I have this table t: ``` key_id | id | record_date | other_cols 1 | 18 | 2011-04-03 | x 2 | 18 | 2012-05-19 | y 3 | 18 | 2012-08-09 | z 4 | 19 | 2009-06-01 | a 5 | 19 | 2011-04-03 | b 6 | 19 | 2011-10-25 | c 7 | 19 | 2012-08-09 | d ``` ...
How about something like: ``` SELECT mt.* FROM MyTable mt INNER JOIN ( SELECT id, MIN(record_date) AS MinDate FROM MyTable GROUP BY id ) t ON mt.id = t.id AND mt.record_date = t.MinDate ``` This gets the minimum date per ID, and then gets the values based on those values. The only...
I could get to your expected result just by doing this in [mysql](/questions/tagged/mysql "show questions tagged 'mysql'"): ``` SELECT id, min(record_date), other_cols FROM mytable GROUP BY id ``` Does this work for you?
Group by minimum value in one field while selecting distinct rows
[ "", "sql", "group-by", "max", "distinct", "min", "" ]
UPDATE: Table and index definition ``` desc activities;x +----------------+--------------+------+-----+---------+ | Field | Type | Null | Key | Default | +----------------+--------------+------+-----+---------+ | id | int(11) | NO | PRI | NULL | | trackable_id | int(11)...
MySQL sometimes work weirdly so I will give this a shot. I'm assuming ID is Primary Key on users table. ``` SELECT act.trackable_type, act.recipient_id, act.recipient_type, max(act.created_at) as max_created_at, group_concat(act.owner_id order by act.created_at DESC) as owner_ids FROM activities act WHERE ...
I think you don't need `offset 0` at all, looks like you can live without subquery too. If you don't use fields from `users` table, you can use `in` (or `exists`) to make it clear: ``` select a.trackable_type, a.recipient_id, a.recipient_type, max(a.created_at) as max_created_at, group_concat(a.owner_id or...
mysql query optimization with multiple groupings or order by
[ "", "mysql", "sql", "query-optimization", "" ]
i have 2 table Table A and B Table A data --- ``` Enquiry_Id Ckeck_In check_Out Place 129 2013-09-20 2013-09-23 Delhi 130 2013-08-09 2013-08-10 Agra 130 2013-08-10 2013-08-12 Punjab 130 2013-08-12 2013-08-13 Haryana ``` Table B Data ``` Enquiry_Id Arrives_On ...
Trigger on TableB where you calculate difference between previous (`DELETED`) and updated (`INSERTED`) value and add that difference to your `TableA` columns. ``` CREATE TRIGGER tgTableBUpdate ON TableB AFTER UPDATE AS BEGIN UPDATE a SET a.Ckeck_In = DATEADD(DD, DATEDIFF(DD,d.Arrives_On, i.Arrives_On), a...
You can create an update trigger in the database on table B ``` CREATE TRIGGER trgAfterUpdate ON [dbo].[B] FOR UPDATE AS declare @ArrivesOn datetime; declare @id int; SELECT @id =i.Enquiry_Id, @ArrivesOn=Arrives_On from inserted i; -- perform update.insert here like -- Insert into A(Enqu...
update date full column on changing only one datafield
[ "", "asp.net", "sql", "sql-server", "sql-server-2008", "c#-4.0", "" ]